Java Methods

  • a method is a block of code that performs a specific task and can be called by other parts of the program

  • a method consists of a method signature, which includes the method name, return type, and parameter list, and a method body, which contains the code that is executed when the method is called

Method example

public int addNumbers(int num1, int num2) {
    int sum = num1 + num2;
    return sum;
}
System.out.println(addNumbers(10, 20));
30

Java Control Structures

  • control structures are constructs that allow you to control the flow of execution in a program

  • they let you execute specific statements or blocks of code based on certain conditions

  • some examples: if-else, for loop, while loop, switch case

IntByReference

  • The IntByReference class uses the integer primitive and its function is swapping the two inputted numbers, if the first is greater than the second

  • A wrapper class is used to change a primitive int into an Integer object

  • the Integer object is turned back into a primitive type "tmp" to switch values

public class IntByReference {
    // sets primitive
    private int value;
    //wrapper class
    public IntByReference(Integer value) {
        this.value = value;
    }

    public String toString() {
        return (String.format("%d", this.value));
    }
    // function to swap the values
    public void swapToLowHighOrder(IntByReference i) {
    // if first value larger than second, then swap
        if (this.value > i.value) {
            //sets the first value back to a primitive type
            int tmp = this.value;
            this.value = i.value;
            i.value = tmp;
        }
    }

    public static void swapper(int n0, int n1) {
        IntByReference a = new IntByReference(n0); // creates objects with wrapper class using primitive int
        IntByReference b = new IntByReference(n1);
        System.out.println("Before: " + a + " " + b);
        a.swapToLowHighOrder(b); //calls method
        System.out.println("After: " + a + " " + b);
        System.out.println();
    }

    public static void main(String[] ags) {
        IntByReference.swapper(21, 16);
        IntByReference.swapper(16, 21);
        IntByReference.swapper(16, -1);
    }

}
IntByReference.main(null);
Before: 21 16
After: 16 21

Before: 16 21
After: 16 21

Before: 16 -1
After: -1 16