JAVA ASSIGNMENT SOLUTION
1. Java's Five Arithmetic Operators
Java provides five basic arithmetic operators for performing fundamental mathematical operations.
These operators work with primitive numeric data types (such as int , float , double , etc.).
Example (int x =
Operator Operation Description
10, y = 3)
x + y results in
+ Addition Adds two values together.
13
Subtracts the right operand from the left x - y results in
- Subtraction
operand. 7
x * y results in
* Multiplication Multiplies two values.
30
Divides the left operand by the right operand. x / y results in
/ Division
(Performs integer division if both are integers). 3
Modulus Returns the division remainder of the left x % y results in
%
(Remainder) operand divided by the right operand. 1
2. Operator Precedence
Operator precedence determines the order in which operators are evaluated in a complex expression.
Operators with higher precedence are evaluated before operators with lower precedence.
If two operators have the same precedence level, their order of evaluation is determined by their
associativity (usually left-to-right for arithmetic operators).
General Hierarchy Table (From Highest to Lowest Precedence):
Precedence Level Operator Type Operators Associativity
1 (Highest) Parentheses / Postfix ( ) , x++ , x-- Left-to-right
2 Prefix / Unary ++x , --x , + , - Right-to-left
Page 1 of 3
Precedence Level Operator Type Operators Associativity
3 Multiplicative * , / , % Left-to-right
4 (Lowest) Additive + , - Left-to-right
3. Difference Between ++x and x++
Both ++x (Prefix) and x++ (Postfix) are increment operators that increase the value of the variable x
by 1. However, they differ significantly in how they return values when used inside an expression:
• Prefix Increment ( ++x ): The value of x is increased by 1 first, and then the new incremented
value is used in the expression.
• Postfix Increment ( x++ ): The current value of x is used in the expression first, and then the value
of x is increased by 1.
Code Example:
int x = 5;
int a = ++x; // x becomes 6, then a becomes 6. (Prefix)
int y = 5;
int b = y++; // b gets the current value 5, then y becomes 6. (Postfix)
4. Practical: Step-by-Step Evaluation
Given the expression:
result = 15 + 3 * 2 - 8 / 4 + (10 - 6) * 2;
We evaluate this step-by-step according to the operator precedence rules:
Step 1: Parentheses (10 - 6) have the highest precedence.
result = 15 + 3 * 2 - 8 / 4 + 4 * 2;
Step 2: Multiplication and Division have higher precedence than addition and subtraction.
We evaluate them from left to right.
First, evaluate 3 * 2 :
result = 15 + 6 - 8 / 4 + 4 * 2;
Next, evaluate 8 / 4 :
Page 2 of 3
result = 15 + 6 - 2 + 4 * 2;
Next, evaluate 4 * 2 :
result = 15 + 6 - 2 + 8 ;
Step 3: Addition and Subtraction have the same precedence. We evaluate them from left to
right.
First, evaluate 15 + 6 :
result = 21 - 2 + 8;
Next, evaluate 21 - 2 :
result = 19 + 8;
Finally, evaluate 19 + 8 :
result = 27 ;
Final Answer: result = 27;
Page 3 of 3