DEV Community

devcse
devcse

Posted on

Operators in Java Explained

Operator are those who performs an action, for example + is an arithmetic operator that perform addition. They are various types of operators are available in java programming language.

Contents [show]

Types of Operator in Java
Arithmetic Operators
Assignment Operators
Auto-increment and Auto-decrement Operators
Logical Operators
Comparison (relational) operators
Arithmetic Operators
arithmetic operators are: +, -, *, /, %

  • is used for addition

– is used for substraction

  • is for multiplication

/ is used for division

% is used for find reminder, % is called modulus(modulo) operator

Let’s take an example:

package com.sync;

public class OperatorsDemo {

public static void main(String[] args) {

    int num1 = 300;
    int num2 = 30;

    System.out.println("num1 + num2: " + (num1 + num2) ); // addition
    System.out.println("num1 - num2: " + (num1 - num2) ); // subtraction
    System.out.println("num1 * num2: " + (num1 * num2) ); // multiplication
    System.out.println("num1 / num2: " + (num1 / num2) ); // division
    System.out.println("num1 % num2: " + (num1 % num2) ); // modulo
}
Enter fullscreen mode Exit fullscreen mode

}

/* output:

num1 + num2: 330
num1 - num2: 270
num1 * num2: 9000
num1 / num2: 10
num1 % num2: 0

*/
Assignment Operators
Assignments operators in java are: =, +=, -=, *=, /=, %=

num2 = num1 would assign value of variable num1 to the variable num2.
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
So, let’s take an example:

package com.sync;

public class OperatorsDemo {

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);

}
Enter fullscreen mode Exit fullscreen mode

}
/* output:

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

*/

Read More: https://codesnipeet.com/operators-in-java-explained/

Top comments (0)