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