File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why is it printing true? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why is it printing true?" Watch "Why is it printing true?" New topic

Why is it printing true?

Junaid Khan

Joined: May 24, 2002
Posts: 2
Hello all,

As per my understanding i==j evaluates to true
and as b is false the next thing should be (false= true) which should evaluate to false
and hence print false but it prints true.Can any please let me know where I am going wrong...
john sham

Joined: Jan 30, 2002
Posts: 6
The reason why it is printing true is that comparison (==) has higher precedence than assignment (=) operator.
As such, b=i==j will be evaluated first as:
i == j which is 10 == 10, which returns true.
The next operation is then
b = true, which is assigning true to b.
The final code is then read as:
So if (true) will print a "True".
Junaid Khan

Joined: May 24, 2002
Posts: 2
Thanks john got it....
[ May 24, 2002: Message edited by: Junaid Khan ]
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Keep in mind that = is an assignment operator. It does not do a comparison!
boolean a = true;
boolean b = false;
if (b = a) // will evaluate to true!
if (b == a) // will evaluate to false!

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
I agree. Here's the link:
subject: Why is it printing true?
It's not a secret anymore!