day-40: Conditional Statements in Java

Conditional statements allow you to control the flow of your program based on different conditions. Java supports the following types: 1). if statement 2). if-else statement 3). if-else-if ladder 4). Nested if 5). switch-case statement *1). if Statement * Executes a block of code only if the condition is true. Syntax if (condition) { // Code to execute if condition is true } Example int age = 18; if (age >= 18) { System.out.println("You are an adult."); } Output: You are an adult. *2). if-else Statement * Executes one block if the condition is true, and another if false. Syntax if (condition) { // Code if true } else { // Code if false } Example int num = 10; if (num % 2 == 0) { System.out.println("Even"); } else { System.out.println("Odd"); } Output: Even 3). if-else-if Ladder Checks multiple conditions in sequence. Syntax if (condition1) { // Code if condition1 is true } else if (condition2) { // Code if condition2 is true } else { // Code if all conditions are false } Example (Grading System) int marks = 85; if (marks >= 90) { System.out.println("Grade A"); } else if (marks >= 80) { System.out.println("Grade B"); } else if (marks >= 70) { System.out.println("Grade C"); } else { System.out.println("Grade D"); } Output: Grade B 4). Nested if An if inside another if. Syntax if (condition1) { if (condition2) { // Code if both conditions are true } } Example (Login System) String username = "admin"; String password = "12345"; if (username.equals("admin")) { if (password.equals("12345")) { System.out.println("Login successful!"); } else { System.out.println("Wrong password."); } } else { System.out.println("Invalid username."); } Output: Login successful! 5). switch-case Statement Used when you have multiple conditions based on a single variable. Syntax switch (variable) { case value1: // Code for value1 break; case value2: // Code for value2 break; default: // Code if no case matches } Example (Day of Week) int day = 3; 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: Wednesday Important Notes on switch-case: break prevents "fall-through" (execution of subsequent cases). default runs if no case matches. Java 14+ supports switch expressions (simplified syntax). Key Takeaways Statement Use Case if Single condition check if-else Two possible outcomes if-else-if Multiple conditions Nested if Conditions inside conditions switch-case Multiple fixed-value checks Common Mistakes to Avoid ❌ Using = instead of == if (x = 5) → Wrong (assignment) if (x == 5) → Correct (comparison) ❌ Missing break in switch-case Causes unintended fall-through. ❌ Comparing strings with == Use str1.equals(str2) instead. When to Use What? Use if-else for range-based conditions (e.g., age > 18). Use switch-case for fixed-value checks (e.g., day == 3). Ternary Operator vs. if Statement in Java Both are used for conditional logic, but they serve different purposes. 1). Ternary Operator (? :) A shorthand for simple if-else conditions. Returns a value (used in assignments). Syntax variable = (condition) ? valueIfTrue : valueIfFalse; Example int age = 18; String status = (age >= 18) ? "Adult" : "Minor"; System.out.println(status); // Output: "Adult" When to Use? ✔ Short, simple conditions (e.g., setting a variable). ✔ Avoids multiple lines of if-else. Limitations ❌ Cannot execute multiple statements. ❌ Less readable for complex conditions. 2). if Statement Used for general conditional logic. Can execute multiple statements. Syntax if (condition) { // code if true } else { // code if false } Example int age = 18; if (age >= 18) { System.out.println("Adult"); System.out.println("You can vote!"); } else { System.out.println("Minor"); } When to Use? ✔ Complex conditions (multiple checks). ✔ When you need multiple statements inside a branch. Key Differences Feature Ternary Operator (? :) if Statement Purpose Returns a value Executes code blocks Best for Simple conditions Complex logic Multi-line ❌ No ✔ Yes Readability Good for short conditions Better for long logic When to Choose Which? Use Ternary → Assigning values based on a condition. java int discount = (isMember) ? 10 : 0; Use if → Multiple operations or nested conditions. if (temperature > 30) { System.out.println("Hot"); turnOnAC(); } else { System.out.println("Cool"); } Advanced: Nested Ternary (Avoid if Possible) int num = 10; String result = (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero"; System.out.pri

May 8, 2025 - 05:31
 0
day-40: Conditional Statements in Java

Conditional statements allow you to control the flow of your program based on different conditions. Java supports the following types:

1). if statement
2). if-else statement
3). if-else-if ladder
4). Nested if
5). switch-case statement

*1). if Statement *
Executes a block of code only if the condition is true.

Syntax

if (condition) {
    // Code to execute if condition is true
}

Example

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

Output:
You are an adult.

*2). if-else Statement *
Executes one block if the condition is true, and another if false.

Syntax

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

Example

int num = 10;
if (num % 2 == 0) {
    System.out.println("Even");
} else {
    System.out.println("Odd");
}

Output:
Even

3). if-else-if Ladder
Checks multiple conditions in sequence.

Syntax

if (condition1) {
    // Code if condition1 is true
} else if (condition2) {
    // Code if condition2 is true
} else {
    // Code if all conditions are false
}

Example (Grading System)

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

Output:
Grade B

4). Nested if
An if inside another if.

Syntax

if (condition1) {
    if (condition2) {
        // Code if both conditions are true
    }
}

Example (Login System)

String username = "admin";
String password = "12345";

if (username.equals("admin")) {
    if (password.equals("12345")) {
        System.out.println("Login successful!");
    } else {
        System.out.println("Wrong password.");
    }
} else {
    System.out.println("Invalid username.");
}

Output:
Login successful!

5). switch-case Statement
Used when you have multiple conditions based on a single variable.

Syntax

switch (variable) {
    case value1:
        // Code for value1
        break;
    case value2:
        // Code for value2
        break;
    default:
        // Code if no case matches
}

Example (Day of Week)

int day = 3;
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:
Wednesday

Important Notes on switch-case:
break prevents "fall-through" (execution of subsequent cases).

default runs if no case matches.

Java 14+ supports switch expressions (simplified syntax).

Key Takeaways
Statement Use Case
if Single condition check
if-else Two possible outcomes
if-else-if Multiple conditions
Nested if Conditions inside conditions
switch-case Multiple fixed-value checks
Common Mistakes to Avoid
❌ Using = instead of ==

if (x = 5) → Wrong (assignment)
if (x == 5) → Correct (comparison)

❌ Missing break in switch-case

Causes unintended fall-through.

❌ Comparing strings with ==
Use str1.equals(str2) instead.

When to Use What?
Use if-else for range-based conditions (e.g., age > 18).
Use switch-case for fixed-value checks (e.g., day == 3).

Ternary Operator vs. if Statement in Java
Both are used for conditional logic, but they serve different purposes.

1). Ternary Operator (? :)
A shorthand for simple if-else conditions.
Returns a value (used in assignments).

Syntax
variable = (condition) ? valueIfTrue : valueIfFalse;

Example

int age = 18;
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println(status); // Output: "Adult"

When to Use?
✔ Short, simple conditions (e.g., setting a variable).
✔ Avoids multiple lines of if-else.

Limitations
❌ Cannot execute multiple statements.
❌ Less readable for complex conditions.

2). if Statement
Used for general conditional logic.
Can execute multiple statements.

Syntax

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

Example

int age = 18;
if (age >= 18) {
    System.out.println("Adult");
    System.out.println("You can vote!");
} else {
    System.out.println("Minor");
}

When to Use?
✔ Complex conditions (multiple checks).
✔ When you need multiple statements inside a branch.

Key Differences
Feature Ternary Operator (? :) if Statement
Purpose Returns a value Executes code blocks
Best for Simple conditions Complex logic
Multi-line ❌ No ✔ Yes
Readability Good for short conditions Better for long logic
When to Choose Which?
Use Ternary → Assigning values based on a condition.

java
int discount = (isMember) ? 10 : 0;
Use if → Multiple operations or nested conditions.

if (temperature > 30) {
    System.out.println("Hot");
    turnOnAC();
} else {
    System.out.println("Cool");
}

Advanced: Nested Ternary (Avoid if Possible)

int num = 10;
String result = (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero";
System.out.println(result); // "Positive"

⚠ Warning: Nested ternaries reduce readability. Prefer if-else for clarity.

Final Advice
Ternary → Best for one-liners (e.g., variable assignments).

if → Best for complex logic (multiple conditions/statements).

----------------------------------- assisted by ai ---------------------------------------