Java 02

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

1 Assignment, Comparison, and Logical Opera-

tors in Java
In Java, operators are used to perform various operations on data. Here, we’ll
explore assignment, comparison, and logical operators.

1.1 Assignment Operator (=)


The assignment operator (=) is used to assign a value to a variable. It takes the
value on its right-hand side and stores it in the variable on its left-hand side.
Example:
int x = 5; // Assigns the value 5 to the variable x

1.2 Comparison Operators


Comparison operators are used to compare two values and return a boolean
result. Here are some common comparison operators:

• ==: Equal to
• !=: Not equal to

• <: Less than


• <=: Less than or equal to
• >: Greater than
• >=: Greater than or equal to

Examples:
int a = 10;
int b = 5;

boolean isEqual = (a == b); // false, because a is not equal to b


boolean isNotEqual = (a != b); // true, because a is not equal to b
boolean isGreaterThan = (a > b); // true, because a is greater than b
boolean isLessThanOrEqual = (a <= b); // false, because a is not less than or equal to b

1.3 Logical Operators


Logical operators are used to perform logical operations on boolean values.
There are three main logical operators:

• &&: Logical AND

• ||: Logical OR

1
• !: Logical NOT

Examples:
boolean isTrue = true;
boolean isFalse = false;

boolean result1 = (isTrue && isFalse); // false


boolean result2 = (isTrue || isFalse); // true
boolean result3 = !isTrue; // false

1.4 Combining Operators


You can use comparison and logical operators together to create complex con-
ditions in your code.
Example:
int age = 25;
boolean isAdult = (age >= 18 && age <= 65); // true

In this example, we use the greater than or equal to (>=) and logical AND
(&&) operators to check if the age variable falls within the range of 18 to 65,
resulting in true.
Understanding these operators is essential for controlling program flow and
making decisions in Java.

You might also like