# Operator Precedence & Associativity

posted 13 years ago

- 0

I had a question about the result of this code from Mughal's Java Cert book (problem 3.17 p74)

public class Logic{

public static void main( String args[]){

int i = 0;

int j = 0;

boolean t = true;

boolean r;

r= (t & 0<(i+=1));

r= (t && 0<(i+=2));

r= (t | 0<(j+=1));

r= (t || 0<(j+=2));

System.out.println(i + " "+j);

}

}

Select all valid answers.

(a) The first digit printed is 1.

(b) The first digit printed is 2.

(c) The first digit printed is 3.

(d) The second digit printed is 1.

(e) The second digit printed is 2.

(f) The second digit printed is 3.

According to the answer in the back of the book, the correct answers are (c) and (d). I understand how the shortcircuited and logical operators work, but since "i+=" and "j+=" are in parenthesis, wouldnt they be executed first in each expression/line, making the correct answers (c) and (f)... I guess im getting the left to right associativity confused with the precedence.

Can anyone clarify this?

Thanks

Chad

public class Logic{

public static void main( String args[]){

int i = 0;

int j = 0;

boolean t = true;

boolean r;

r= (t & 0<(i+=1));

r= (t && 0<(i+=2));

r= (t | 0<(j+=1));

r= (t || 0<(j+=2));

System.out.println(i + " "+j);

}

}

Select all valid answers.

(a) The first digit printed is 1.

(b) The first digit printed is 2.

(c) The first digit printed is 3.

(d) The second digit printed is 1.

(e) The second digit printed is 2.

(f) The second digit printed is 3.

According to the answer in the back of the book, the correct answers are (c) and (d). I understand how the shortcircuited and logical operators work, but since "i+=" and "j+=" are in parenthesis, wouldnt they be executed first in each expression/line, making the correct answers (c) and (f)... I guess im getting the left to right associativity confused with the precedence.

Can anyone clarify this?

Thanks

Chad

Anonymous

Ranch Hand

Posts: 18944

posted 13 years ago

- 0

This seems to be the problem line:

For any expression 'X || Y', subexpression Y isn't evaluated at all if subexpression X happens to be true, no matter whether or not subexpression Y is parenthesized. So, if 't' happens to be true (which it is), expression '0 < '(j+=2) will not be evaluated.

For completeness, for any epxression 'X && Y', subexpression Y isn't evaluated at all if subexpression X happens to be false.

kind regards

**r= (t || 0<(j+=2));**For any expression 'X || Y', subexpression Y isn't evaluated at all if subexpression X happens to be true, no matter whether or not subexpression Y is parenthesized. So, if 't' happens to be true (which it is), expression '0 < '(j+=2) will not be evaluated.

For completeness, for any epxression 'X && Y', subexpression Y isn't evaluated at all if subexpression X happens to be false.

kind regards

I agree. Here's the link: http://aspose.com/file-tools |