DMCA.com Protection Status Java Programming Lesson 4 | Conditional Statements Tutorial for Beginners - ZAREEN TECH WAVE -Largest Tutorials Website For Freelancer ZAREEN TECH WAVE -Largest Tutorials Website For Freelancer

Header Ads

Java Programming Lesson 4 | Conditional Statements Tutorial for Beginners

LESSON-4: CONDITIONAL STATEMENTS



Conditional statements are one of the most important foundations of programming. They allow your program to make decisions, respond to user input, and perform different actions based on different conditions.

In this lesson, we will explore Java’s powerful decision-making tools:

  • if statements
  • if–else
  • else if
  • Nested conditions
  • Logical operators (&&, ||, !)
  • switch statement
  • Real-world coding examples

Let’s dive in!


🔷 What Are Conditional Statements?

Conditional statements help your program decide what to do next.

Example logic:

  • If a user enters the correct password → allow login
  • If temperature is high → turn on cooling system
  • If marks ≥ 40 → pass, else fail

Java provides multiple ways to perform conditional checks.

🔷 1️⃣ The if Statement — Basic Decision Making

Syntax
if (condition) { // code runs only if condition is true }

Example
int age = 20; if (age >= 18) { System.out.println("You are an adult."); }

🔷 2️⃣ The if–else Statement — Two-Way Decision

Syntax
if (condition) { // if true } else { // if false }

Example
int marks = 35; if (marks >= 40) { System.out.println("Passed"); } else { System.out.println("Failed"); }

🔷 3️⃣ The else if Ladder — Multiple Decisions

Syntax
if (condition1) { ... } else if (condition2) { ... } else if (condition3) { ... } else { // if none match }

Example
int score = 75; if (score >= 90) { System.out.println("Grade A"); } else if (score >= 80) { System.out.println("Grade B"); } else if (score >= 70) { System.out.println("Grade C"); } else { System.out.println("Grade D"); }

🔷 4️⃣ Nested if Statements — Conditions Inside Conditions

Used when a decision depends on another decision.

Example
int age = 22; boolean hasID = true; if (age >= 18) { if (hasID) { System.out.println("Entry allowed"); } else { System.out.println("ID required"); } } else { System.out.println("Underage"); }

🔷 5️⃣ Logical Operators — Combine Multiple Conditions

Operator                  Meaning                        Example
&&                     AND                    age ≥ 18 and hasID
``
!                     NOT                    reverse a condition


Example with &&

int age = 25; boolean registered = true; if (age >= 18 && registered) { System.out.println("Eligible to vote"); }


Example with ||

String day = "Sunday"; if (day.equals("Saturday") || day.equals("Sunday")) { System.out.println("Weekend"); }


Example with !

boolean isRaining = false; if (!isRaining) { System.out.println("Go outside"); }

🔷 6️⃣ The switch Statement — Clean Multi-Choice Condition

Useful when checking many fixed values.

Syntax

switch (variable) { case value1: ... break; case value2: ... break; default: ... }


Example

int day = 3; switch (day) { case 1: System.out.println("Sunday"); break; case 2: System.out.println("Monday"); break; case 3: System.out.println("Tuesday"); break; default: System.out.println("Invalid day"); }

🔷 Real-World Examples of Conditional Statements

✔ Example 1: Login Authentication

String username = "admin"; String password = "1234"; if (username.equals("admin") && password.equals("1234")) { System.out.println("Login successful"); } else { System.out.println("Login failed"); }


✔ Example 2: Positive, Negative, or Zero

int num = -5; if (num > 0) { System.out.println("Positive"); } else if (num < 0) { System.out.println("Negative"); } else { System.out.println("Zero"); }


✔ Example 3: Small Calculator Using switch

int a = 10, b = 5; char op = '+'; switch (op) { case '+': System.out.println(a + b); break; case '-': System.out.println(a - b); break; case '*': System.out.println(a * b); break; case '/': System.out.println(a / b); break; default: System.out.println("Invalid operator"); }

🔷 Common Mistakes Beginners Make

❌ Using = instead of ==

if (x = 5) // wrong

❌ Forgetting .equals() for string comparisons

if (name == "Java") // incorrect

Correct:

if (name.equals("Java"))

❌ Missing break in switch cases

Leads to unwanted fall-through.


🔷 Summary of What You Learned

In this lesson, you now understand:

  • What conditional statements are
  • How if, else, and else if work
  • How logical operators help combine conditions
  • When to use nested conditions
  • How the switch statement works
  • Real-world example programs

These decisions help your Java programs behave intelligently and interact dynamically with users.


✅ Full Practical Example

import java.util.Scanner; public class ConditionsExample { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter your age: "); int age = input.nextInt(); if(age >= 18){ System.out.println("Eligible for Voting"); } else { System.out.println("Not Eligible"); } System.out.println("Enter day number (1-7): "); int day = input.nextInt(); switch(day){ case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; default: System.out.println("Invalid Day"); } } }

📝 Exercise for You ✅

Write a program:

📌 Input
A number from user

📌 Output
Check and print whether:

✅ Positive or Negative
✅ Even or Odd
✅ Number category using switch (1 → "One", 2 → "Two", otherwise → "Other Number")

You must use:

✔ if
✔ else-if
✔ switch

Reply with:
✅ Your Code
✅ Output Screenshot or text

I will grade it ✅🔥


🎯 Quick Quiz

1️⃣ Which keyword stops switch case?
A) stop
B) exit
C) break

2️⃣ Choose valid condition:
A) if x = 10
B) if(x == 10)
C) if(x => 10)

Reply: 1 → ?, 2 → ?


✅ Lesson-4 Completed!

When you're ready →
Lesson-5: Loops (for, while, do-while) 🚀

Send your exercise + quiz answers below 👇😊


▶ NEXT PART - Lesson-5: Loops


Frequently Asked Questions (FAQs)

What are conditional statements in Java?

Conditional statements allow Java programs to make decisions by executing different blocks of code based on whether specific conditions are true or false.

What are the main types of conditional statements in Java?

Java supports if, if-else, else-if ladder, and switch statements to control decision-making in programs.

How does the if statement work in Java?

The if statement checks a boolean condition. If the condition is true, the code inside the block runs; otherwise, it is skipped.

When should I use if-else instead of just if?

Use if-else when you want the program to choose between two actions: one for true conditions and another for false conditions.

What is the else-if ladder?

The else-if ladder is used when you need to evaluate multiple conditions sequentially and execute the block of the first true condition.

What is the switch statement used for?

The switch statement simplifies multi-condition checks by matching a variable against predefined cases, making the code cleaner and more readable.

What is the role of the break statement inside a switch?

The break statement prevents fall-through by stopping further case checks once the matching case executes.

When should the default case be used in a switch?

The default case runs when none of the specified cases match. It is useful for handling unexpected or invalid values.

Can switch statements work with Strings in Java?

Yes. Since Java 7, switch statements can evaluate String values, making them helpful for menu-driven programs and text-based conditions.

How do conditional statements improve program logic?

Conditional statements enhance program flexibility by allowing dynamic decision-making, enabling programs to react intelligently to user input or system states.

No comments

Thank You For Visit My Website.
I Will Contact As Soon As Possible.

Theme images by 5ugarless. Powered by Blogger.