Java Operators

Arithmetic and Unary Operatos

Java Operators

Java Operators

Java divides the operators into the following groups:

Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators

Arithmetic Operators

, - , * , / , %

Example 1

int a = 4; int b = 5; int c = a+b; System.out.println(c);

Output

9

Example 2

int a = 3; int b = 4; int c = a-b; System.out.println(c);

Output

-1

Example 3

float x = 1.00f; float y = 2.00f; float z = x/y; System.out.println(z);

Output

0.5

Example 4:

int a = 10: int b = 9: int c = a%b; System.out.println(c);

Output

1 Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:

Example

int x = 10;
System.out.println(x);

Output

10

The addition assignment operator (+=) adds a value to a variable:

Example

int x = 10;
x += 5;
System.out.println(x);

Output

15

Unary Arithmetic Operators

In Java, unary arithmetic operators are used to increasing or decreasing the value of an operand. Increment operator adds 1 to the value of a variable, whereas the decrement operator decreases a value.

Increment and decrement unary operator works as follows:

Syntax:

val++;
val--;

These two operators have two forms:

Postfix and Prefix. Both do increment or decrement in appropriate variables. These two operators can be placed before or after of variables. When it is placed before the variable, it is called prefix. And when it is placed after, it is called postfix.

val = a++; //Store the value of "a" in "val" then increments.
val = a--; //Store the value of "a" in "val" then decrements.
val = ++a; //Increments "a" then store the new value of "a" in "val".
val = --a; //Decrements "a" then store the new value of "a" in "val".

Comparison Operators

== , != , > , < , >= , <=

Example 1

int a = 10; boolean b = a>5; System.out.println(b);

Output

true

Example 2

int x = 10; boolean y = (x==10);

Output

true

Logical Operators

&& , || , !

Example 1

int a = 20; int b = 10; boolean z = (a>b) && (b<a); System.out.println(z);

Output

true

Example 2

int a = 20; int b = 1; boolean y = (a>b) || (b>a); System.out.println(y);

Output

true

Example 3

int a = 12; int b = 21; boolean z = ((a>b) || (b >0)) && (a !=0); System.out.println(z);

Output

true

Example 4

boolean isAssignmentCompleted = true; boolean negate = !isAssignmentCompleted; System.out.println(negate);

Output

false