Operators in Java (Arithmetic, Assignment, Comparison)

Learn Java operators step by step: arithmetic, assignment, and comparison with clear explanations and examples. Day 3 Java tutorial.
Operators (Arithmetic, Assignment, Comparison)

In Java, operators are symbols that perform specific actions on variables and values. They help us do math, assign values, and compare results. Without operators, coding would be much harder. In this lesson, we cover three important categories: Arithmetic, Assignment, and Comparison operators.

1. Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations on numbers:

  • + : Addition
  • - : Subtraction
  • * : Multiplication
  • / : Division (returns quotient)
  • % : Modulus (returns remainder)

int a = 10, b = 3;
System.out.println(a + b); // 13
System.out.println(a - b); // 7
System.out.println(a * b); // 30
System.out.println(a / b); // 3 (integer division)
System.out.println(a % b); // 1 (remainder)

How it works: If you divide 10 by 3, the quotient is 3 and the remainder is 1. That’s why a / b gives 3 and a % b gives 1.

2. Assignment Operators

Assignment operators are used to assign values to variables. The basic one is =, but Java also supports shorthand forms like +=, -=, *=, /=.


int x = 5;   // assigns 5 to x
x += 3;      // same as x = x + 3 → x = 8
x *= 2;      // same as x = x * 2 → x = 16

How it works: Instead of writing x = x + 3, we can just use x += 3. This makes the code shorter and easier to read.

3. Comparison Operators

Comparison operators are used to compare two values. The result is always true or false (a boolean value).

  • == : Equal to
  • != : Not equal to
  • > : Greater than
  • < : Less than
  • >= : Greater than or equal to
  • <= : Less than or equal to

int a = 10, b = 5;
System.out.println(a == b);  // false (10 is not equal to 5)
System.out.println(a != b);  // true  (10 is not equal to 5)
System.out.println(a > b);   // true  (10 is greater than 5)
System.out.println(a < b);   // false (10 is not less than 5)
System.out.println(a >= 10); // true  (10 is equal to 10)
System.out.println(b <= 5);  // true  (5 is equal to 5)

How it works: The comparison operators always return true or false. For example, a > b checks if 10 is greater than 5, which is true.

Summary

Operators are essential in Java. Arithmetic operators handle math, assignment operators update values efficiently, and comparison operators check conditions. Together, they form the basis of programming logic that you’ll use in decision-making and loops later in the course.

إرسال تعليق