DEV Community

Karthick Narayanan
Karthick Narayanan

Posted on

Day 5: Understanding Java Operators

What is an Operator in Java?

In Java, an operator is a special symbol or keyword used to perform operations such as:

  • Addition
  • Subtraction
  • Division
  • Comparison
  • Logical checking

Important terms:

  • Operator → Symbol that performs an operation
  • Operand → Value on which the operator works

Example:

int a = 10;
Enter fullscreen mode Exit fullscreen mode

Here:

  • = is the operator
  • a and 10 are operands

Types of Operators in Java

Java has the following operator types:


1️⃣ Assignment Operator

Used to assign a value to a variable.

Operator:

=
Enter fullscreen mode Exit fullscreen mode

Example:

int no = 10;
Enter fullscreen mode Exit fullscreen mode

2️⃣ Arithmetic Operators

Used to perform mathematical calculations.

Operators:

+, -, *, /, %
Enter fullscreen mode Exit fullscreen mode

Examples:

int a = 10;
int b = 3;

System.out.println(a + b); // Addition
System.out.println(a - b); // Subtraction
System.out.println(a * b); // Multiplication
System.out.println(a / b); // Division
System.out.println(a % b); // Modulus (remainder)
Enter fullscreen mode Exit fullscreen mode

3️⃣ Unary Operators

Unary operators work on a single variable.

Increment Operator (++)

Used to increase value by 1.

=> Post Increment (no++)

  • First use the value
  • Then increase it

Example:

int no = 10;
System.out.println(no++); // 10
System.out.println(no);   // 11
Enter fullscreen mode Exit fullscreen mode

=> Pre Increment (++no)

  • First increase the value
  • Then use it

Example:

int age = 15;
System.out.println(++age); // 16
Enter fullscreen mode Exit fullscreen mode

Decrement Operator (--)

Used to decrease value by 1.

=> Post Decrement (no--)

int no = 10;
System.out.println(no--); // 10
System.out.println(no);   // 9
Enter fullscreen mode Exit fullscreen mode

=> Pre Decrement (--no)

int age = 15;
System.out.println(--age); // 14
Enter fullscreen mode Exit fullscreen mode

4️⃣ Equality and Relational Operators

Used to compare two values.

Operators:

== , != , < , > , <= , >=
Enter fullscreen mode Exit fullscreen mode

Examples:

int a = 10;
int b = 20;

System.out.println(a == b); // false
System.out.println(a != b); // true
System.out.println(a < b);  // true
Enter fullscreen mode Exit fullscreen mode

The result of these operators is always true or false.


5️⃣ Conditional (Logical) Operators

Used to combine conditions.

Operators:

&&  (AND)
||  (OR)
Enter fullscreen mode Exit fullscreen mode

=> AND operator (&&)

  • Returns true only if both conditions are true

=> OR operator (||)

  • Returns true if any one condition is true

Example:

int age = 20;
System.out.println(age > 18 && age < 60);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)