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

Relevant must get it right coding questions and answers



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( );
System.out.println(s);

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