The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators:

Assume integer variable a = 10 and variable b = 20, then:

Operator Description Example
+ Addition - Adds values on either side of the operator a + b will give 30
- Subtraction - Subtracts right hand operand from left hand operand a - b will give -10
* Multiplication - Multiplies values on either side of the operator a * b will give 200
/ Division - Divides left hand operand by right hand operand b / a will give 2
% Modulus - Divides left hand operand by right hand operand and returns remainder b % a will give 0
++ Increment - Increases the value of operand by 1 b++, ++b gives 21; equivalent to b = b +1;
-- Decrement - Decreases the value of operand by 1 b-- , --b gives 19; equivalent to b = b-1;

The Shorthand Assignment Operators:

These are the shorthand assignment operators supported in Java:

Examples

Operator Description Example
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand c += a
is same as
c = c + a
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand c -= a
is same as
c = c - a
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand c *= a
is same as
c = c * a
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand c /= a
is same as
c = c / a
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand c %= a
is same as
c = c % a

Points to remember!

  • The result of any division operation is a double type
  • Use shorthand notations where ever possible
  • Java uses the standard PEMDAS (Parenthesis, Exponents, Multiplication and Division, Addition and Subtraction) order when evaluating several operators in the same expression. When there are multiple instances of the same precedence, Java reads from left to right.

The Relational Operators

Following are the relational operators supported in Java language. The result of a relational operator is a boolean value, true or false. The operands for this operator can be any variable or an expression.

Assume variable a = 10 and variable b = 20, then:

Examples

Operator Description Example
== Checks if the values of two operands are equal or not, if yes then condition becomes true. (a == b) is false.
!= Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (a != b) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (a > b) is false.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (a < b) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (a >= b) is false.
< = Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (a < = b) is true.

The Logical Operators

Logical operators are applied to booleans only. Either it is a variable which holds a boolean value or a relational expression which evaluates to a boolean value. The following table lists the logical operators:

Assume Boolean variables c = true and variable d = false, then:

Examples

Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (c && d) is false.
|| Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true. (c || d) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(c && d) is true.

Using Scanner

Scanner is a very useful class present in java.util package used to obtain input from the user. You have so far been able to pass input to your program as a program argument. When you send input this way, you have to run your program every time you want to change your argument. Using Scanner, you can send input to your program, when the program is running.

To create an object of Scanner class, you generally pass System.in argument, which represents the standard input stream.

Here is an example of using Scanner:

import java.util.Scanner; //notice the import statement for scanner!

public class ScannerDemo {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Hi, please input your name");

        String name = sc.nextLine(); // expects and gets a String value from use
        System.out.println("Hi " + name);

        System.out.println(name + ", please input your age");
        short age = sc.nextShort(); // expects and gets a short value from user
        System.out.println("Glad to know you are " + age + " years old!");

        System.out.println(name + ", please input your height in inches");
        double height = sc.nextDouble(); // expects and gets a double value from use
        System.out.println("Glad to know you are " + height + " inches tall!");  
        sc.close();
    }
}

To use the scanner you have to first import it in your code. Import statements always come on the top of your class name and not inside of your class definition. Any class which is not in of java.lang package should be imported. java.lang is the package that contains the core classes of Java programming language. When you use classes in this package, you do not need to import that class in your class. However, if you use any other class in any other package, you need to first have an import statement that defines the package name from which the specific class is imported from.

Here is the javadoc for Scanner: https://docs.oracle.com/javase/9/docs/api/java/util/Scanner.html Can you study the documentation and figure out what method to use to get an integer value from the console using Scanner? If you did not find the method name from the documentation, the next example will show you.

Reference for Boolean Algebra: http://www.categories.acsl.org/wiki/index.php?title=Boolean_Algebra

Special Caveats

When you apply arithmetic operations on any two variables of different data types, here are the various ways in which the resultant datatype is chosen

  • If the variables are of any of the types byte, short or int, the resultant will be of type int.
  • If one of the variable is of type long and the other is of type byte, short, int or long, then the resultant will be of type long.
  • If one of the variable is of decimal type then the largest of the decimal types will be resultant. So if float is the largest decimal type in the operation then the resultant would be float. If double is one of the types, then the resultant is a double.
  • In a division operation if both the variables are of integer types (byte, short, int and long) then the resultant will be an integer with no decimal part.

public class ByteAddition {

    public static void main(String[] args) {
        byte a = 1;
        byte b = 3;
        byte c = a+b;
        System.out.println(c);
    }
}

In the above example, a and b are declared of byte type and are then added. The result of adding 1 with 3 is 4 which is within the range of a byte value. However when you run the above program, you get a compile time error with the message

incompatible types: possible lossy conversion from int to byte

The reason for this error is when the expression 'a+b' is executed, the result of the sum is of type 'int'. So the value of type 'int' is being saved in a variable 'c' of type byte. Since an 'int' value can be bigger than a 'byte' value, the compiler throws an error. Even though you and me know that the result of this sum is '4' which can be saved in a byte type, compiler cannot figure that out.

Now if you change the statement to int c = a+b then the compiler is happy with you!

However, if you know for sure that result of any expression will never exceed the declared smaller datatype then you can typecast the result to the lower sized data type. Here is how you would change the expression to ensure that the result can be saved in byte:

byte c = (byte) (a+b);

Notice the (byte) being added before the expression (a+b) which is also within the parenthesis.

Note however that casting is only required when a value saved in bigger sized data type is being assigned to a smaller sized data type. For situations which are other way around no casting is required.
For example;


int a = 1;
int b = 3;
long c = a+b;

Statements in the above example are perfectly valid as the sum of 'a+b' is of type 'int' and is being assigned to 'c' which is of datatype 'long', that is bigger than an 'int'

Here is an example program which shows how to find the data type chosen during the operation;

short a = 2;
short b = 20;

System.out.println(((Object)(b/a)).getClass().getSimpleName());

In the above expression you cast the resultant to type Object first and then get the class name of the object to find its simple name. This is possible because all the primitives can be represented as an Object too and you will learn about that later.

results matching ""

    No results matching ""