wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt 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 "doubt" Watch "doubt" New topic
Author

doubt

sunny
Greenhorn

Joined: Feb 01, 2001
Posts: 23
boolean flag=false;
if(flag=true)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
The key answer is true.But I think answer is false.
Why is it so?Please clarify.Thanks in advance
Savithri Devaraj
Ranch Hand

Joined: Jun 26, 2000
Posts: 103
Originally posted by sunny:
boolean flag=false;
if(flag=true)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
The key answer is true.But I think answer is false.
Why is it so?Please clarify.Thanks in advance


Change Line 2 to ==, otherwise you are assigning true to flag, hence the result.
Savithri
Ankur Gupta
Ranch Hand

Joined: Jun 13, 2000
Posts: 66
Sunny,
The condition in an if statement should evaluate to be boolean. The statement "if (flag=true)..." is an assignment for flag but it results in a boolean value for the if statement. Therefore the answer is given as true.
Ankur
sunny
Greenhorn

Joined: Feb 01, 2001
Posts: 23
Hi savithri,
I amde a mistake.
ok.If we give as
if(flag==true)
How the answer is true.I think it should be false because flag is assigned to false.
Savithri Devaraj
Ranch Hand

Joined: Jun 26, 2000
Posts: 103
Originally posted by sunny:
Hi savithri,
I amde a mistake.
ok.If we give as
if(flag==true)
How the answer is true.I think it should be false because flag is assigned to false.

This code here
class abc{
public static void main(String args[]){

boolean flag=false;
if(flag==true)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
}
}
will printout false, it will not print true.
== tests for a value, = assigns a value. Assignment statements return the value assigned.
Hope this clarifies your doubt.
Savithri
sunny
Greenhorn

Joined: Feb 01, 2001
Posts: 23
Thank u. This clarifies my doubt.
 
GeeCON Prague 2014
 
subject: doubt