" Hello World "
with the leading and trailing spaces. Some would expect a trimmed "Hello World". So, what concepts does this question try to test?
What follow on questions can you expect?
|
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.