Skip to main content

Java Operators

Operators in Java are special symbols used to perform operations on variables and values. They form the building blocks of expressions and logic in Java programs.


๐Ÿง  Definitionโ€‹

An operator in Java is a symbol that tells the compiler to perform specific mathematical, relational, or logical operations.


โœจ Fun Factโ€‹

The + operator is overloaded in Java to work both as an addition operator and a string concatenation operator.

System.out.println(5 + 10);        // Outputs 15
System.out.println("Age: " + 25); // Outputs Age: 25

๐Ÿ“š Types of Java Operatorsโ€‹

  1. Arithmetic Operators: +, -, *, /, %
  2. Relational (Comparison) Operators: ==, !=, >, <, >=, <=
  3. Logical Operators: &&, ||, !
  4. Assignment Operators: =, +=, -=, *=, /=, %=
  5. Unary Operators: +, -, ++, --, !
  6. Bitwise Operators: &, |, ^, ~, <<, >>, >>>
  7. Ternary Operator: ? :

๐Ÿ’ก Exampleโ€‹

int a = 10, b = 5;
System.out.println(a + b); // 15
System.out.println(a > b); // true
System.out.println(a != b); // true
System.out.println((a > b) && (a < 20)); // true

๐ŸŒ Real-World Analogyโ€‹

Imagine you're cooking:

  • Measuring ingredients = Arithmetic
  • Checking if a step is done = Comparison
  • Deciding what to do next = Logical
  • Storing recipe steps = Assignment

Each operation helps you build a full recipe โ€” just like code!


๐Ÿง’ Explain Like I'm Five (ELI5)โ€‹

You have a toy calculator:

  • + adds toys
  • - takes away
  • == checks if you and your friend have the same toys
  • && means both things must be true to get candy

Operators are like buttons on your logic calculator!


๐Ÿ“Š Operator Precedence (Simplified)โ€‹

Some operators run before others. Think:

  • * and / before + and -
  • Brackets () first
System.out.println(2 + 3 * 4); // 14, not 20
System.out.println((2 + 3) * 4); // 20

๐Ÿงช Exerciseโ€‹

  1. Try using all arithmetic operators with two numbers.
  2. Write a program that checks if a person is eligible to vote (age >= 18).
  3. Use the ternary operator to find the minimum of two numbers.

โšก Quick Recapโ€‹

  • Operators perform tasks like math and logic.
  • Java supports various operators: arithmetic, logical, relational, etc.
  • Precedence matters!