Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

operators

 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
when i compile this code I got compile error.
Here at ////1

Do let me know why ???

public class haiii
{
public static void main (String[] args)
{
boolean b1 = false;
boolean b2 = false;
if (b2 != b1 = b2) ////1
{
System.out.println("true");
}
else
{
System.out.println("false");
}
}
}


If I change the above code at ////1 to below as it compiles fine

i dont understand why ...

public class haiii
{
public static void main (String[] args)
{
boolean b1 = false;
boolean b2 = false;
if (b2 = b1 = b2) ////1
{
System.out.println("true");
}
else
{
System.out.println("false");
}
}
}
 
manogna edintipal
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The '!=' operator has higher precedence than '=' operator

so the if condition evaluates to (booleanvalue)=variable.

this leads to the complie time error....
 
Thomas De Vos
stable boy
Ranch Hand
Posts: 425
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is one of those dangerous and easy to overlook assignments which can cause defects which cannot be traced back easily. Be careful please.

Anyway - for the purpose of the SCJP exam.

In your second code fragment the result of the assignment can be assigned to the variable b2.

However in the first example, the result of the variable cannot be assigned and as such the code won't compile.

It would have been legal to write:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic