Reputation: 643
public class MyClass
{
public static void main(String args[])
{
Boolean b=false;
if(b=true)
{
System.out.println("TRUE");
}
if(b=false){
System.out.println("FALSE");
}
}
}
Although it might seem to be a very simple problem for the most of you, but i am unable to understand that when i run this code the output is TRUE.
Since =
is an assignment operator so therefore in both the cases it should come out to be true, since the values are assigned i.e. if(b=true) = true
(valid) and if(b=false) = true
(valid). And since there is no else condition in this therefore it should give both TRUE and FALSE as the outputs.
Upvotes: 1
Views: 135
Reputation: 1
The conditional statement must evaluate to a boolean type. Because of that, the value contained in b is automatically unboxed when the conditional statement is evaluated, and works the same way as the primitive type boolean works. So since if(b=true) is true, it returns the value. It evaluates as if(true) assigning the value of true to the variable b and if(b=false), assigning the value of false to the variable b and exiting since it is false.
Upvotes: 0
Reputation: 85
the inner part of if statement executes only when its true that is if (true) inner statement executes if(false) inner statement doesnt execute in the second if statement ur assigning false to b so it doesnt execute ...
Upvotes: 0
Reputation: 1669
if(b=false)
is different than
if(b == false)
if(b==false) checks if b is false than enters the if section, BUT if(b=false) aqssigns false to ba and then does not enter to the if section because it is false.
Upvotes: 0
Reputation: 10543
if(b=true)
means that true
value is set to b
and now in the bracket b
's value will be replaced, so JVM treats it like
if(true)
//variable b replaced with it's value.
That is why you are getting such output which is expected from JVM. =
is an assignment operator.
We must use ==
operator to compare boolean values.
Upvotes: 1
Reputation: 6242
The return value of such assignment is always a right-hand side of it. So result of (b=false) is false.
It is defined in the java language specification here http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26
At run time, the result of the assignment expression is the value of the variable after the assignment has occurred.
Upvotes: 5
Reputation: 387687
You are basically correct in what you think. However assignments do not return true if they succeed and false if they don’t succeed (actually, assignments cannot not succeed; invalid assignments would either be a syntax error or throw an exception).
Instead, assignments return the value that has been assigned.
So b = true
returns true
, and b = false
returns false
. That’s why the condition of your second if won’t be true.
Upvotes: 2
Reputation: 5554
if(b=false)
is evaluated as False. Here you are assigning the value of false to the variable b
. So it becomes if(false)
which means that if
block is not executed.
Upvotes: 2