Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes equality test for boolean Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equality test for boolean " Watch "equality test for boolean " New topic

equality test for boolean

lakshmisreenivas karri

Joined: Oct 31, 2003
Posts: 5
What is the result of executing the following fragment of code:
boolean flag = false;
if (flag = true) {
} else {

A. true is printed to standard out
B. false is printed to standard out
C. An exception is raised
D. Nothing happens
E. Compile error
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi Karri
The if(flag=true) always is true, there is not a compile error because flag is a boolean. So the answer is A.
lakshmisreenivas karri

Joined: Oct 31, 2003
Posts: 5
Thnx for the reply.
but why "if(flag=true)" is always true?
Could u gimme clear picture?
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Because flag=true is an assignment, not a comparison. Therefore it assigns true to flag and then returns the value of flag.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
lakshmisreenivas karri

Joined: Oct 31, 2003
Posts: 5
Yes I'm seeing it as an assignment but still i was stucked.
Ofcourse i got it now.
Thnx anyway.
I agree. Here's the link:
subject: equality test for boolean
Similar Threads
Q.52 from John Hunt
simple question
boolean question from John Junt Mock Exam