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
posted
0
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
posted
0
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
posted
0
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
posted
0
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