Java Android App Development Course, Conditional Statements and Loops

Android application development fundamentally relies on the Java programming language. Conditional statements and loops are the most basic structures in programming, and it is difficult to implement app functionality without them. In this post, I will provide a detailed explanation of conditional statements and loops using Java, along with example code to demonstrate their use.

1. Understanding Conditional Statements

Conditional statements are used to control the flow of a program based on whether a particular condition is true or false. In Java, the primary conditional statements used are if, else, and switch.

1.1 if Statement

The most basic conditional statement is the if statement. This statement executes a specific block of code when the given condition is true.

if (condition) {
    // Code to be executed if the condition is true
}

1.2 else Statement

The else statement, used in conjunction with the if statement, defines the code that will be executed if the specified condition is false.

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

1.3 else if Statement

When you need to check multiple conditions, you use else if.

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

1.4 switch Statement

The switch statement is useful when you need to select one from multiple conditions. It allows for cleaner writing and is useful when dealing with complex conditions.

switch (variable) {
    case value1:
        // Executed if value1
        break;
    case value2:
        // Executed if value2
        break;
    default:
        // Executed if no conditions match
}

2. Understanding Loops

Loops help execute a specific block of code multiple times. In Java, the main types of loops are for, while, and do while.

2.1 for Statement

The for loop is useful when the number of iterations is clear. It repeats based on an initial value, a condition, and an increment expression.

for (initialization; condition; increment) {
    // Code to be executed in loop
}

2.2 while Statement

The while loop repeats as long as the given condition is true.

while (condition) {
    // Code to be executed in loop
}

2.3 do while Statement

The do while loop executes at least once and then checks the condition for further repetition.

do {
    // Code to be executed
} while (condition);

3. Example Utilizing Conditional Statements and Loops

Now, let’s explore how conditional statements and loops are used in a simple Android app through an example.

3.1 Example: User Input-Based Calculator App

We will create a calculator app that outputs results based on two numbers and an operator input by the user. Here, we will use both conditional statements and loops.

package com.example.simplecalculator;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private EditText number1EditText, number2EditText;
    private TextView resultTextView;
    private Button calculateButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        number1EditText = findViewById(R.id.number1);
        number2EditText = findViewById(R.id.number2);
        resultTextView = findViewById(R.id.result);
        calculateButton = findViewById(R.id.calculateButton);

        calculateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calculate();
            }
        });
    }

    private void calculate() {
        String number1String = number1EditText.getText().toString();
        String number2String = number2EditText.getText().toString();
        if (number1String.isEmpty() || number2String.isEmpty()) {
            resultTextView.setText("Please fill in all input fields.");
            return;
        }

        int number1 = Integer.parseInt(number1String);
        int number2 = Integer.parseInt(number2String);
        String operator = ""; // TODO: Add operator variable here

        switch (operator) {
            case "+":
                resultTextView.setText("Result: " + (number1 + number2));
                break;
            case "-":
                resultTextView.setText("Result: " + (number1 - number2));
                break;
            case "*":
                resultTextView.setText("Result: " + (number1 * number2));
                break;
            case "/":
                if (number2 == 0) {
                    resultTextView.setText("Cannot divide by zero.");
                } else {
                    resultTextView.setText("Result: " + (number1 / number2));
                }
                break;
            default:
                resultTextView.setText("Please select a valid operator.");
                break;
        }
    }
}

4. Detailed Explanation of the Example

The code above is a simple calculator app where the user inputs two numbers and selects an operator to calculate the result.

4.1 User Input Handling

To receive two numbers from the user, we use EditText widgets. We use the getText().toString() method to retrieve the value entered by the user.

4.2 Using Conditional Statements

To check if the input values are empty, we use an if statement to prompt the user to fill in all input fields.

4.3 Using switch Statement

To perform calculations based on the operator selected by the user, we use a switch statement. Each case executes the corresponding operation, and the result is displayed in the TextView.

4.4 Exception Handling

For division operations, additional conditions are checked to prevent division by zero.

5. Conclusion

Conditional statements and loops are fundamental and crucial concepts in Java Android app development. If you have learned how to use them through the above example, you can build upon that knowledge to implement more complex logic. Appropriately using conditional statements and loops in various scenarios will help you develop useful applications.

6. Next Steps

Having mastered conditional statements and loops, the next step is to learn about data structures and algorithms. Use lists, maps, etc., to extend the functionality of your app. Additionally, you should also learn about event handling to make interactions with the user interface even richer.

Did you find this post useful? Please leave your comments!