Jun 25, 2012

Core Java coding questions frequently asked in written tests and interviews - part 1: Immutability and object references

Core Java Coding Questions and Answers for beginner to intermediate level

Q1 Q2 Q3 Q4 Q5 - Q8 Q9 Q10 Q11 Q12 - Q14 Q15

Some core java questions are very frequently asked in job interviews and written tests to ascertain if you know the Java fundamentals. I have covered a few questions that are not covered in my books. These coding questions will also clear up the fundamentals.

Q1. What will be the output of the following code snippet?

String s = " Hello ";
s += " World ";
s.trim( );

A1. The output will be

" Hello  World "

with the leading and trailing spaces. Some would expect a trimmed "Hello World".
So, what concepts does this question try to test?
  1. String objects are immutable and there is a trick in s.trim( ) line.
  2. Understanding object references and unreachable objects that are eligible for garbage collection.
What follow on questions can you expect?
  1. You might get a follow on question on how many string objects are created in the above example and when will it become an unreachable object to be garbage collected.
  2. You might also be asked a follow on question as to if the above code snippet is efficient.
The best way to explain this is via a self-explanatory diagram as shown below.

If you want the above code to output "Hello World" with leading and trailing spaces trimmed then assign the s.trim( ) to the variable "s". This will make the reference "s" to now point to the newly created trimmed String object.

The above code can be rewritten as shown below

StringBuilder sb = new StringBuilder(" Hello ");
sb.append(" World ");
System.out.println(sb.toString().trim( ));

The StringBuilder is not a thread-safe class. It is fine when you are using it as a local variable. If you want to use it as an instance variable then use the StringBuffer class which is thread-safe. If you are curious to know what happens under the covers during String manipulation -- String concatenation

Relevant must get it right coding questions and answers


  1. In first illustration... comment line 3 and use System.out.println(s.trim());
    The output is same as II illustration "Hello World", note the extra space between these two words. (It should have ideally truncate the space like "Hello World".)

  2. Yes, you could do

    String s = " Hello ";
    s += " World ";
    System.out.println(s.trim( ));

    The main purpose of this question is to understand immutability and object references.

  3. It was really a nice article and i failed with ur question but m glad that i understood the concept

  4. "String objects are immutable and there is a trick in s.trim( ) line."

    I would thin the "trick" is in s += " World " since it makes it look like it's adding to the same String object while it is actually not.
    There's not trick in s.trim() - the method signature is public String trim(), so it's pretty clear that the trimmed object is returned.

  5. What you say above about the string being eligible for garbage collection is not correct and people should beware repeating this wrong information in an interview.

    In your example you create string literals. String literals are special objects in Java and they are stored in a string literal pool, which is NOT garbage collected. This is precisely why concatenating strings in a loop can lead to problems, as it fills up the string pool.
    Only strings created with new String(...) are garbage collected, since they're stored in the regular object heap.

  6. You are right jlem, and thanks for pointing this out.

    As per the JVM Spec, the area for storing string literals is in the "runtime constant pool". The runtime constant pool memory area is allocated on a per-class or per-interface basis, so it's not tied to any object instances at all for which heap memory is used for. The JVM has "permgen heap" containing all the reflective data of the virtual machine itself, such as class and method objects. A string literal created like String s = "Hello" is stored in "permgen heap" and a string object created like String s = new String("Hello"); is stored in heap.

    Under normal circumstances, String literals and other stuff in the permgen heap are not garbage collected. This means, the String literals are always reachable from the code that use them. However, I think the JVM can be configured to find and collect dynamically loaded classes that are no longer needed, and this may cause String literals to be garbage collected.

  7. In Java 7, the interned String (i.e. literals) are placed in the main heap space.

  8. thanks for removing the incorrect information from the page (I hope it's not in the books also).
    one more point, your phrase "permgen heap", even if you put it in quotes, is misleading, since the Permgen space is a separate area in the JVM that is NOT part of the heap.

  9. Actually, I now see that the incorrect information about garbage collection is still part of the graphics on this page. I wonder why you keep information that you know is incorrect.

  10. Here is what the JDK7 reference says:

    In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.

  11. This documentation uses the word "heap" in an unusual way. What is usually referred to as "heap" is what they call the "main Java heap". If your aim is to provide information for interviews it is best to use standards understood by everyone rather than rely on an obscure reference in Oracle JDK 7 documentation.
    (perhaps the explanation of this new vocabulary is that at some point in the development of JDK 7 the plan is to remove the Permgen space almost completely; see here: http://answerpot.com/showthread.php?3521332-Java+7+Perm+Gen)

    See here for an explanation of why Permgen needs to be separate from the heap:

  12. There are 4 objects that are created not 3.

    1) " Hello "
    2) " World "
    3) " Hello World "
    4) "Hello World"

    Thanks for writing the post. You idea is correct, string concatenation is inefficient.

  13. How to write a method, which recieved a number and return its 2's power?
    i.g. if passed number to method is 13 it should return 3 as 13=2^3+5.

  14. I have one doubt pls help me in this

    string s1="hi"
    string s2 ="hello"
    string s3=s1+s2
    s1 ="world"
    S3= s1+s2

    what will the output of s3 will now
    Pls ans this

    1. valueishihello

  15. Try the program by executing and see what happens. That is the best way to learn.

  16. what is the diff b/t class A and B
    class A
    int a;
    int b;
    public A()

    class B
    public B()
    int a=0;
    int b=0;

  17. There are 4 objects that are created not 3.

    another is " World "

  18. nice blog.. try to give ans of java codes in my blog

  19. String s1= "hi";
    String s2 ="hello";
    String s3=s1+s2;

    //It will print hihello

    // Now s1 previous value is elligble for garbage
    s1 ="world";
    s3= s1+s2;
    so bow output woul be //worldhello

  20. IMHO, there should not be any "frequently" asked interview questions to access someone's skills. A nice article though. :-)

  21. Your information is so helpful your giving brief information about the strings.I want to require more information on java.

  22. This comment has been removed by a blog administrator.

  23. Hi Arun sir,

    it is very good articles and help full for all of us. but my doubt is why string is immutable? what is the reason behind that.?

    1. The main reason is security so that passwords cannot be modified once constructed. Secondly, immutable objects are inherently thread-safe as they cannot be modified. Thirdly, it can be easily cached or reused.

  24. Thanks for sharing such a good information...

  25. Thank you provide valuable informations and iam seacrching same informations,and saved my time SAS Online Training