Java Operators, Conditional Statements and Loops
Operators#
Introduction#
In Java, operators are symbols used to perform operations on values and variables.
What Is an Operator?#
An operator is a symbol that tells Java to perform a particular operation.
For example:
int result = 10 + 20;
Here:
10→ operand20→ operand+→ operatorresult→ variable storing the result
The values on which an operator works are called operands.
Types of Operators in Java#
Java operators can be classified as:
Operators
├── Arithmetic Operators
├── Assignment Operators
├── Relational Operators
├── Logical Operators
├── Unary Operators
├── Ternary Operator
├── Bitwise Operators
├── Shift Operators
└── instanceof Operator
Let's understand them one by one.
Arithmetic Operators#
Arithmetic operators are used to perform mathematical operations.
| Operator | Meaning | Example |
|---|---|---|
+ |
Addition | a + b |
- |
Subtraction | a - b |
* |
Multiplication | a * b |
/ |
Division | a / b |
% |
Modulus | a % b |
Example:
int a = 10;
int b = 3;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println(a / b);
System.out.println(a % b);
Output:
13
7
30
3
1
Addition with Strings#
The + operator can also be used to join strings.
String firstName = "Ravi";
String lastName = "Kumar";
String fullName = firstName + " " + lastName;
System.out.println(fullName);
Output:
Ravi Kumar
The + operator behaves differently when strings are involved.
For example:
System.out.println("Age: " + 20);
Output:
Age: 20
Assignment Operators#
Assignment operators are used to assign values to variables.
The basic assignment operator is:
=
Example:
int x = 10;
Here, 10 is assigned to x.
Java also provides compound assignment operators.
| Operator | Example | Equivalent |
|---|---|---|
= |
x = 10 |
x = 10 |
+= |
x += 5 |
x = x + 5 |
-= |
x -= 5 |
x = x - 5 |
*= |
x *= 5 |
x = x * 5 |
/= |
x /= 5 |
x = x / 5 |
%= |
x %= 5 |
x = x % 5 |
Relational Operators#
Relational operators are used to compare two values.
The result of a relational operation is a boolean value:
true
or:
false
| Operator | Meaning |
|---|---|
== |
Equal to |
!= |
Not equal to |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
Example:
int a = 10;
int b = 20;
System.out.println(a == b);
System.out.println(a != b);
System.out.println(a > b);
System.out.println(a < b);
Output:
false
true
false
true
Logical Operators#
Logical operators are used to combine boolean expressions.
| Operator | Meaning |
|---|---|
&& |
Logical AND |
| ` | |
! |
Logical NOT |
Logical AND &&
The && operator returns true only when both conditions are true.
| Condition 1 | Condition 2 | Result |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
Example:
int age = 20;
System.out.println(age >= 18 && age <= 60);
Output:
true
Both conditions are true.
Logical OR ||
The || operator returns true when at least one condition is true.
| Condition 1 | Condition 2 | Result |
|---|---|---|
| true | true | true |
| true | false | true |
| false | true | true |
| false | false | false |
Example:
int age = 16;
System.out.println(age < 18 || age > 60);
Output:
true
At least one condition is true.
Logical NOT !
The ! operator reverses a boolean value.
boolean passed = true;
System.out.println(!passed);
Output:
false
Unary Operators#
Unary operators work with only one operand.
Common unary operators are:
+
-
++
--
!
Example:
int x = 10;
System.out.println(-x);
Output:
-10
The unary minus changes the sign of the value.
Pre-Increment
When ++ is placed before the variable, it is called pre-increment.
int x = 10;
int result = ++x;
System.out.println(x);
System.out.println(result);
Output:
11
11
First x is increased, then its value is used.
Post-Increment
When ++ is placed after the variable, it is called post-increment.
int x = 10;
int result = x++;
System.out.println(x);
System.out.println(result);
Output:
11
10
The current value is used first, and then x is increased.
Pre-Decrement
int x = 10;
int result = --x;
System.out.println(x);
System.out.println(result);
Output:
9
9
Post-Decrement
int x = 10;
int result = x--;
System.out.println(x);
System.out.println(result);
Output:
9
10
Ternary Operator#
The ternary operator is a short form of a simple if-else statement.
Syntax:
condition ? valueIfTrue : valueIfFalse
Example:
int age = 20;
String result = age >= 18 ? "Adult" : "Minor";
System.out.println(result);
Output:
Adult
The same logic using if-else would be:
int age = 20;
String result;
if (age >= 18) {
result = "Adult";
} else {
result = "Minor";
}
The ternary operator is useful when the logic is simple.
Bitwise Operators#
Bitwise operators work at the bit level.
Common bitwise operators are:
| Operator | Meaning |
|---|---|
& |
Bitwise AND |
| ` | ` |
^ |
Bitwise XOR |
~ |
Bitwise complement |
For example:
int a = 5;
int b = 3;
System.out.println(a & b);
The binary values are:
5 = 0101
3 = 0011
Bitwise AND:
0101
0011
----
0001
Output:
1
Bitwise operators are commonly used in low-level programming and specialized applications.
Shift Operators#
Shift operators move bits to the left or right.
| Operator | Meaning |
|---|---|
<< |
Left shift |
>> |
Right shift |
>>> |
Unsigned right shift |
Example:
int x = 5;
System.out.println(x << 1);
Output:
10
Another example:
int x = 8;
System.out.println(x >> 1);
Output:
4
instanceof Operator#
The instanceof operator is used to check whether an object belongs to a particular type.
Example:
String name = "Ravi";
System.out.println(name instanceof String);
Output:
true
The result is a boolean value.
Conditional Statements#
Introduction#
In a Java program, sometimes we need to make decisions.
For example:
- If a student passes, display "Pass".
- If the age is 18 or above, allow the user to vote.
For these situations, Java provides conditional statements.
Conditional statements allow a program to execute different blocks of code depending on whether a condition is true or false.
What Is a Conditional Statement?#
A conditional statement checks a condition and decides which code should execute.
For example:
int age = 20;
if (age >= 18) {
System.out.println("Eligible");
}
Here:
age >= 18
is the condition.
Because the condition is true, the message is printed.
Types of Conditional Statements#
Java provides several ways to make decisions.
Conditional Statements
├── if
├── if-else
├── else-if
├── Nested if
└── switch
Let's understand each one.
if Statement#
The if statement executes a block of code only when the condition is true.
Syntax:
if (condition) {
// statements
}
Example:
int age = 20;
if (age >= 18) {
System.out.println("You are an adult");
}
Output:
You are an adult
Because age >= 18 is true.
If the condition is false, the statements inside the if block are skipped.
For example:
int number = -10;
if (number > 0) {
System.out.println("Positive number");
}
There is no output because the condition is false.
if-else Statement#
The if-else statement provides two choices.
If the condition is true, the if block executes.
If the condition is false, the else block executes.
Syntax:
if (condition) {
// if block
} else {
// else block
}
Example:
int age = 16;
if (age >= 18) {
System.out.println("Eligible");
} else {
System.out.println("Not eligible");
}
Output:
Not eligible
else-if Statement#
When there are multiple conditions, we can use else-if.
Syntax:
if (condition1) {
} else if (condition2) {
} else if (condition3) {
} else {
}
Example:
int marks = 85;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else if (marks >= 60) {
System.out.println("Grade C");
} else if (marks >= 40) {
System.out.println("Grade D");
} else {
System.out.println("Fail");
}
Output:
Grade B
Java checks the conditions from top to bottom.
As soon as one condition becomes true, its block executes and the remaining conditions are skipped.
Nested if#
An if statement inside another if statement is called a nested if.
Example:
int age = 20;
boolean hasId = true;
if (age >= 18) {
if (hasId) {
System.out.println("Entry allowed");
}
}
Output:
Entry allowed
Here, the second condition is checked only when the first condition is true.
switch Statement#
The switch statement is useful when we want to compare one value against multiple possible values.
Syntax:
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements
}
Example:
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
Output:
Tuesday
if-else vs switch#
Both can be used for decision-making, but they are commonly used in different situations.
if-else |
switch |
|---|---|
| Useful for conditions and ranges | Useful for matching specific values |
| Supports complex boolean expressions | Commonly compares one expression with cases |
Can use >, <, >=, &&, ` |
|
| Good for ranges | Good for fixed choices |
Loops#
Introduction#
Sometimes we need to execute the same block of code multiple times.
For example:
- Print numbers from 1 to 10
- Print a message 5 times
- Calculate the sum of numbers
Writing the same statement again and again would make the program long and difficult to maintain.
For example:
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);
Instead, Java provides loops.
A loop allows us to execute a block of code repeatedly.
What Is a Loop?#
A loop is a programming structure used to execute a block of code repeatedly while a condition is satisfied.
For example:
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
Output:
1
2
3
4
5
Instead of writing five println() statements, we used a loop.
Types of Loops in Java#
Java provides several types of loops.
Loops
├── while loop
├── do-while loop
├── for loop
└── enhanced for loop
We also use:
- Nested loops
breakcontinue
Let's understand them one by one.
while Loop#
The while loop executes a block of code as long as the condition is true.
Syntax:
while (condition) {
// statements
}
Example:
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
Output:
1
2
3
4
5
do-while Loop#
The do-while loop is similar to the while loop.
The important difference is:
A
do-whileloop executes its body at least once.
Syntax:
do {
// statements
} while (condition);
Example:
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
Output:
1
2
3
4
5
while vs do-while
Consider this example.
while#
int i = 10;
while (i <= 5) {
System.out.println(i);
}
There is no output because the condition is false before the first execution.
do-while#
int i = 10;
do {
System.out.println(i);
} while (i <= 5);
Output:
10
Why?
Because the do block executes first.
Only after that does Java check the condition.
for Loop#
The for loop is commonly used when we know how many times we want to repeat something.
Syntax:
for (initialization; condition; update) {
// statements
}
Example:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
Output:
1
2
3
4
5
Enhanced for Loop#
Java also provides an enhanced for loop.
It is commonly used to iterate through arrays and collections.
Syntax:
for (dataType variable : array) {
// statements
}
Example:
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
System.out.println(number);
}
Output:
10
20
30
40
50
The enhanced for loop is also called the for-each loop.
Nested Loops#
A loop inside another loop is called a nested loop.
Example:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println(i + " " + j);
}
}
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
The inner loop executes completely for every iteration of the outer loop.
Example: Printing a Pattern
Nested loops are commonly used to create patterns.
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
Output:
*
* *
* * *
* * * *
* * * * *
break Statement#
The break statement is used to immediately terminate a loop.
Example:
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
Output:
1
2
3
4
When i becomes 5, the break statement ends the loop.
continue Statement#
The continue statement skips the current iteration and moves to the next iteration.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
Output:
1
2
4
5
The value 3 is skipped.
break vs continue#
break |
continue |
|---|---|
| Terminates the loop | Skips current iteration |
| Loop ends immediately | Loop continues |
| Used when we want to stop | Used when we want to skip |
Example:
break;
means:
Stop the loop.
Example:
continue;
means:
Skip this iteration and continue with the next one.
Infinite Loop#
An infinite loop is a loop that never ends because its condition never becomes false.
Example:
while (true) {
System.out.println("Hello");
}
This loop continues forever unless something interrupts the program.
Another example:
for (;;) {
System.out.println("Hello");
}
An infinite loop can sometimes be intentional, but an accidental infinite loop is usually a programming mistake.
while vs do-while vs for
| Feature | while |
do-while |
for |
|---|---|---|---|
| Condition checked | Before execution | After execution | Before execution |
| Minimum executions | 0 | 1 | 0 |
| Common use | Unknown number of iterations | At least one execution required | Known/repeated count |
| Syntax | Simple | Simple | Initialization + condition + update |
Which Loop Should You Use?#
A simple way to remember:
Use for
When you generally know how many times the loop should execute.
Use while
When the number of iterations may depend on a condition.
Use do-while
When the code should execute at least once.
Use Enhanced for
When you want to iterate through an array or collection.