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โ
- Arithmetic Operators:
+,-,*,/,% - Relational (Comparison) Operators:
==,!=,>,<,>=,<= - Logical Operators:
&&,||,! - Assignment Operators:
=,+=,-=,*=,/=,%= - Unary Operators:
+,-,++,--,! - Bitwise Operators:
&,|,^,~,<<,>>,>>> - 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โ
- Try using all arithmetic operators with two numbers.
- Write a program that checks if a person is eligible to vote (age >= 18).
- 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!