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 inswitch
statements to handle unexpected values.
- Use
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.