File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Presidence in an IF statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Presidence in an IF statement" Watch "Presidence in an IF statement" New topic
Author

Presidence in an IF statement

jon ruane
Greenhorn

Joined: Mar 08, 2007
Posts: 13
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
Sheriff

Joined: Sep 28, 2004
Posts: 18117
    
  39

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
jon ruane
Greenhorn

Joined: Mar 08, 2007
Posts: 13
oooooooooooooooooooooooh!

thanks very much!
Urs Waefler
Ranch Hand

Joined: Mar 13, 2007
Posts: 77
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


SCJP 1.4
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Presidence in an IF statement
 
Similar Threads
Majji's mock exam doubt
Question by Sreenivasa Kumar Majji
operator precedence
operators
Majji Mock Exam # 1