[Go to site: main page, start]

0% found this document useful (0 votes)
4 views18 pages

Java Operators & Control Statements Guide

Uploaded by

elonrmuxk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views18 pages

Java Operators & Control Statements Guide

Uploaded by

elonrmuxk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

🧭 Complete Beginner-Friendly Tutorial: Operators and Control

Statements in Java
Duration: 3 to 4 hours (with demos)
Audience: Complete Beginners

🔹 1. Introduction
What is a Java Program?
Think of a Java program like a recipe for cooking:

A recipe has ingredients (data/variables)

A recipe has steps (instructions)

A recipe has decisions ("if onions are brown, add tomatoes")

In programming, execution flow and logic depend on two things:

Operators → Think of these as ACTION WORDS like "add", "subtract", "compare"

Control Statements → Think of these as DECISION MAKERS like "if this happens, do that"

Every Java application—from payroll to web backend—uses them in every module.

🔹 2. Java Operators
📘 What is an Operator?
Simple Definition: An operator is a symbol that tells Java to do something with numbers or values.

Real-Life Example:

In math class: 5 + 3 → The "+" tells you to ADD

In Java: Same thing! The "+" tells computer to ADD

Example:

java

int total = x + y;

Breaking it down:

x and y are like boxes holding numbers

+ is the operator (it means ADD)

total is where we store the answer

🔸 Types of Operators in Java


Let me explain each type in simple words:

Type What it does Example Think of it as

Arithmetic Does math +-*/% Calculator buttons

Relational Compares things > < >= <= "Is this bigger than that?"

Logical Combines questions `&&

Assignment Stores values = += -= Putting things in a box

Ternary Quick if-else ?: "If yes, this; else that"


 
🧩 3. Arithmetic Operators (Like Your Calculator)
What are Arithmetic Operators?
Simple Definition: These do basic math operations like addition, subtraction, multiplication, division.

Think of: Your calculator buttons!

The Basic Five Operations

java

public class ArithmeticExample {


public static void main(String[] args) {
int x = 15; // First number
int y = 4; // Second number

// 1. ADDITION (+) - Adding two numbers


[Link]("Addition: " + (x + y)); // 15 + 4 = 19

// 2. SUBTRACTION (-) - Taking away


[Link]("Subtraction: " + (x - y)); // 15 - 4 = 11

// 3. MULTIPLICATION (*) - Repeated addition


[Link]("Multiplication: " + (x * y)); // 15 × 4 = 60

// 4. DIVISION (/) - Splitting into equal parts


[Link]("Division: " + (x / y)); // 15 ÷ 4 = 3

// 5. MODULUS (%) - Remainder after division


[Link]("Modulus: " + (x % y)); // 15 ÷ 4 = 3, remainder 2
}
}

Output:

Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3
Modulus: 3

💡 Understanding MODULUS (%) - The Remainder Operator


What is Modulus? When you divide and have something left over, that leftover is called REMAINDER.

Real-Life Example: You have 15 candies and 4 friends.

Each friend gets: 15 ÷ 4 = 3 candies

Candies left with you: 15 % 4 = 3 candies (remainder)

Visual Explanation:

3 ← Each friend gets 3 (quotient)


---
4 | 15
12 ← 4 friends × 3 candies = 12 given away
---
3 ← 3 candies left (remainder)

So: 15 / 4 = 3 (quotient) and 15 % 4 = 3 (remainder)

💡 Real-world Use:
Bank systems use these for calculating interest, loan EMI

Shopping apps use these to calculate total bill, discounts


➤ Increment (++) and Decrement (--)
Simple Definition:

++ means "add 1"

-- means "subtract 1"

Why do we need this? Instead of writing num = num + 1 , we can simply write num++

java

public class IncrementDemo {


public static void main(String[] args) {
int num = 5;

// POST-INCREMENT (num++)
// Meaning: Use the current value FIRST, then add 1
[Link](num++); // Prints: 5 (uses current value)
[Link](num); // Prints: 6 (now it's increased)

// PRE-INCREMENT (++num)
// Meaning: Add 1 FIRST, then use the new value
[Link](++num); // Prints: 7 (increased first, then print)

// POST-DECREMENT (num--)
[Link](num--); // Prints: 7 (uses current value)
[Link](num); // Prints: 6 (now it's decreased)

// PRE-DECREMENT (--num)
[Link](--num); // Prints: 5 (decreased first, then print)
}
}

Easy Way to Remember:

POST (num++): Use it, THEN change it

PRE (++num): Change it, THEN use it

Use Case: Counting pages, tracking number of students, serial numbers.

🧮 4. Relational Operators (Comparing Things)


What are Relational Operators?
Simple Definition: These operators COMPARE two things and answer with TRUE or FALSE.

Think of: Asking questions like "Is A bigger than B?"

Real-Life Example:

"Is your age greater than 18?" → Yes (true) or No (false)

"Is the price less than 100?" → Yes (true) or No (false)

All Comparison Operators

java
public class RelationalDemo {
public static void main(String[] args) {
int userAge = 20;

// Greater than (>)


[Link]("Is age > 18? " + (userAge > 18)); // true

// Less than (<)


[Link]("Is age < 18? " + (userAge < 18)); // false

// Greater than or equal to (>=)


[Link]("Is age >= 20? " + (userAge >= 20)); // true

// Less than or equal to (<=)


[Link]("Is age <= 15? " + (userAge <= 15)); // false

// Equal to (==)
// IMPORTANT: Use == (two equal signs) for comparison!
[Link]("Is age == 20? " + (userAge == 20)); // true

// Not equal to (!=)


[Link]("Is age != 18? " + (userAge != 18)); // true
}
}

⚠️ Common Beginner Mistake


java

// WRONG - This is assignment (storing value)


if (age = 18) { } // ❌ This gives ERROR!

// CORRECT - This is comparison (checking value)


if (age == 18) { } // ✅ This is correct!

Remember:

ONE equal sign = → Store/Assign

TWO equal signs == → Compare/Check

Use Case:

Checking if user is old enough to vote

Checking if bank balance is sufficient

Checking if password length is valid

⚙️ 5. Logical Operators (Combining Questions)


What are Logical Operators?
Simple Definition: These operators combine MULTIPLE questions into one.

Think of: Making complex decisions in real life.

The Three Logical Operators

1. AND Operator (&&)

Meaning: BOTH conditions must be TRUE

Real-Life Example: "You can ride the roller coaster IF you are tall enough AND you are brave"

If you're tall BUT not brave → NO

If you're brave BUT not tall → NO


If you're BOTH tall AND brave → YES!

java

public class LogicalDemo {


public static void main(String[] args) {
int userAge = 25;
double monthlyIncome = 80000;

// Both conditions must be TRUE


if (userAge > 18 && monthlyIncome > 50000) {
[Link]("Eligible for premium credit card");
}

// Explanation:
// userAge > 18 → TRUE (25 is greater than 18)
// monthlyIncome > 50000 → TRUE (80000 is greater than 50000)
// TRUE && TRUE → TRUE, so message prints!
}
}

2. OR Operator (||)

Meaning: At least ONE condition must be TRUE

Real-Life Example: "You get discount IF you are a student OR you are a senior citizen"

If you're a student → YES (discount!)

If you're a senior citizen → YES (discount!)

If you're both → YES (discount!)

If you're neither → NO (no discount)

java

public class OrOperatorDemo {


public static void main(String[] args) {
boolean isStudent = true;
boolean isSenior = false;

// At least ONE must be TRUE


if (isStudent || isSenior) {
[Link]("You get 20% discount!");
}

// Explanation:
// isStudent → TRUE
// isSenior → FALSE
// TRUE || FALSE → TRUE, so discount applies!
}
}

3. NOT Operator (!)

Meaning: Reverses TRUE to FALSE and FALSE to TRUE

Real-Life Example: "If it is NOT raining, let's go out"

java
public class NotOperatorDemo {
public static void main(String[] args) {
boolean isRaining = false;

// NOT operator reverses the value


if (!isRaining) {
[Link]("Let's go outside!");
}

// Explanation:
// isRaining → FALSE
// !isRaining → TRUE (reversed!)
// So, message prints!
}
}

Truth Table (Simple Guide)


AND (&&) - Both must be true:

TRUE && TRUE → TRUE ✓


TRUE && FALSE → FALSE ✗
FALSE && TRUE → FALSE ✗
FALSE && FALSE → FALSE ✗

OR (||) - At least one must be true:

TRUE || TRUE → TRUE ✓


TRUE || FALSE → TRUE ✓
FALSE || TRUE → TRUE ✓
FALSE || FALSE → FALSE ✗

Use Case: Loan approval, user eligibility checks, access control systems.

🧠 6. Assignment Operators (Storing Values)


What are Assignment Operators?
Simple Definition: These operators PUT values into variables (boxes).

Think of: Putting items into a storage box.

Simple Assignment (=)

java

int value = 10; // Put 10 into the box called 'value'

Compound Assignment Operators (Shortcuts)


Instead of writing long code, we can use shortcuts:

java
public class AssignmentDemo {
public static void main(String[] args) {
int value = 10;
[Link]("Starting value: " + value); // 10

// LONG WAY: value = value + 5


// SHORT WAY: value += 5
value += 5; // Means: Add 5 to current value
[Link]("After += 5: " + value); // 15

// LONG WAY: value = value * 2


// SHORT WAY: value *= 2
value *= 2; // Means: Multiply current value by 2
[Link]("After *= 2: " + value); // 30

// Other shortcuts:
value -= 10; // Subtract 10 → value becomes 20
value /= 2; // Divide by 2 → value becomes 10
value %= 3; // Remainder when divided by 3 → value becomes 1

[Link]("Final value: " + value); // 1


}
}

Simple Explanation:

+= → Add and store

-= → Subtract and store

*= → Multiply and store

/= → Divide and store

%= → Remainder and store

Use Case:

Keeping running total in shopping cart

Updating bank balance after transaction

Calculating salary increments

💡 7. Ternary Operator (Quick If-Else)


What is Ternary Operator?
Simple Definition: A SHORTCUT way to write simple if-else in ONE line.

Think of: Quick decision making.

Syntax (Pattern)

variable = (question) ? answerIfYes : answerIfNo;

Read it as: "If question is true, use answerIfYes, otherwise use answerIfNo"

Example

java
public class TernaryDemo {
public static void main(String[] args) {
int studentMarks = 65;

// Using ternary operator


String outcome = (studentMarks >= 40) ? "Pass" : "Fail";
[Link](outcome); // Pass

// This is same as writing:


// if (studentMarks >= 40) {
// outcome = "Pass";
// } else {
// outcome = "Fail";
// }
}
}

Breaking it down:

1. (studentMarks >= 40) → The QUESTION (Is marks 40 or more?)

2. ? → IF yes

3. "Pass" → Give this answer

4. : → ELSE (otherwise)

5. "Fail" → Give this answer

More Examples

java

public class TernaryExamples {


public static void main(String[] args) {
// Example 1: Even or Odd
int number = 7;
String type = (number % 2 == 0) ? "Even" : "Odd";
[Link](number + " is " + type); // 7 is Odd

// Example 2: Discount eligibility


int age = 70;
double price = 500;
double finalPrice = (age > 60) ? price * 0.5 : price;
[Link]("Price: ₹" + finalPrice); // Price: ₹250.0
}
}

Use Case:

Quick validations in forms

Simple discount calculations

Status messages (Active/Inactive)

🏗️ 8. Special Operators (new, dot, instanceof)


8.1 The 'new' Operator
Simple Definition: Creates NEW objects (like creating a new car from a blueprint).

Think of: A car factory making a new car.

java
class Car {
void start() {
[Link]("Car started");
}
}

public class ObjectDemo {


public static void main(String[] args) {
// 'new' creates a NEW car object
Car vehicle = new Car();

// Explanation:
// Car → Blueprint/Design
// new Car() → Actually making the car
// vehicle → Name we give to this car
}
}

8.2 The Dot (.) Operator


Simple Definition: Used to ACCESS things inside an object.

Think of: Opening a box and taking out items.

java

class Car {
void start() {
[Link]("Car started");
}
}

public class ObjectDemo {


public static void main(String[] args) {
Car vehicle = new Car();

// Dot operator accesses the start() method


[Link](); // Output: Car started

// Read as: "vehicle, do your start() action"


}
}

8.3 The 'instanceof' Operator


Simple Definition: Checks if an object is of a specific TYPE.

Think of: "Is this a Car?" "Is this a Dog?"

java

class Car {
void start() {
[Link]("Car started");
}
}

public class ObjectDemo {


public static void main(String[] args) {
Car vehicle = new Car();

// Check: Is 'vehicle' a Car?


if (vehicle instanceof Car) {
[Link]("Yes, it's a Car object");
}
}
}
Use Case:

Creating objects in games (new Player, new Enemy)

Type checking before using objects

Accessing object properties and methods

🎯 CONTROL STATEMENTS
What are Control Statements?
Simple Definition: Instructions that CONTROL which code runs and HOW MANY TIMES it runs.

Think of: Traffic signals controlling cars - sometimes stop, sometimes go, sometimes wait.

🔹 1. Decision Making Statements (If-Else Family)


1.1 The 'if' Statement
Simple Definition: "IF this is true, DO this"

Think of: "If it's raining, take umbrella"

Pattern:

if (condition) {
// Do this when condition is TRUE
}

Example

java

public class IfDemo {


public static void main(String[] args) {
int studentMarks = 90;

// If marks are more than 80, print message


if (studentMarks > 80) {
[Link]("Excellent!");
}

// Explanation:
// studentMarks > 80 → 90 > 80 → TRUE
// So, the message prints!
}
}

1.2 The 'if-else' Statement


Simple Definition: "IF this is true, DO this, ELSE DO that"

Think of: "If it's raining, take umbrella, else take sunglasses"

Pattern:

if (condition) {
// Do this when TRUE
} else {
// Do this when FALSE
}
Example

java

public class IfElseDemo {


public static void main(String[] args) {
int personAge = 16;

if (personAge >= 18) {


[Link]("Eligible to vote");
} else {
[Link]("Not eligible");
}

// Explanation:
// personAge >= 18 → 16 >= 18 → FALSE
// So, "else" part executes: "Not eligible"
}
}

1.3 The 'if-else-if' Ladder


Simple Definition: Check MULTIPLE conditions one by one.

Think of: Choosing grades based on marks:

If marks ≥ 90 → Grade A

Else if marks ≥ 75 → Grade B

Else if marks ≥ 60 → Grade C

Else → Fail

java

public class LadderDemo {


public static void main(String[] args) {
int yearsOfExp = 7;

if (yearsOfExp <= 2) {
[Link]("Associate Engineer");
} else if (yearsOfExp <= 5) {
[Link]("Software Engineer");
} else if (yearsOfExp <= 9) {
[Link]("Senior Software Engineer");
} else {
[Link]("Manager");
}

// Explanation:
// Check 1: 7 <= 2? NO
// Check 2: 7 <= 5? NO
// Check 3: 7 <= 9? YES! → Print "Senior Software Engineer"
}
}

Use Case:

Grade calculation based on marks

Role assignment based on experience

Tax calculation based on income slabs


🔄 2. The 'switch' Statement
What is switch?
Simple Definition: Check ONE variable against MANY possible values.

Think of: A TV remote - pressing different buttons gives different channels.

When to use:

When you have ONE thing to check

When it can have MANY exact values (1, 2, 3... or Monday, Tuesday...)

Pattern

switch (variable) {
case value1:
// Do this if variable == value1
break;
case value2:
// Do this if variable == value2
break;
default:
// Do this if no match
}

Example

java

import [Link];

public class SwitchDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter day number (1-7): ");
int dayNum = [Link]();

switch (dayNum) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid day");
}
[Link]();
}
}
Explanation:

If dayNum is 1 → Print "Monday"

If dayNum is 2 → Print "Tuesday"

And so on...

If dayNum is anything else → Print "Invalid day"

⚠️ Why we need 'break'?


Without break: Code keeps running to next cases (fall-through) With break: Stops after matching case

Use Case:

Menu systems (press 1 for this, 2 for that)

Day/Month selection

Operation selection (calculator)

🔁 3. Looping Statements (Repeating Code)


What is a Loop?
Simple Definition: A way to repeat code MULTIPLE times automatically.

Real-Life Examples:

Counting from 1 to 100 (you repeat "say next number")

Brushing each tooth (you repeat "brush this tooth, move to next")

Checking attendance (you repeat "call name, mark present/absent")

3.1 The 'while' Loop


Simple Definition: "WHILE condition is true, KEEP repeating"

Think of: "While you're hungry, keep eating"

Pattern:

while (condition) {
// Do this repeatedly
// UPDATE something to eventually make condition false
}

Example

java
public class WhileLoop {
public static void main(String[] args) {
int counter = 1;

while (counter <= 5) {


[Link]("Count: " + counter);
counter++; // IMPORTANT: Increase counter
}

// How it works:
// Round 1: counter=1, 1<=5? YES → Print "Count: 1", counter becomes 2
// Round 2: counter=2, 2<=5? YES → Print "Count: 2", counter becomes 3
// Round 3: counter=3, 3<=5? YES → Print "Count: 3", counter becomes 4
// Round 4: counter=4, 4<=5? YES → Print "Count: 4", counter becomes 5
// Round 5: counter=5, 5<=5? YES → Print "Count: 5", counter becomes 6
// Round 6: counter=6, 6<=5? NO → STOP!
}
}

⚠️ DANGER: If you forget to update counter++ , loop never stops! (Infinite loop)

Use Case:

Password retry (while password is wrong, ask again)

ATM (while user doesn't choose exit, show menu)

3.2 The 'do-while' Loop


Simple Definition: DO something first, THEN check if you should repeat.

Difference from while: Executes AT LEAST ONCE.

Think of: "Try the food first, then decide if you want more"

Pattern:

do {
// Do this first
} while (condition);

Example

java

public class DoWhileLoop {


public static void main(String[] args) {
int counter = 1;

do {
[Link]("Executed at least once: " + counter);
counter++;
} while (counter <= 5);

// Always runs once, then checks condition


}
}

Use Case:

Menu systems (show menu at least once)

User input validation (ask at least once)

3.3 The 'for' Loop


Simple Definition: When you know EXACTLY how many times to repeat.

Think of: "Do this 10 times" or "Count from 1 to 100"


Pattern:

for (start; condition; update) {


// Do this repeatedly
}

Example

java

public class ForLoop {


public static void main(String[] args) {
// Count from 1 to 5
for (int counter = 1; counter <= 5; counter++) {
[Link]("Iteration " + counter);
}

// Breaking it down:
// int counter = 1 → START: counter begins at 1
// counter <= 5 → CONDITION: continue while counter is ≤ 5
// counter++ → UPDATE: increase counter by 1 after each round
}
}

How for loop works:

1. Run START part once (int counter = 1)

2. Check CONDITION (counter <= 5?)

3. If TRUE: Execute code inside { }

4. Run UPDATE part (counter++)

5. Go back to step 2

6. If FALSE: Stop loop

Use Case:

Print multiplication table

Count numbers

Process array elements

3.4 The 'for-each' Loop (Enhanced For)


Simple Definition: Automatically go through ALL items in a list/array.

Think of: "For each student in class, take attendance"

Pattern:

for (dataType item : collection) {


// Use item
}

Example

java
public class ForEachDemo {
public static void main(String[] args) {
int[] examScores = {90, 80, 70, 60};

// For each score in examScores array


for (int score : examScores) {
[Link]("Score: " + score);
}

// Explanation:
// Round 1: score = 90 → Print "Score: 90"
// Round 2: score = 80 → Print "Score: 80"
// Round 3: score = 70 → Print "Score: 70"
// Round 4: score = 60 → Print "Score: 60"
// No more items → Stop
}
}

Use Case:

Going through all students

Processing all products

Reading all file names

🔹 4. Nested Loops (Loops Inside Loops)


What are Nested Loops?
Simple Definition: A loop INSIDE another loop.

Think of:

Outer loop: Going through each floor of a building

Inner loop: Going through each room on that floor

Pattern Printing Example

java

public class StarPattern {


public static void main(String[] args) {
// Outer loop: Controls ROWS (how many lines)
for (int row = 1; row <= 5; row++) {

// Inner loop: Controls COLUMNS (how many stars per line)


for (int col = 1; col <= row; col++) {
[Link]("* ");
}

[Link](); // Move to next line


}
}
}

How it works:

Row 1: Inner loop runs 1 time → *


Row 2: Inner loop runs 2 times → * *
Row 3: Inner loop runs 3 times → * * *
Row 4: Inner loop runs 4 times → * * * *
Row 5: Inner loop runs 5 times → * * * * *

Use Case:
Pattern printing

Processing 2D data (like spreadsheets)

Comparing every item with every other item

🔹 5. Branching Statements (Jump Controls)


5.1 The 'break' Statement
Simple Definition: STOP the loop immediately and exit.

Think of: Finding what you're looking for → stop searching!

java

public class BreakDemo {


public static void main(String[] args) {
// Find first number greater than 5
for (int num = 1; num <= 10; num++) {
[Link]("Checking: " + num);

if (num > 5) {
[Link]("Found it! Stopping.");
break; // Exit loop immediately
}
}
[Link]("Loop ended");

// Output:
// Checking: 1
// Checking: 2
// Checking: 3
// Checking: 4
// Checking: 5
// Checking: 6
// Found it! Stopping.
// Loop ended
}
}

5.2 The 'continue' Statement


Simple Definition: SKIP current round, go to next round.

Think of: Skipping songs you don't like in a playlist.

java

public class ContinueDemo {


public static void main(String[] args) {
// Print only even numbers
for (int num = 1; num <= 10; num++) {

if (num % 2 != 0) {
continue; // Skip odd numbers
}

[Link](num);
}

// Output: 2, 4, 6, 8, 10
// (Skips 1, 3, 5, 7, 9)
}
}
break vs continue

java

public class BreakVsContinue {


public static void main(String[] args) {
[Link]("=== WITH BREAK ===");
for (int num = 1; num <= 5; num++) {
if (num == 3) {
break; // STOPS entire loop
}
[Link](num);
}
// Output: 1, 2 (then STOPS)

[Link]("\n=== WITH CONTINUE ===");

You might also like