Project Management Professional: Core Java Interview Questions!

Tuesday, July 21, 2020

Core Java Interview Questions!

29.Why Java provides default constructor ?

Ans. At the beginning of an object's life, the Java virtual machine (JVM) allocates memory on the heap to accommodate the object's instance variables. When that memory is first allocated, however, the data it contains is unpredictable. If the memory were used as is, the behavior of the object would also be unpredictable. To guard against such a scenario, Java makes certain that memory is initialized, at least to predictable default values before it is used by any code.

30.Why String is popular HashMap key in Java?

Ans. Since String is immutable, its hashcode is cached at the time of creation and it doesnt need to be calculated again. This makes it a great candidate for key in a Map and its processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.

31.Write a Program to check if 2 strings are Anagrams ?

{a word, phrase, or sentence formed from another by rearranging its letters: “Angel” is an anagram of “glean.” }

Check by sorting/equals method:

   

    public class CheckAnagram {

//a word, phrase, or sentence formed from another by rearranging its letters: “Angel” is an anagram of “glean.” 

public static void main (String[] args) throws java.lang.Exception

    {

        boolean result = isAnagram("now","own");

        System.out.println(result);

    }

    public static boolean isAnagram(String first, String second)

    {

        // remove all whitespaces and convert strings to lowercase

        first  = first.replaceAll("\\s", "").toLowerCase();

        second = second.replaceAll("\\s", "").toLowerCase();


        /* check whether string lengths are equal or not,

        if unequal then not anagram */

        if (first.length() != second.length())

        return false;


        // convert string to char array

        char[] firstArray = first.toCharArray();

        char[] secondArray = second.toCharArray();


        // sort both the arrays

        Arrays.sort(firstArray);

        Arrays.sort(secondArray);


        // checking whether both strings are equal or not

        return Arrays.equals(firstArray,secondArray);

    }

}

No comments: