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?
- String objects are immutable and there is a trick in s.trim( ) line.
- Understanding object references and unreachable objects that are eligible for garbage collection.
What follow on questions can you expect?
- 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.
- 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
- Core Java coding questions frequently asked in written tests and interviews - part 2 - == Vs equals()
- Core Java coding questions frequently asked in written tests and interview - part 3 - overload Vs override
- Core Java coding questions frequently asked in written tests and interview - part 4 -- iteration Vs recursion
- Reviewing a given Java code at job interviews and code review sessions
- Java coding question and answer on multi-threading
- Java OO interview questions and answers.
- Java coding interview questions and answers -- swapping, reversing a string, etc
- Can you write code by asking the right questions?
- Handling the programming question on the popular Fibonacci number.
- Java writing code -- compare two CSV files in Java.
- Working with Java Calendar and Dates - coding Q&A.
- Java Tree structure coding questions and answers : more tougher questions & answers for written tests