String Handling Interview Questions and Answers in Java - 2

Question: 6

How to convert String to byte array and vice versa?

We can use String getBytes() method to convert String to byte array and we can use String constructor new String(byte[] arr) to convert byte array to String.

Question: 7

Why String is popular HashMap key in Java?

Since String is immutable, its hashcode is cached at the time of creation and it doesn’t 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.

Question: 8

Explain the scenarios to choose between String, StringBuilder and StringBuffer?

If the Object value will not change in a scenario use String Class because a String object is immutable.

If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized (means faster).

If the Object value may change, and can be modified by multiple threads, use a StringBuilder because StringBuffer is thread safe (synchronized).

Question: 9

How to compare two Strings in java program?

Java String implements Comparable interface and it has two variants of compareTo() methods.

compareTo(String another String) method compares the String object with the String argument passed lexicographically.

If String object precedes the argument passed, it returns negative integer and if String object follows the argument String passed, it returns positive integer.

It returns zero when both the String have same value, in this case equals (String str) method will also return true.

compare ToIgnoreCase (String str): This method is similar to the first one, except that it ignores the case.

It uses String CASE_INSENSITIVE_ORDER Comparator for case insensitive comparison.

If the value is zero thenequalsIgnoreCase(String str) will also return true.

Question: 10

What does String intern() method do?

When the intern method is invoked, if the pool already contains a string equal to this string object as determined by the equal (Object) method, then the string from the pool is returned.

Otherwise, this String object is added to the pool and a reference to this String object is returned.

These method always return a String that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

Related Questions