aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes A nice question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A nice question" Watch "A nice question" New topic
Author

A nice question

Roel De Nijs
Bartender

Joined: Jul 19, 2004
Posts: 5545
    
  13

what's the output of the following program ?



[edit] if you want to know the solution (and explanation), just send me a PM, so the fun of other rangers won't be spoiled because solution is in the thread.
[ August 11, 2006: Message edited by: Roel De Nijs ]

SCJA, SCJP (1.4 | 5.0 | 6.0), SCJD
http://www.javaroe.be/
Ivan Rebrov
Ranch Hand

Joined: Jul 09, 2006
Posts: 30
what's the output of the following program ?


Cool! Wow!

And jet more interesting the following:


SCJP 5.0 - 95%<br />Preparing for SCWCD
Praveen Babu
Ranch Hand

Joined: Jul 30, 2006
Posts: 138
Its really a nice one.

Bye & Regards,
Praveen
Justin Yao
Greenhorn

Joined: Jun 16, 2006
Posts: 19
Hello all,
It is really interesting.
[ August 11, 2006: Message edited by: Yao Gao ]
Rachil Chandran
Ranch Hand

Joined: Mar 05, 2006
Posts: 67
Cool Question!!


SCJP2 96%
Amit Batra
Ranch Hand

Joined: Mar 04, 2006
Posts: 361
So are you going to tell us why?
Ivan Rebrov
Ranch Hand

Joined: Jul 09, 2006
Posts: 30
Originally posted by Amitabha Batranab:
So are you going to tell us why?


See this table of operator precedence in Java

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html

operator "==" has lower precedence then �perator "+"
Roel De Nijs
Bartender

Joined: Jul 19, 2004
Posts: 5545
    
  13

Full explanation

the first line outputs 'equals: true' (i think no explanation needed)
the second line outputs 'false', because the '+' operator has a higher priority then the '==' operator
==> so System.out.println("==: " + obj1==obj2); is equal to System.out.println(("==: " + obj1) == obj2); (pay attention to the braces)
so "==: SCJP" is compared with "SCJP" which returns false of cource

to get the expected output '==: true' you have to change it to
System.out.println("==: " + (obj1==obj2)); (again pay attention to the braces)
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: A nice question