Skip to main content

Java Fundamentals

Multiple Operators

So far, we've only used one operator at a time in our expressions. But there might be cases where we need to use multiple operators in a single line.

Let’s look at an example - 

class Main {
   public static void main(String[] args) { 
     int x = 6 / 2 + 4 * 8 - 2; 
     System.out.println(x); 
   }
}

Output

33

Explanation - 

       Step1 - First, the division (6 / 2) is calculated, resulting in 3.

       Step2 - Then, the multiplication (4 * 8) is done, resulting in 32.

       Step3 - Next, the addition (3 + 32) is performed, resulting in 35.

       Step4 - Finally, the subtraction (35 - 2) gives us 33.

In order to make code more readable, it’s good practice  to use parenthesis () when dealing with multiple operators in a single line. 

 The above can be written as - 

int x = (6 / 2) + (4 * 8) - 2;