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( ); 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?
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