#00004 Operators in Java
Posted by Superadmin on November 09 2018 01:25:12

1.1.            Operators in Java

An operator is a character that represents an action, for example + is an arithmetic operator that represents addition.

Types of Operator in Java

1) Basic Arithmetic Operators
2) Assignment Operators
3) Auto-increment and Auto-decrement Operators
4) Logical Operators
5) Comparison (relational) operators
6) Bitwise Operators
7) Ternary Operator

1) Basic Arithmetic Operators

Basic arithmetic operators are: +, -, *, /, %
+ is for addition.

 is for subtraction.

* is for multiplication.

/ is for division.

% is for modulo.
Note: Modulo operator returns remainder, for example 10 % 5 would return 0

Example of Arithmetic Operators

public class ArithmeticOperatorDemo {
   public static void main(String args[]) {
      int num1 = 100;
      int num2 = 20;
 
      System.out.println("num1 + num2: " + (num1 + num2) );
      System.out.println("num1 - num2: " + (num1 - num2) );
      System.out.println("num1 * num2: " + (num1 * num2) ); 
      System.out.println("num1 / num2: " + (num1 / num2) );
      System.out.println("num1 % num2: " + (num1 % num2) );
   }
}

Output:

num1 + num2: 120
num1 - num2: 80
num1 * num2: 2000
num1 / num2: 5
num1 % num2: 0

 

Java Program to Add two Numbers

Here we will see two programs to add two numbers, In the first program we specify the value of both the numbers in the program itself. The second programs takes both the numbers (entered by user) and prints the sum.

First Example: Sum of two numbers

public class AddTwoNumbers {
 
   public static void main(String[] args) {
        
      int num1 = 5, num2 = 15, sum;
      sum = num1 + num2;
 
      System.out.println("Sum of these numbers: "+sum);
   }
}

Output:

Sum of these numbers: 20

 

Second Example: Sum of two numbers using Scanner

The scanner allows us to capture the user input so that we can get the values of both the numbers from user. The program then calculates the sum and displays it.

import java.util.Scanner;
public class AddTwoNumbers2 {
 
    public static void main(String[] args) {
        
        int num1, num2, sum;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter First Number: ");
        num1 = sc.nextInt();
        
        System.out.println("Enter Second Number: ");
        num2 = sc.nextInt();
        
        sc.close();
        sum = num1 + num2;
        System.out.println("Sum of these numbers: "+sum);
    }
}
 
Output:
Enter First Number: 
121
Enter Second Number: 
19
Sum of these numbers: 140

 

Java Program to Multiply Two Numbers

When you start learning java programming, you get these type of problems in your assignment. Here we will see two Java programs, first program takes two integer numbers (entered by user) and displays the product of these numbers. The second program takes any two numbers (can be integer or floating point) and displays the result.

Example 1: Program to read two integer and print product of them

This program asks user to enter two integer numbers and displays the product..

import java.util.Scanner;
 
public class Demo {
 
    public static void main(String[] args) {
 
        /* This reads the input provided by user
         * using keyboard
         */
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter first number: ");
 
        // This method reads the number provided using keyboard
        int num1 = scan.nextInt();
        
        System.out.print("Enter second number: ");
        int num2 = scan.nextInt();
 
        // Closing Scanner after the use
        scan.close();
        
        // Calculating product of two numbers
        int product = num1*num2;
        
        // Displaying the multiplication result
        System.out.println("Output: "+product);
    }
}

Output:

Enter first number: 15
Enter second number: 6
Output: 90

 

Example 2: Read two integer or floating point numbers and display the multiplication

In the above program, we can only integers. What if we want to calculate the multiplication of two float numbers? This programs allows you to enter float numbers and calculates the product.

Here we are using data type double for numbers so that you can enter integer as well as floating point numbers.

import java.util.Scanner;
 
public class Demo {
 
    public static void main(String[] args) {
 
        /* This reads the input provided by user
         * using keyboard
         */
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter first number: ");
 
        // This method reads the number provided using keyboard
        double num1 = scan.nextDouble();
        
        System.out.print("Enter second number: ");
        double num2 = scan.nextDouble();
 
        // Closing Scanner after the use
        scan.close();
        
        // Calculating product of two numbers
        double product = num1*num2;
        
        // Displaying the multiplication result
        System.out.println("Output: "+product);
    }
}

 

Output:

Enter first number: 1.5
Enter second number: 2.5
Output: 3.75

 

2) Assignment Operators

Assignments operators in java are: =, +=, -=, *=, /=, %=
num2 = num1 would assign value of variable num1 to the variable.

num2+=num1 is equal to num2 = num2+num1

num2-=num1 is equal to num2 = num2-num1

num2*=num1 is equal to num2 = num2*num1

num2/=num1 is equal to num2 = num2/num1

num2%=num1 is equal to num2 = num2%num1

Example of Assignment Operators

public class AssignmentOperatorDemo {
   public static void main(String args[]) {
      int num1 = 10;
      int num2 = 20;
 
      num2 = num1;
      System.out.println("= Output: "+num2);
 
      num2 += num1;
      System.out.println("+= Output: "+num2);
               
      num2 -= num1;
      System.out.println("-= Output: "+num2);
               
      num2 *= num1;
      System.out.println("*= Output: "+num2);
               
      num2 /= num1;
      System.out.println("/= Output: "+num2);
               
      num2 %= num1;
      System.out.println("%= Output: "+num2);
   }
}

 

Output:

= Output: 10
+= Output: 20
-= Output: 10
*= Output: 100
/= Output: 10
%= Output: 0

 

3) Auto-increment and Auto-decrement Operators

++ and —
num++ is equivalent to num=num+1;

num–- is equivalent to num=num-1;

Example of Auto-increment and Auto-decrement Operators

public class AutoOperatorDemo {
   public static void main(String args[]){
      int num1=100;
      int num2=200;
      num1++;
      num2--;
      System.out.println("num1++ is: "+num1);
      System.out.println("num2-- is: "+num2);
   }
}

 

Output:

num1++ is: 101
num2-- is: 199

 

4) Logical Operators

Logical Operators are used with binary variables. They are mainly used in conditional statements and loops for evaluating a condition.

Logical operators in java are: &&, ||, !

Let’s say we have two boolean variables b1 and b2.

b1&&b2 will return true if both b1 and b2 are true else it would return false.

b1||b2 will return false if both b1 and b2 are false else it would return true.

!b1 would return the opposite of b1, that means it would be true if b1 is false and it would return false if b1 is true.

Example of Logical Operators

public class LogicalOperatorDemo {
   public static void main(String args[]) {
      boolean b1 = true;
      boolean b2 = false;
 
      System.out.println("b1 && b2: " + (b1&&b2));
      System.out.println("b1 || b2: " + (b1||b2));
      System.out.println("!(b1 && b2): " + !(b1&&b2));
   }
}

 

Output:

b1 && b2: false
b1 || b2: true
!(b1 && b2): true

 

5) Comparison(Relational) operators

We have six relational operators in Java: ==, !=, >, <, >=, <=

== returns true if both the left side and right side are equal

!= returns true if left side is not equal to the right side of operator.

> returns true if left side is greater than right.

< returns true if left side is less than right side.

>= returns true if left side is greater than or equal to right side.

<= returns true if left side is less than or equal to right side.

Example of Relational operators

public class RelationalOperatorDemo {
   public static void main(String args[]) {
      int num1 = 10;
      int num2 = 50;
      if (num1==num2) {
          System.out.println("num1 and num2 are equal");
      }
      else{
          System.out.println("num1 and num2 are not equal");
      }
 
      if( num1 != num2 ){
          System.out.println("num1 and num2 are not equal");
      }
      else{
          System.out.println("num1 and num2 are equal");
      }
 
      if( num1 > num2 ){
          System.out.println("num1 is greater than num2");
      }
      else{
          System.out.println("num1 is not greater than num2");
      }
 
      if( num1 >= num2 ){
          System.out.println("num1 is greater than or equal to num2");
      }
      else{
          System.out.println("num1 is less than num2");
      }
 
      if( num1 < num2 ){
          System.out.println("num1 is less than num2");
      }
      else{
          System.out.println("num1 is not less than num2");
      }
 
      if( num1 <= num2){
          System.out.println("num1 is less than or equal to num2");
      }
      else{
          System.out.println("num1 is greater than num2");
      }
   }
}

Output:

num1 and num2 are not equal
num1 and num2 are not equal
num1 is not greater than num2
num1 is less than num2
num1 is less than num2
num1 is less than or equal to num2

 

Check out these related java programs related to relational operators:

Example 1: Program to check whether the given number is positive or negative

→ If a number is greater than zero then it is a positive number
→ If a number is less than zero then it is a negative number
→ If a number is equal to zero then it is neither negative nor positive.

In this program we have specified the value of number during declaration and the program checks whether the specified number is positive or negative. To understand this program you should have the basic knowledge of if-else-if statement in Core Java Programming.

public class Demo
{
    public static void main(String[] args) 
    {
        int number=109;
        if(number > 0)
        {
            System.out.println(number+" is a positive number");
        }
        else if(number < 0)
        {
            System.out.println(number+" is a negative number");
        }
        else
        {
            System.out.println(number+" is neither positive nor negative");
        }
    }
}

Output:

109 is a positive number

 

Example 2: Check whether the input number(entered by user) is positive or negative

Here we are using Scanner to read the number entered by user and then the program checks and displays the result.

import java.util.Scanner;
public class Demo
{
    public static void main(String[] args) 
    {
        int number;
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the number you want to check:");
        number = scan.nextInt();
        scan.close();
        if(number > 0)
        {
            System.out.println(number+" is positive number");
        }
        else if(number < 0)
        {
            System.out.println(number+" is negative number");
        }
        else
        {
            System.out.println(number+" is neither positive nor negative");
        }
    }
}

 

Output:

Enter the number you want to check:-12
-12 is negative number

 

Java Program to check Even or Odd number

import java.util.Scanner;
 
class CheckEvenOdd
{
  public static void main(String args[])
  {
    int num;
    System.out.println("Enter an Integer number:");
 
    //The input provided by user is stored in num
    Scanner input = new Scanner(System.in);
    num = input.nextInt();
 
    /* If number is divisible by 2 then it's an even number
     * else odd number*/
    if ( num % 2 == 0 )
        System.out.println("Entered number is even");
     else
        System.out.println("Entered number is odd");
  }
}

Output 1:

Enter an Integer number:
78
Entered number is even

Output 2:

Enter an Integer number:
77
Entered number is odd

 

6) Bitwise Operators

There are six bitwise Operators: &, |, ^, ~, <<, >>

num1 = 11; /* equal to 00001011*/
num2 = 22; /* equal to 00010110 */

Bitwise operator performs bit by bit processing.

 

num1 & num2 compares corresponding bits of num1 and num2 and generates 1 if both bits are equal, else it returns 0. In our case it would return: 2 which is 00000010 because in the binary form of num1 and num2 only second last bits are matching.

num1 | num2 compares corresponding bits of num1 and num2 and generates 1 if either bit is 1, else it returns 0. In our case it would return 31 which is 00011111

num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if they are not equal, else it returns 0. In our example it would return 29 which is equivalent to 00011101

~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to 0. In our example it would return -12 which is signed 8 bit equivalent to 11110100

num1 << 2 is left shift operator that moves the bits to the left, discards the far left bit, and assigns the rightmost bit a value of 0. In our case output is 44 which is equivalent to 00101100

Note: In the example below we are providing 2 at the right side of this shift operator that is the reason bits are moving two places to the left side. We can change this number and bits would be moved by the number of bits specified on the right side of the operator. Same applies to the right side operator.

num1 >> 2 is right shift operator that moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. In our case output is 2 which is equivalent to 00000010

Example of Bitwise Operators

public class BitwiseOperatorDemo {
  public static void main(String args[]) {
 
     int num1 = 11;  /* 11 = 00001011 */
     int num2 = 22;  /* 22 = 00010110 */
     int result = 0;
 
     result = num1 & num2;   
     System.out.println("num1 & num2: "+result);
 
     result = num1 | num2;   
     System.out.println("num1 | num2: "+result);
    
     result = num1 ^ num2;   
     System.out.println("num1 ^ num2: "+result);
    
     result = ~num1;   
     System.out.println("~num1: "+result);
    
     result = num1 << 2;   
     System.out.println("num1 << 2: "+result); result = num1 >> 2;   
     System.out.println("num1 >> 2: "+result);
  }
}

Output:

num1 & num2: 2
num1 | num2: 31
num1 ^ num2: 29
~num1: -12
num1 << 2: 44 num1 >> 2: 2

 

Java Program to Swap two numbers using Bitwise XOR Operator

This java program swaps two numbers using bitwise XOR operator. Before going though the program, lets see what is a bitwise XOR operator: A bitwise XOR compares corresponding bits of two operands and returns 1 if they are equal and 0 if they are not equal. For example:

num1 = 11; /* equal to 00001011*/
num2 = 22; /* equal to 00010110 */

 

num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if they are not equal, else it returns 0. In our example it would return 29 which is equivalent to 00011101

Let’s write this in a Java program:

Example: Swapping two numbers using bitwise operator

import java.util.Scanner;
public class JavaExample 
{
    public static void main(String args[])
    {
        int num1, num2;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first number:");
        num1 = scanner.nextInt();
        System.out.print("Enter second number:");
        num2 = scanner.nextInt();
        /* To make you understand, lets assume I am going
         * to enter value of first number as 10 and second 
         * as 5. Binary equivalent of 10 is 1010 and 5 is
         * 0101
         */
        
        //num1 becomes 1111 = 15
        num1 = num1 ^ num2;
        //num2 becomes 1010 = 10
        num2 = num1 ^ num2;
        //num1 becomes 0101 = 5
        num1 = num1 ^ num2;
        scanner.close();
        System.out.println("The First number after swapping:"+num1);
        System.out.println("The Second number after swapping:"+num2);
    }
}

Output:

Enter first number:10
Enter second number:5
The First number after swapping:5
The Second number after swapping:10

 

7) Ternary Operator

This operator evaluates a boolean expression and assign the value based on the result.
Syntax:

variable num1 = (expression) ? value if true : value if false

If the expression results true then the first value before the colon (:) is assigned to the variable num1 else the second value is assigned to the num1.

Example of Ternary Operator

public class TernaryOperatorDemo {
 
   public static void main(String args[]) {
        int num1, num2;
        num1 = 25;
        /* num1 is not equal to 10 that's why
          * the second value after colon is assigned
          * to the variable num2
          */
         num2 = (num1 == 10) ? 100: 200;
         System.out.println( "num2: "+num2);
 
         /* num1 is equal to 25 that's why
          * the first value is assigned
          * to the variable num2
          */
         num2 = (num1 == 25) ? 100: 200;
         System.out.println( "num2: "+num2);
   }
}

Output:

num2: 200
num2: 100

 

Check out these related java programs:

Java Program to find largest of three numbers using Ternary Operator

This program finds the largest of three numbers using ternary operator. Before going through the program, lets understand what is a ternary Operator:
Ternary operator evaluates a boolean expression and assign the value based on the result.

variable num = (expression) ? value if true : value if false

If the expression results true then the first value before the colon (:) is assigned to the variable num else the second value is assigned to the num.

Example: Program to find the largest number using ternary operator

In this Program, we have used the ternary operator twice to compare the three numbers, however you can compare all three numbers in one statement using ternary operator like this:

result = num3 > (num1>num2 ? num1:num2) ? num3:((num1>num2) ? num1:num2);

However if you are finding it difficult to understand then use it like I have shown in the example below:

import java.util.Scanner;
public class JavaExample 
{
    public static void main(String[] args) 
    {
        int num1, num2, num3, result, temp;
        /* Scanner is used for getting user input. 
         * The nextInt() method of scanner reads the
         * integer entered by user.
         */
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter First Number:");
        num1 = scanner.nextInt();
        System.out.println("Enter Second Number:");
        num2 = scanner.nextInt();
        System.out.println("Enter Third Number:");
        num3 = scanner.nextInt();
        scanner.close();
       
        
        /* In first step we are comparing only num1 and
         * num2 and storing the largest number into the
         * temp variable and then comparing the temp and
         * num3 to get final result.
         */
        temp = num1>num2 ? num1:num2;
        result = num3>temp ? num3:temp;
        System.out.println("Largest Number is:"+result);
    }
}

Output:

Enter First Number:
89
Enter Second Number:
109
Enter Third Number:
8
Largest Number is:109

 

Java Program to find the Smallest of three numbers using Ternary Operator

This java program finds the smallest of three numbers using ternary operator. Lets see what is a ternary operator:
This operator evaluates a boolean expression and assign the value based on the result.

variable num1 = (expression) ? value if true : value if false

 

If the expression results true then the first value before the colon (:) is assigned to the variable num1 else the second value is assigned to the num1.

Example: Program to find the smallest of three numbers using ternary operator

We have used ternary operator twice to get the final output because we have done the comparison in two steps:
First Step: Compared the num1 and num2 and stored the smallest of these two into a temporary variable temp.
Second Step: Compared the num3 and temp to get the smallest of three.
If you want, you can do that in a single statement like this:

result = num3 < (num1 < num2 ? num1:num2) ? num3:(num1 < num2 ? num1:num2);

Here is the complete program:

import java.util.Scanner;
public class JavaExample 
{
    public static void main(String[] args) 
    {
        int num1, num2, num3, result, temp;
        /* Scanner is used for getting user input. 
         * The nextInt() method of scanner reads the
         * integer entered by user.
         */
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter First Number:");
        num1 = scanner.nextInt();
        System.out.println("Enter Second Number:");
        num2 = scanner.nextInt();
        System.out.println("Enter Third Number:");
        num3 = scanner.nextInt();
        scanner.close();
        
        /* In first step we are comparing only num1 and
         * num2 and storing the smallest number into the
         * temp variable and then comparing the temp and
         * num3 to get final result.
         */
        
        temp = num1 < num2 ? num1:num2;
        result = num3 < temp ? num3:temp;
        System.out.println("Smallest Number is:"+result);
    }
}

Output:

Enter First Number:
67
Enter Second Number:
7
Enter Third Number:
9
Smallest Number is:7

 

Operator Precedence in Java

This determines which operator needs to be evaluated first if an expression has more than one operator. Operator with higher precedence at the top and lower precedence at the bottom.
Unary Operators
++  – –  !  ~

Multiplicative
*  / %

Additive
+  –

Shift
<<  >>  >>>

Relational
>  >=  <  <=

Equality
==  !=

Bitwise AND
&

Bitwise XOR
^

Bitwise OR
|

Logical AND
&&

Logical OR
||

Ternary
?:

Assignment
=  +=  -=  *=  /=  %=  >  >=  <  <=  &=  ^=  |=