Java Flashcards

1
Q

Is the String constant pool garbage collected?

A

Before Java 7, the JVM placed the Java String Pool in the PermGen space, which has a fixed size — it can’t be expanded at runtime and is not eligible for garbage collection.

The risk of interning Strings in the PermGen (instead of the Heap) is that we can get an OutOfMemory error from the JVM if we intern too many Strings.

From Java 7 onwards, the Java String Pool is stored in the Heap space, which is garbage collected by the JVM. The advantage of this approach is the reduced risk of OutOfMemory error because unreferenced Strings will be removed from the pool, thereby releasing memory.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Is it better to represent a password in memory as a String or as a character array?

A

Both String and Char[] array are used to store the textual data but choosing one over the other is more difficult. Maybe we can get the idea from the immutability of String why char[] array is preferred over String for storing sensitive information data like password, SSN, etc.

Using the plain string is a much higher chance of accidentally printing the password to logs or some other insecure places where char[] array is less vulnerable.
Since String is immutable, there is no method defined that allow us to change or overwrite the content of the string. This feature makes string objects unstable for storing secure information such as passwords, SSN, etc. We should always store the secure information in char[] array rather than String.
Since String is immutable if we store the password as plain text it will be available in memory until the garbage collector cleans it. Since string used String Constant Pool (SCP) for re-usability of a string, there will be a pretty chance that it will remain in memory for a long duration. Since anyone who has access to memory dump can easily find the password in plain text that’s another reason should use encrypt password than plain text.
If we notice in Java Swing applications, there is a method of JPasswordField getPassword() which return char[] and the deprecated method getText() which return the password in plain text. So java itself recommending to use the get password() method.
Another reason for storing a password in char[] array, because char[] can be sanitized, for example, after usage one can override a clear password with junk, while String is immutable in Java.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly