Java String Q&A

I’ve made a list of some common Java String questions I receive starting from extremely basic to more advanced questions.

What is String in Java?

String is a Class in java and defined in java.lang package. It’s not a primitive data type like int and long. String class represents character Strings. String is used in almost every Java application.

String str = new String("abc");
String str1 = "abc";

Further Use:
Here is an example method that will remove a given character from a String.

 private static String removeChar(String str, char c) {
        if (str == null)
            return null;
        return str.replaceAll(Character.toString(c), "");

Why using Char array for password storage is better than using String?

String is immutable in java and stored in String pool. Once it’s created it stays in the pool until garbage is collected, so even when we’re finished with a password it is still available in memory, and we don’t want that. This means anyone with access to the memory dump will have access to it, a big security no no.

So, by using char array for password storage, we can set it to blank once we are done with it. Also we can control how long it’s available in memory thus avoiding the security threat.

How do you check if two Java Strings are equal?

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 String 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 equals method to check if two Strings are equal or not.
There is another function equalsIgnoreCase that we can use to ignore case.

String s1 = "sethcodes";
String s2 = "sethcodes";
String s3 = new String("sethcodes");
System.out.println("s1 == s2 ? "+(s1==s2)); //true
System.out.println("s1 == s3 ? "+(s1==s3)); //false
System.out.println("s1 equals s3 ? "+(s1.equals(s3))); //true

What does the 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 equals(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.
This method always return a String that has the same contents as this string, but is guaranteed to be from a pool of unique strings.