String class and char

string class

The String class represents character strings. All string literals in Java programs, such as “abc”, are implemented as instances of this class.

Why is String immutable or final in Java?

Java StringBuilder and StringBuffer

Java String Pool / String literal pool / String interning

substring()

substring method is used to get parts of String in Java. It’s defined in String Class and is overloaded one which takes just beginIndex and returns part of String started from beginIndex till end. While other takes two parameter beginIndex and endIndex and returns part of String starting from beginIndex to endIndex-1.

  1. What will happen if beginIndex is equal to length in SubString(int beginIndex)?

    It won’t throw IndexOutOfBoundException. Instead it will return empty String. Same is the case when beginIndex and endIndex is same in case of second method. It will only throw StringIndexBoundException when BeginIndex is negative, larger than EndIndex or larger than length of String.

  2. How SubString works in Java?

    If you look substring method inside String class, you will figure out that it calls String (int offset, int count, char value []) constructor to create new String object. What is interesting here is value[], which is the same character array used to represent original string.

  3. So what’s wrong with this?

    If the Original string is very long and has array of size 1GB, no matter how small a Substring is, it will be backed up 1GB array. It also stop original string to be garbage collected in case if doesn’t have any live reference.

  4. How do you deal with this problem?

    Though you can not go and change substring method in java, you can still make some work around in case you are creating substring of significant longer String. Simple solution is to trim the string and keep the array-size according to substring length. Luckily String has constructor to do this.

    String listOfStockSymbolsOnNYSE = getStockSymbolsForNYSE(); //comma separated stock symbols from NYSE
    String apple = new String(listOfStockSymbolsOnNYSE.substring(appleStartIndex,appleEndIndex)); //calling String(string) constructor
    

    Another way to solve this problem is to call intern() method on substring, which will than fetch an existing string from pool or add it if necessary. Since the String in the pool is a real string, it only take space as much it requires. It’s also worth noting that substrings are not internalized when you call intern method on original method.

    Most developers successfully answers first three questions which is related to usage of substring. But they get stuck on last two. Its not completely their fault because what you know is that every time substring() returns new String which is not exactly true, since it’s backed by same character array.

char

A Java keyword used to declare a variable of type character.

Why character array is better than String for storing password in Java

Both Character array and String can be used to store text data

  1. Since Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since String are used in String pool for reusability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat. Since any one who has access to memory dump can find the password in clear text and that’s another reason you should always used an encrypted password than plain text. Since Strings are immutable there is no way contents of Strings can be changed because any change will produce new String, while if you char[] you can still set all his element as blank or zero. So Storing password in character array clearly mitigates security risk of stealing password.
  2. Java itself recommends using getPassword() method of JPasswordField which returns a char[] and deprecated getText() method which returns password in clear text stating security reason. Its good to follow advice from Java team and adhering to standard rather than going against it.
  3. With String there is always a risk of printing plain text in log file or console but if use Array you won’t print contents of array instead its memory location get printed. though not a real reason but still make sense.
    String strPassword="Unknown";
    char[] charPassword= new char[]{'U','n','k','w','o','n'};
    System.out.println("String password: " + strPassword);
    System.out.println("Character password: " + charPassword);
    String password: Unknown
    Character password: [C@110b053
    

Links to this note