Control Structures and Functions

In this lesson, we’ll explore how Java handles control structures and functions, comparing them to their Python counterparts. We’ll see both similarities and differences that will help you transition smoothly from Python to Java.

Control Structures

If-else Statements

Java’s if-else statements are structurally similar to Python’s, but with some syntactic differences:

// Java
if (condition) {
    // code block
} else if (anotherCondition) {
    // code block
} else {
    // code block
}

Note the use of parentheses around conditions and curly braces for code blocks. Unlike Python, indentation in Java is for readability, not for defining code blocks.

Switch Expressions

Java offers switch statements, which are similar to Python’s match statements (introduced in Python 3.10). Java 12 introduced switch expressions, making them more concise:

// Java
String day = "MONDAY";
String type = switch (day) {
    case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> "Weekday";
    case "SATURDAY", "SUNDAY" -> "Weekend";
    default -> "Invalid day";
};

Loops

Java offers several types of loops:

  1. For loop:
// Java
for (int i = 0; i < 5; i++) {
    System.out.println(i);
}
  1. Enhanced for-loop (similar to Python’s for-in loop):
// Java
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}
  1. While loop:
// Java
int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}
  1. Do-while loop (not available in Python):
// Java
int i = 0;
do {
    System.out.println(i);
    i++;
} while (i < 5);

The do-while loop ensures that the code block is executed at least once before checking the condition.

Functions (Methods in Java)

In Java, functions are called methods and are always associated with a class. This is a significant difference from Python, where functions can exist independently.

Defining Methods

Here’s how you define a method in Java:

// Java
public static int add(int a, int b) {
    return a + b;
}

Let’s break this down:

  • public: Access modifier (can be called from anywhere)
  • static: Indicates that this method belongs to the class, not an instance
  • int: Return type
  • add: Method name
  • (int a, int b): Parameters with their types

Method Overloading

Java supports method overloading, which isn’t available in Python. This allows you to define multiple methods with the same name but different parameters:

// Java
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }
}

The appropriate method is called based on the argument types.

Static vs. Instance Methods

In Java, methods can be static (belonging to the class) or instance methods (belonging to an object):

// Java
public class MyClass {
    public static void staticMethod() {
        System.out.println("This is a static method");
    }

    public void instanceMethod() {
        System.out.println("This is an instance method");
    }
}

// Usage
MyClass.staticMethod(); // Call static method directly on the class
MyClass obj = new MyClass();
obj.instanceMethod(); // Call instance method on an object

Varargs and Default Arguments

Java supports varargs (variable-length arguments) using the ... syntax:

// Java
public static int sum(int... numbers) {
    int total = 0;
    for (int num : numbers) {
        total += num;
    }
    return total;
}

// Usage
int result = sum(1, 2, 3, 4, 5);

Unlike Python, Java doesn’t support default arguments directly. However, method overloading can be used to achieve similar functionality:

// Java
public void greet(String name) {
    greet(name, "Hello");
}

public void greet(String name, String greeting) {
    System.out.println(greeting + ", " + name + "!");
}

Conclusion

In this lesson, we’ve explored Java’s control structures and methods, highlighting both similarities and differences with Python. We’ve seen how Java’s syntax differs in areas like loop constructs and method definitions, and we’ve introduced concepts like method overloading that are unique to Java.

In the next lesson, we’ll dive into Arrays and Collections in Java, exploring how they compare to Python’s list and dictionary data structures. We’ll look at the Java Collections Framework and learn about the various implementations available for different use cases.