Java Operators – Mastering Arithmetic, Logical, and Relational Operations
Introduction
- What are Operators in Java?
- Explanation of operators as symbols that perform operations on variables and values.
- Why understanding operators is crucial in Java programming.
1. Arithmetic Operators in Java
Overview
- Arithmetic operators perform mathematical calculations like addition, subtraction, multiplication, and division.
List of Arithmetic Operators
Operator Description Example +
Addition a + b
-
Subtraction a - b
*
Multiplication a * b
/
Division a / b
%
Modulus (remainder) a % b
Examples:
- Explanation: Shows the result of each arithmetic operation.
2. Logical Operators
Overview
- Logical operators are used to combine multiple conditions, often in decision-making (
if
statements).
- Logical operators are used to combine multiple conditions, often in decision-making (
List of Logical Operators
Operator Description Example &&
Logical AND (a > b) && (a < c)
` ` !
Logical NOT !(a > b)
Examples:
- Explanation: Demonstrates how
&&
,||
, and!
work with Boolean values.
- Explanation: Demonstrates how
3. Relational Operators
Overview
- Relational operators are used to compare two values and return a boolean result (true or false).
List of Relational Operators
Operator Description Example ==
Equal to a == b
!=
Not equal to a != b
>
Greater than a > b
<
Less than a < b
>=
Greater than or equal a >= b
<=
Less than or equal a <= b
Examples:
- Explanation: Shows the results of comparing two numbers with each relational operator.
4. Assignment Operators
Overview
- Assignment operators assign values to variables.
=
is the most basic, but there are compound operators for combined arithmetic and assignment.
- Assignment operators assign values to variables.
List of Assignment Operators
Operator Description Example =
Simple assignment a = 10
+=
Add and assign a += 5
-=
Subtract and assign a -= 3
*=
Multiply and assign a *= 2
/=
Divide and assign a /= 4
%=
Modulus and assign a %= 3
Examples:
- Explanation: Demonstrates each assignment operation, modifying
a
step-by-step.
- Explanation: Demonstrates each assignment operation, modifying
5. Ternary Operator
Overview
- A shorthand for
if-else
statements, the ternary operator allows quick condition evaluation.
- A shorthand for
Syntax
Example:
- Explanation: This example evaluates the condition
a > b
. If true, it assigns"a is greater"
toresult
; otherwise, it assigns"b is greater or equal"
.
- Explanation: This example evaluates the condition