free web tracker
Course Content
Java Programming Basics for Android
Learn the basics of Java programming for Android app development using Android Studio. This guide covers key concepts like variables, loops, and classes to help you start building your first Android apps with confidence. Perfect for beginners!
0/10
Android UI with XML
Create stunning Android interfaces using XML in Android Studio. Learn to design responsive layouts and UI elements with Java integration for dynamic app experiences. Perfect for developers aiming to build professional Android apps.
0/7
Mastering Java Android Development – Beginner

In Android development using Java, conditional statements are essential for controlling app behavior based on different conditions. Here’s a beginner-friendly guide on how to use if, else, and switch statements effectively in Android Studio.

1. Using if Statement

The if statement allows your app to execute a block of code only if a specified condition is true.

int score = 80;

if (score > 70) {
    Log.d("Result", "You passed!");
}

2. Using if-else Statement

When you want to perform one action if a condition is true and another action if it is false, use if-else.

int score = 65;

if (score > 70) {
    Log.d("Result", "You passed!");
} else {
    Log.d("Result", "You failed!");
}

3. Using if-else if-else Statement

This is useful when you have multiple conditions to evaluate.

int score = 85;

if (score >= 90) {
    Log.d("Result", "Excellent");
} else if (score >= 75) {
    Log.d("Result", "Good");
} else if (score >= 60) {
    Log.d("Result", "Pass");
} else {
    Log.d("Result", "Fail");
}

4. Using switch Statement

The switch statement is best when you want to compare one variable against multiple constant values.

int day = 3;

switch (day) {
    case 1:
        Log.d("Day", "Monday");
        break;
    case 2:
        Log.d("Day", "Tuesday");
        break;
    case 3:
        Log.d("Day", "Wednesday");
        break;
    default:
        Log.d("Day", "Unknown day");
        break;
}

Tips:

    • Use if-else for range-based conditions (e.g., score > 80).
    • Use switch for exact value matching (e.g., menu options, day number).
    • Always include a default case in switch statements to handle unexpected values.

Conclusion

Mastering if, else, and switch statements in Java will help you control the flow of your Android apps and make decisions based on user inputs or app data. These statements form the core of logical thinking in programming.