Java Math: Addition, Subtraction, Multiplication, Division, Division Rest (module) and operator precedence

What the result of  1 + 2 x 2?
For us, it may be 5 or 6. To Java is always 5.

If you make the sum firstis 6: 1 + 2  = 3 and 3 x 2 = 6
If you make the product first, is 5: 2x2 = 2 + 1 = 5
And the computer? How it does ? And if it confuse too?

E 5 divided by 2?
2.5? To Java can be 2.5 or 2.

Math in Computer 

First, forget the 'x' as the multiplication sign, from now on is '*'.
Second, the division is represented by a '/'. For example, 4/2 = 2
Third, all in computing is math.

Moreover, computing comes from compute, ie count.
Even when you write in Java, the JVM (Java Virtual Machine) exchange information with the machine in a mathematical (in bits) way.
Even the images are divided into small blocks are numbered and each pad is painted with a color properly identified.

Guess how this identification? Of course, by numbers.
Or thought the machine would divide into 'emo pink', 'blue baby' or 'blue pool'?

Addition, Subtraction and Multiplication 

These three do not have a lot of difficulty. Are easy. You can add, subtract and multiply what you want.
At rigor, it is a sum.
Subtraction is a sum with negative numbers: a - b = a + (-b)
Multiplication is a sum repeated several times:  a * b = a + a + a + a ... + a (the 'a' is repeated 'b' times).

The following code asks for two integers (if aren't, have errors) and shows the result of addition, subtraction and multiplication, not secret:


import java.util.Scanner; 

public class Operations { 

    public static void main(String[] args) { 
        Scanner input = new Scanner(System.in); 
        int num1; 
        int num2; 
         
        System.out.print("Enter the first number:"); 
        num1 = input.nextInt (); 
         
        System.out.print("Enter the second number:"); 
        num2 = input.nextInt (); 
         
        System.out.println(); 
        System.out.println(num1 + "+" + num2 + "=" + (num1 + num2)); 
        System.out.println(num1 + "-" + num2 + "=" + (num1 - num2)); 
        System.out.println(num1 + "*" + num2 + "=" + (num1 * num2)); 
         
         
    } 
}

If not using integers (or whatever), I advise to use 'printf' because you can form the output.

Formatting with printf

A different way to display numbers is:
System.out.printf("number: %d", num1);

The last example would be:

import java.util.Scanner;

public class Operations {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int num1;
        int num2;
       
        System.out.print("Enter the first number:");
        num1 = input.nextInt ();
       
        System.out.print("Enter the second number:");
        num2 = input.nextInt ();
       
        System.out.printf("\n%d + %d = %d \n", num1, num2, num1 + num2);
        System.out.printf("%d - %d = %d \n", num1, num2, num1 - num2);
        System.out.printf("%d * %d = %d \n", num1, num2, num1 * num2);
       
       
    }
}


That is, the '%d' is replaced with the value of num1 or num2 or the other operation/variable.
To replace float variable values, use %f.

With multiplication and division of decimals, it can get messy because of the point. So let us add that '.2' between '%' and 'f', leaving %.2f .
This means that after the decimal point, print only two decimals. See:

import java.util.Scanner;

public class Operations {

    public static void main(String [] args) {
        Scanner input = new Scanner (System.in);
        float num1;
        float num2;
       
        System.out.print ("Enter the first number:");
        num1 = input.nextFloat();
       
        System.out.print ("Enter the second number:");
        num2 = input.nextFloat();
       
        System.out.printf ("\n%.2f + %.2f =%.2f \n", num1, num2, num1 + num2);
        System.out.printf ("%.2f - %.2f = %.2f \n", num1, num2, num1 - num2);
        System.out.printf ("%.2f * %.2f = %.2f \n", num1, num2, num1 * num2);
        System.out.printf ("%.2f / %.2f = %.2f \n", num1, num2, num1 / num2);
       
       
    }
}


Try taking the '.2' off and see the mess when you multiply and divide.

Division

Do not divide anything by zero. It does not exist.
It is no infinite or -infinity. It is a blurring mathematics.

Another detail that you should pay attention is the integer division. How much is 5/2?
We'll see what we mean by the Java program as follows:


import java.util.Scanner;

public class Operations {

    public static void main (String[] args) {
        Scanner input = new Scanner(System.in);
        int num1 = 5;
        intnum2 = 2;
       
        System.out.println(num1/num2);
       
       
    }
}

run:
2
BUILD SUCCESSFUL (total time: 0 seconds)

2?
"OMG, my computer is dumb!"

Calm, now test:
import java.util.Scanner;

public class Operations {

    public static void main (String [] args) {
        Scanner input = new Scanner (System.in);
        float num1 = 5;
        float num2 = 2;
       
        System.out.println (num1/num2);
       
       
    }
}

run:
2.5
BUILD SUCCESSFUL (total time: 0 seconds)


That is, whole divisions of return integer results. Even if the result 'real' was 2.999999, Java return only integer, which is 2, not 3.
In technical terms, the Java truncates the decimal part. Simply discards it.

Remainder of the division

Returning to the 5/2: if the transaction is made with integers, you know that the result is 2. However, there will be rest, which is 1.
Cause: 5 = 2 * 2 + 1

The rest of the division symbol is %.
Thus, 8 % 3 = 2.  Because: 8 = 3 * 2 + 2

In mathematics we call 'mod', module: 8 mod 3 = 2

That is the 'rest' that we let down in our counts:



Test:
public class Operations {

    public static void main (String[] args) {
       
        System.out.println(16 % 3);
       
       
    }
}


We'll see and we'll use the rest of the division enough on various problemas/algorithms.
For example, every even number leaves remainder of the division 0. This information is very important.


Operator Precedence and use of parentheses

Not to be confused and more than one possible outcome, Java adopts a precedence of their operators:

1st: Multiplication (*), division (/) and remainder of the division (%) are calculated first. If there are more than one in the same expression, Java enforces precedence as from left to right of the expression.

2: Addition (+) and Minus (-) after the above operators are calculated, these are calculated. If there are more than one in the same expression, Java enforces precedence as from left to right of the expression.

Not to be confused and to always make your code more clear, separate expressions with parentheses. For example, as calculated average of the numbers a and b?
a + b / 2 -> wrong
(a + b) / 2 -> right

The parentheses form a block. It's as if you were in there were calculated separately.

In the example from the beginning of this chapter: 1 + 2 * 2
Depending on what you want, break in on parantêses that will fit.

See:
1 + 2 * 2 = 5 (precedence of * before + , in Java)
(1 + 2) * 2 = 6
1 + (2 * 2) = 5

It is easy to see that is more clear and organized with the use of parentheses.

Exercises:
1. Create a program that receives yours three grades (high school or college) and calculates the average.
2. Create a program that receives the height and weight of the user, and tell your BMI (Body Mass Index), given by:



Learn how to perform the operations add, subtract, multiply, divide and calculate the rest of the division in Java. Besides knowing the precedence of operators.



No comments: