Study and learn Java MCQ questions and answers on Arithmetic Operators and their priorities. Attend job interviews easily with these Multiple Choice Questions.
Go through Java Theory Notes on Arithmetic Operators before studying questions.
What is the output of the below Java code snippet? int a = 2 - - 7; System.out.println(a);
Minus of Minus is Plus. So 2 - - 7 becomes 2+7.
What is the output of Java code snippet below? short p = 1; short k = p + 2; System.out.println(k);
Numbers are treated as int type by default. So an int value cannot be assigned to a short variable. You have to type cast the whole expression.
short k = (short)(p + 2);
What is the output of Java code snippet? short k=1; k += 2; System.out.println(k);
Compound assignment operators automatically convert the expression value to the left-hand side data type.
k = k + 1; //Error k += 1; //Works k++; //Works
What is the output of the Java code snippet? int a=5, b=10, c=15; a -= 3; b *= 2; c /= 5; System.out.println(a +" " + b + " " + c);
a = a - 3; b = b*2; c = c/5;
How do you rewrite the below Java code snippet? int p=10; p = p%3;
p=%3;
p%=3;
p=3%;
//Modulo Division operator // or simply Modulus Operator int a = 14%5; //a holds 4 5)14(2 -10 ------ 4
op++, op-- have more priority than --op, ++op.
a++ > ++b
All are having equal priority.
Again between Prefix and Post operators, Postfix operators have higher priority.
What is the output of the Java code snippet? int a=10, b=6; int c = a+b*5; System.out.println(c);
* has higher priority than +. So, Multiplication operation is performed first.
a+(b*5) 10 + (6*5) 10 + 30 40
What is the output of the Java code snippet? int a=10, b=5, c=3; int d = a+c/2*b; System.out.println(d);
/ and * have equal priority. So associativity of Left to Right is used. Remember that 3/2 is 1 not 1.5 as both operands are integers.
a+c/2*b a+(c/2*b) a + ( (c/2) * b) a + ( 3/2 * b) a + ( 1 * 5) 10 + 5 15
What is the output of the Java code snippet? int a=5, b=6; if(a++ == --b) { System.out.println("5=5"); } else { System.out.println("NONE"); }
At time of evaluating a++ == --b, a(5)is compared with --b(6-1). So, "if" condition passes. If you check a value after the ELSE block, it will be a+1 i.e 6.
What is the output of the Java code snippet? int a=6, b=5; if(++b == a--) { System.out.println("RABBIT"); } else { System.out.println("BUNNY"); }
After the ELSE block, b will be b+1 i.e 6
++b == a-- ++b == (a-1) b == (a-1) 5 ==5
What is the output of the Java code snippet? int a=10, b=20; int c = a++*2; int d = --b*2; System.out.println(c +"," + d);
The prefix is incremented or decremented immediately. Postfix incremented or decremented on the next line/statement.
1) a++*2 a*2 2) --b*2 (b-1)*2