Enter your keyword

post

Java Precedence

Definition

Java has well-defined rules for specifying the order in which the operators in an expression are evaluated when the expression has several operators. For example, multiplication and division have a higher precedence than addition and subtraction. Precedence rules can be overridden by explicit parentheses.
Precedence order. When two operators share an operand the operator with the higher precedence goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher precedence than addition.

Example

public class Precedence {
public static void main(String[] args) {
System.out.println( 3 + 3 * 2 );
System.out.println( 3 * 3 - 2 );
System.out.println( 3 * 3 / 2 );
System.out.println("--");

System.out.println( 1 * 1 + 1 * 1);
System.out.println( 1 + 1 / 1 – 1);
System.out.println( 3 * 3 / 2 + 2);
System.out.println(“–“);

int x = 1;
System.out.println( x++ + x++ * –x );

x = 1;
System.out.println( x << 1 * 2 >> 1);

x = 0xf;
System.out.println( 0xf & 0x5 | 0xa );
}
}

Commonly asked interview questions on Constructors

1. Which of these have highest precedence?

a) ()
b) ++
c) *
d) >>

Answer: a
Explanation: Order of precedence is (highest to lowest) a -> b -> c -> d.

2What should be expression1 evaluate to in using ternary operator as in this line?
expression1 ? expression2 : expression3

a) Integer
b) Floating – point numbers
c) Boolean
d) None of the mentioned

Answer:c
Explanation: The controlling condition of ternary operator must evaluate to boolean.

3. What is the value stored in x in following lines of code? int x, y, z;
x = 0;
y = 1;
x = y = z = 8;

a) 0
b) 1
c) 9
d) 8

Answer: d
Explanation: None.

4. What is the order of precedence (highest to lowest) of following operators?

1. &
2. ^
3. ?:
a) 1 -> 2 -> 3
b) 2 -> 1 -> 3
c) 3 -> 2 -> 1
d) 2 -> 3 -> 1

Answer: a
Explanation: None.

5.Which of these statements are incorrect?

a) Equal to operator has least precedence.
b) Brackets () have highest precedence.
c) Division operator, /, has higher precedence than multiplication operator.
d) Addition operator, +, and subtraction operator have equal precedence.

Answer: c
Explanation: Division operator, /, has equal precedence as of multiplication operator. In expression involving multiplication and division evaluation of expression will begin from right side when no brackets are used.

Take Sample Test

Reference Books

1. Head First Java

No Comments

Add your review

Your email address will not be published.