What will the following Java code print? This is a little teaser/quiz. Enjoy!
public class JamesBond {
public static void main(String[] args) {
System.out.print("World's greatest spy is: ");
System.out.println('J' + 007);
}
}
Execute the code and see for yourself ! Some clues below.
Would it print:
- Joo7 (concat 'J' and 'oo7')
- J7 (007 is actually 7. So concat 'J' and 7)
- 81 (ASCII for 'J' is 74 and 74 + 7 ==> 81 )
- Q ('Q' is 7 characters after 'J')
Keith,
Since it is a simple program - all it takes is to save the given code into a .java file, compile and run :-) I thought it would be fun and instructive to actually run the code and experiment more.
--Sai Matam.
Posted by: Sai Matam | 06/02/2012 at 07:52 PM
The answer is actually #3. You should have done a quick test before answering. And Java supports Unicode, not ASCII. It so happens J = 74 in both standards.
Posted by: Keith | 06/02/2012 at 02:25 AM
Dan,
You are right. There is a difference in using "J" (a String) and 'J' ( a char). When I first encountered this, I was very surprised. I thought I would share with everyone.
regards,
Sai Matam
Posted by: Sai Matam | 05/06/2012 at 12:08 PM
You also get a different answer when using "J" versus 'J'.
However, in php you get the same answer regardless of "J" or 'J'.
Posted by: Dan | 05/06/2012 at 11:56 AM
Ans should be 4th option
Posted by: Sandeep | 05/06/2012 at 10:45 AM