• Recent Posts

  • Archives

  • Categories

  • Episode 5: Arithmetic operators

    Hello dear programmer. You have seen in a previous episode how to declare, initialize, modify and display an int variable. In that episode we have talked about one arithmetic operator: the addition operator. This episode is the continuation: you will see the rest of the arithmetic operators and the precedence rules that govern them. Fasten your seat belt and get ready :)

     Unary plus operator

    Until now we have seen two different uses of the + operator: to sum two numbers or to concatenate the String representation of its two operands (or arguments). Well, there is a third use, but don’t worry it will be the last one :) . This third use is different from the first and the second in that the plus sign is this time an unary operator: an operator which is applied to only one operand. Take a look at this program:

    1
    2
    3
    4
    5
    6
    7
    8
    
    public class Main 
    {
        public static void main(String[] argv) 
        {
            int money = +70;
            System.out.println("The amount of money is " + money);
        }
    }

    The result is obviously:

    The amount of money is 70

    Have you noticed the line :

    int money = +70;

    The new thing in it is the + sign preceding 70. This is the unary plus operator. Its only task is to indicate that the operand right next to it is positive. Actually the unary plus operator is always optional (you can always write 70 instead of +70). It’s just an indication or a decoration that a programmer may use.

    The most important with the + operator is to be able to distinguish between it’s three uses : addition, concatenation or unary plus here is a simple way, or algorithm, to do it :

     

    And remember that the compiler (the amazing software that reads the program) by default reads from left to right :) .

    Now let’s apply that to the following program and see if you can recognize each use of the + sign and predict the output on the screen:

    1
    2
    3
    4
    5
    6
    7
    
    public class Main 
    {
        public static void main(String[] argv) 
        {
            System.out.println(5 + +15 + " vs "+ +1 + 2);
        }
    }

    Answer:

    First we have 5 + +15 : The first + cannot be unary because it comes after the operand 5 (if it was unary then what on earth would be the significance of that 5 ?). So we have a + operator applied to two arguments which are 5 and +15. The second + is obviously unary because we have only one argument which is +15. And since both arguments are numbers then all we have to do is sum 5 and + 15 (which is the same as summing 5 and 15): the result is then 20.

    Next we have 20 + ” vs “: two arguments and one of them is not a number. It is then a concatenation and the result is the String “20 vs “.

    Next we have “20 vs ” +  +1: The first + is not unary since it is preceded by an argument. So it is a two arguments operator. And since the first argument is not a number it will be a concatenation of the String representation of the two arguments. The first argument is a String so its String representation is itself : “20vs “. The second argument is a number (+1) preceded by the optional unary plus operator, so its String representation is the number 1 as it is without any leading optional signs.  The result of the concatenation is then “20 vs 1″.

    In the same manner we have another concatenation leading to the following output on the screen:

    20 vs 12

    Unary minus operator

    In all the past examples we have dealt only with positive integers. But you know that in life we have highs and lows, and in numbers we have positive and negative :) . That’s why in Java we have the unary minus operator (-) in the same way that we have the unary plus operator (+). Only this time, the unary minus operator is not optional at all. The mathematical rule (or the common sense if you want) says that when you remove or add a minus sign to a number then what you are doing is changing the sign of the number from positive to negative or from negative to positive.

    Here is an example :

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    public class Main 
    {
        public static void main(String[] argv) 
        {
            int a = 55;
            int b = -23;
            System.out.println(-a + " " + b);
        }
    }

    The result is then :

    -55 -23

    First we have the concatenation  -a + ” “: variable a contains a positive number (which is 55) , but inside System.out.println it was preceded by the unary minus operator so the first argument of the concatenation becomes -55 and its String representaion is “-55″. Therefor the result is the String “-55 “.

    Finally we have “-55 ” + b which can be translated to “-55 ” + -23 : another concatenation resulting to “- 55 -23″.

    Subtraction operator

    This is the second and final use of the – operator: the usual subtraction operation, which needs two operands like the addition operation. Here is a simple example :

    1
    2
    3
    4
    5
    6
    7
    8
    
    public class Main 
    {
        public static void main(String[] argv) 
        {
            int sub = 9 - 5;
            System.out.println("value of sub : " + sub);
        }
    }

    The result is as expected :

    value of sub : 4

    9 – 5 is 4 isn’t it :)

    Now let’s see a little bit more sophisticated example :

    1
    2
    3
    4
    5
    6
    7
    
    public class Main 
    {
        public static void main(String[] argv) 
        {
            System.out.println(5 - 7 + 3 + -(5 + -11));
        }
    }

    answer :

    5 - 7 + 3 + -(5 + -11) → ((5 - 7) + 3) + -(5 + -11)
                           → (-2 + 3) + -(5 + -11)
                           → 1 + -(5 + -11)
                           → 1 + -(-6)
                           → 1 + 6

    The final result is then :

    7

    Multiplication operator

    In java the multiplication operator is * (not x or ×). It accepts two operands which must be numbers (or you will get a compilation error)  and returns their product.

    Example :

    1
    2
    3
    4
    5
    6
    7
    8
    
    public class Main 
    {
        public static void main(String[] argv) 
        {
            int mul = 7 * 3;
            System.out.println("value of mul : " + mul);
        }
    }

    Output :

    value of mul : 21

    Nothing unusual isn’t it ? But Here is the catch. Try the following program :

    1
    2
    3
    4
    5
    6
    7
    
    public class Main 
    {
        public static void main(String[] argv) 
        {
            System.out.println(9 + 2 * 3 - 4);
        }
    }

    Without further ado, when you have a mix of of additions, subtractions and multiplications, multiplication operations occur first, then additions and subtractions occur from left to right.

    Using the above rule you can deduce that 9 + 2 * 3 – 4 must be understood as (9 + (2 * 3)) – 4 and certainly not as (9 + 2) * (3 – 4):

    9 + 2 * 3 - 4 → (9 + (2 * 3)) - 4
                  → (9 + 6) - 4
                  → 15 - 4

    The final result is then :

    11

    Division operator

     The division operator is / (slash). It accepts two arguments (one on the left and one on the right :) ) and if they are integer numbers then the result is the quotient of the Euclidean division of the argument on the left by the argument on the right. For example suppose that you want to divide 13 by 2. We know that (mathematically speaking) 13 = 5 × 2 + 3 the quotient is then 5 because it is an integer division (without decimal point) . We will see non integer numbers in another episode.

    Here is the program illustrating the above example :

    1
    2
    3
    4
    5
    6
    7
    
    public class Main 
    {
        public static void main(String[] argv) 
        {
            System.out.println(13 / 2);
        }
    }

    And the result is :

    5

    An important thing to be aware of when you are dividing numbers is that you never want to devide a number by zero (do you :) ?). Anyway, if you do you will get an execution error (in Java it’s called an exception). Go ahead and try the following example :

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    public class Main 
    {
        public static void main(String[] argv) 
        {
            System.out.println("Begin");
            System.out.println(13 / 0);
            System.out.println("End");
        }
    }

    Here is what you will get in Eclipse :

    You can see on the console output that the first String “Begin” has been printed, while the two others have not. That’s because the line containing the 13 / 0 has made your program explode and exit right away. Eclipse has made that clear by giving you the type of the Exception (the error) and even the line at which the problem has occurred (Main.java:6). Actually it is a link that takes you to the exact line of the problem, which is very useful, especially when your program contains a lot more than three instructions :)

    Now consider the following example mixing division, multiplication, addition and subtraction :mrgreen: :

    1
    2
    3
    4
    5
    6
    7
    
    public class Main 
    {
        public static void main(String[] argv) 
        {
            System.out.println(5 + 39 * 5 / 7 - 40);
        }
    }

    The new rule here is that division is as important as multiplication. So they occur from left to right.Therefor here is how to simplify the above program :

    5 + 39 * 5 / 7 - 40 → (5 + ((39 * 5) / 7))) - 40
                        → (5 + (195 / 7)) - 40
                        → (5 + 27) - 40
                        → 32 - 40

    The multiplication here has occurred before the division simply because it is the leftmost between the two.

    And the final answer is as simple as :

    -8

    If we wanted to force the division of 5 / 7 then all we should have done is add parentheses :

    1
    2
    3
    4
    5
    6
    7
    
    public class Main 
    {
        public static void main(String[] argv) 
        {
            System.out.println(5 + 39 * (5 / 7) - 40);
        }
    }

    Here are the steps of simplification :

    5 + 39 * (5 / 7) - 40 → (5 + (39 * (5 / 7))) - 40
                          → (5 + (39 * 0)) - 40
                          → (5 + 0) - 40
                          → 5 - 40

    Notice that when you divide an integer number by a greater integer number then the quotient of the Euclidean division is always zero (in this example 5 = 0 * 7 + 5)

    Modulo operator

    In an Euclidean division there is a quotient, that you obtain in Java using the division operator, and a rest that you obtain using the modulo operator % (percent sign). For example 13 = 2 * 5 + 3 then the rest of the Euclidean division of 13 by 2 is 3. Try it in a program :

    1
    2
    3
    4
    5
    6
    7
    
    public class Main 
    {
        public static void main(String[] argv) 
        {
            System.out.println(13 % 2);
        }
    }

    The result is as expected :

    3

    Now let’s mix this new operator with the others and see who will win :) :

    1
    2
    3
    4
    5
    6
    7
    
    public class Main 
    {
        public static void main(String[] argv) 
        {
            System.out.println(1 - 2 * 3 % 4 / 5 + 6);
        }
    }

    Actually modulo operator has the same importance (or priority) as multiplication and division operators, so whoever is the leftmost wins :) . Provided that, here are the simplification steps :

    1 - 2 * 3 % 4 / 5 + 6 → (1 - (((2 * 3) % 4) / 5)) + 6
                          → (1 - ((6 % 4) / 5)) + 6
                          → (1 - (2 / 5)) + 6
                          → (1 - 0) + 6
                          → 1 + 6

    In the above example the multiplication happens before the modulo, and the modulo happens before the division.

    And the final result is :

    7

    Notice that using expressions like 1 – 2 * 3 % 4 / 5 + 6 is not a good programming habit. It is recommended to simplify things using parentheses to avoid any confusions or bad surprises :mrgreen:

    Summary of arithmetic operators priorities

    Very simple : multiplication, division and modulo are more important (or have higher precedence) than addition and subtraction. Add to that that inside the same category, it is the left most operation that has higher precedence.

    Again, even if you have to know these simple rules in order to be able to read a program, bear in mind that you don’t have to complicate things when yourself are writing a program. And as one professor I know used to say: “Intelligence is the art of simplifying” :) .

    What is next ?

    The next step is to learn the rest of Java primitive types, but before that you need to know about how numbers are represented on your computer. That’s what you will get next episode.  But until then, take your time to practice, practice and practice again what you learned so far in Java using Eclipse. Do not hesitate to go back to past episodes to clarify things; and if you still have any questions then there is always the option of leaving them as a comment that I will answer gladly.

    Goodbye and see you in the next episode :) .

    January 5, 2013 at 21:43 | Java tutorials| Be the first to comment this post

    Leave a Reply

    You must be logged in to post a comment.