• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt

 
sunny
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank u. This clarifies my doubt.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic