Intent of my Blog
Today i was writing a piece of code and found one java puzzle. When i debugged it, i remembered that i read it something like this when i was reading Java(TM) Puzzlers: Traps, Pitfalls, and Corner Cases .
Java Puzzle
Today while doing my day to day office work i found one java puzzle which i thought was worth writing.
Can you guess what is the output of following java code:-
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
String[] arr = {"java ","puzzlers ","is ","a ","good ","book"};
String message = null;
for(String str : arr){
message += str;
}
System.out.println(message);
}
}
I am posting the answer as well as the solution to overcome this problem.But first try this java puzzler yourself.Run this piece of code in eclipse and see what you guessed is correct.
Answer
If you ran this code you will get nulljava puzzlers is a good book
but you might be thinking that it should print java puzzlers is a good book If you don’t know that when you are concatenating the string null is taken as a string and was appended to the result . + operator is overridden for string so it does the concatenation for you.
The Easiest Solution to this problem can be initializing message with empty string rather than null.
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
String[] arr = {"java ","puzzlers ","is ","a ","good ","book"};
String message = "";// replacing null with empty string
for(String str : arr){
message += str;
}
System.out.println(message);
}
}
But this solution also has a problem and that problem is related to performance because when you are iterating over array you are doing String using concatenation in a loop. In each iteration, the String is converted to a StringBuffer/StringBuilder, appended to, and converted back to a String.This can lead to decrease in performance of your program.
The best solution is the use of StringBuilder class.
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
String[] arr = {"java ","puzzlers ","is ","a ","good ","book"};
StringBuilder message = new StringBuilder();
for(String str : arr){
message.append(str);
}
System.out.println(message.toString());
}
}
If you think there is anyother better solution please put that in comment.