Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Presidence in an IF statement

 
jon ruane
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As i understand: Conditional operators have higher presidence over Assignment operators, as the following example code shows:

public class Q10
{
public static void main(String[] args)
{
int i = 10;
int j = 10;
boolean b = false;

if( b = i == j)
System.out.println("True");
else
System.out.println("False");
}
}

(Prints out "True")


What i cant understand is why a compliation error is not thrown at the fact a boolean variable is having an int assigned to it in the IF statement. It doesnt even look like a legal IF statemnt, but it is!

If you place the code:

b = i anywhere else, the compiler picks up this illegal assignment.

Is the assignment being ignored because the conditional side of the IF statement is the only part the compiler deals with?
 
Henry Wong
author
Marshal
Pie
Posts: 20905
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What i cant understand is why a compliation error is not thrown at the fact a boolean variable is having an int assigned to it in the IF statement. It doesnt even look like a legal IF statemnt, but it is!


The reason it works is because...

As i understand: Conditional operators have higher presidence over Assignment operators,


The boolean variable "b" is *not* being assigned the value of "i", it is being assigned the boolean value of whether "i" is equal to "j". In this case, it is assigned the value of true.

Henry
 
jon ruane
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oooooooooooooooooooooooh!

thanks very much!
 
Urs Waefler
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Try this one:

public class Q10
{
public static void main(String[] args) {
int i = 10;
int j = 10;
boolean b = false;

b = i == j;
System.out.println(b);


}
}

It works fine.

First it compares i & j. The resulat is true. Then it assigns true to b.

Regards
Urs
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic