String Handling Interview Questions and Answers in Java - 3

Question: 11

Write a program to print all permutations of String?

We need to use recursion to find all the permutations of a String,

For example “AAB” permutations will be “AAB”, “ABA” and “BAA”.

We also need to use Set to make sure there are no duplicate values.

Question: 12

Why Char array is preferred over String for storing password?

String is immutable in java and stored in String pool. Once it’s created it stays in the pool until unless garbage collected, so even though we are done with password it’s available in memory for longer duration and there is no way to avoid it. It’s a security risk because anyone having access to memory dump can find the password as clear text.

If we use char array to store password, we can set it to blank once we are done with it. So we can control for how long it’s available in memory that avoids the security threat with String.

Question: 13

How can we make String upper case or lower case?

We can use String class to Upper Case and to Lower Case methods to get the String in all upper case or lower case.

These methods have a variant that accepts Locale argument and use that locale rules to convert String to upper or lower case.

Question: 14

How do you check if two Strings are equal in Java?

There are two ways to check if two Strings are equal or not – using “==” operator or using equals method.

When we use “==” operator, it checks for value of Strings as well as reference but in our programming, most of the time we are checking equality of String for value only.

So we should use equal method to check if two Strings are equal or not.

Related Questions