Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

doubt

 
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
 
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
 
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.
 
    Bookmark Topic Watch Topic
  • New Topic