24su ver.

Note: this is for the Summer 2024 iteration of CSE 121. Looking for a different quarter? Please visit https://courses.cs.washington.edu/courses/cse121/.

Methods

(a group of statements that runs when called, also reduces redundancy)

Declaration

Syntax

public static void name() {
    statements;
}

Example

public static void printHello() {
    System.out.println("Hello World");
    System.out.println("Have a great day!");
    System.out.println();
}

Call

Syntax

methodName();

Example

public static void main(String[] args) {
    printHello();
    printHello();
}

Output

Hello World
Have a great day!

Hello World
Have a great day!

Class Constant

(unchangeable global values that can be seen within your class)

Declaration

Syntax

public class ClassName() {
    ...
    public static final <type> <name> = <value>;
}

Example

public class Hello() {
    ...
    public static final int DAYS_PER_WEEK = 7;
}

Parameters

(a way to pass information into a method)

Declaration

Syntax

public static void name(type name, ...) {
    statements;
}

Example

public static void box(int width, int height) {
    for (int i = 1; i <= height; i++) {
        for (int j = 1; j <= width; j++) {
            System.out.print("*");
        }
        System.out.println();
    }
}

Call

Syntax

methodName(value, ..., value);

Example

public static void main(String[] args) {
    box(10, 7); // width = 10, height = 7
    box(5, 3);  // width = 5, height = 3
}

Output

**********
**********
**********
**********
**********
**********
**********
*****
*****
*****