Saturday, July 4, 2009

String puzzle

A short, but interesting puzzle.

Question
What does the following program print:



Answer
When you run the code, you get the answer: 2.

Why?
The compiler translates Unicode escapes into the characters they represent before it parses the program into tokens, such as strings literals. As you see, NetBeans IDE doesn't know it, it present the code like a string with a length() method.

4 comments:

Gabor Garami said...

There is a bug in your code, the closing " is on wrong place in L23.

I think you think:

System.out.println("a\u0022.length() " + "\u0022b".length());

Peter Szilagyi said...

Hello. This isn't a bug. Copy my code and check the result. It will be 2!
Before the code runs, the \u0022 unicode character code is transformed to " and the program run in this form:
System.out.println("a".length() + "b".length());

The code written by you isn't compile for me!

Anonymous said...

you have a nice site.thanks for sharing this site. various kinds of ebooks are available here

http://feboook.blogspot.com

vivekcis said...

nice post. Unicode has special features. However as i am an asp .net programmer and i faced the same situation in .net also.