Alex Rivera | Logout

How many string objects in Java?

Asked 2013-07-27T13:17:38.510
38

My friend sent me a question he saw in one mock exam for the Java certification about string objects:

String makeStrings(){
    String s = "HI";
    s = s + "5";
    s = s.substring(0,1);
    s = s.toLowerCase();
    return s.toString();
}

How many string objects will be created when this method is invoked? The correct answer the exam gave was 3. But I think it's five.

  1. "HI"
  2. "5"
  3. "HI5"
  4. "H"
  5. "h"

Am I wrong?

Edit
Report

1 Answer

9

Some of the other answers do make sense, but what about the string literal?

String s = "HI";

For the string literals, when a .java file is compiled into a .class file, any string literals are noted in a special way, just as all constants are. When a class is loaded (note that loading happens prior to initialization), the JVM goes through the code for the class and looks for string literals.

When it finds one, it checks to see if an equivalent String is already referenced from the heap. If not, it creates a String instance on the heap and stores a reference to that object in the constant table

Once a reference is made to that string object, any references to that string literal throughout your program are simply replaced with the reference to the object referenced from the string literal pool.

Hence there should be four Java objects, although when the same method is called again and again then there would only be three objects as in the application the string literal pool contains the literal "HI".

Also, for more information on why new objects are created when the above method blocks are exectued we can also check the hash codes which are different for different strings (String being immutable.)

  public static void main(String[] args)
  {
      NumberOfString str = new NumberOfString();
      String s = str.makeStrings();
      System.out.println(s.hashCode());
  }

  public String makeStrings()
  {
      String s = "HI";
      System.out.println(s.hashCode());
      s = s + "5";
      System.out.println(s.hashCode());
      s = s.substring(0, 1);
      System.out.println(s.hashCode());
      s = s.toLowerCase();
      System.out.println(s.hashCode());
      return s.toString();
  }

You get the following output:

2305
71508
72
104
104

Should we not count in the String literal object in t

answered 2013-07-29T05:36:16.770

Your Answer