Java Puzzlers are found in day to day work


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.

5 thoughts on “Java Puzzlers are found in day to day work”

  1. Thanks for posting an explanation to this puzzle. I realize your request for “better solution” probably was not a call for third party libraries to use, but I would still like to mention one I’ve found very useful in this context and many others: Google Collections: http://code.google.com/p/google-collections/

    Here’s a sample of how the above mentioned library could be used:

    import com.google.common.base.Joiner

    String[] arr = {“java”,”puzzlers”,”is”,”a”,”good”,”book”};
    String message = Joiner.on(” “).join(arr);
    System.out.println(message);

  2. Excellent site, keep up the good work. I read a lot of blogs on a daily basis and for the most part, people lack substance but, I just wanted to make a quick comment to say I’m glad I found your blog. Thanks, 🙂

    A definite great read.. ..

    -Bill-Bartmann

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: