Methods¶
(a group of statements that runs when called, also reduces redundancy)
Declaration¶
Method Declaration Syntax
public static void name() {
statements;
}
Example Method Declaration
public static void printHello() {
System.out.println("Hello World");
System.out.println("Have a great day!");
System.out.println();
}
Call¶
Method Call Syntax
methodName();
Method Call Example
public static void main(String[] args) {
printHello();
printHello();
}
Method Call 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¶
Class Constant Syntax
public class ClassName() {
...
public static final <type> <name> = <value>;
}
Class Constant Example
public class Hello() {
...
public static final int DAYS_PER_WEEK = 7;
}
Parameters¶
(a way to pass information into a method)
Declaration¶
Parameter Syntax
public static void name(type name, ...) {
statements;
}
Method with Parameters 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¶
Calling Methods with Parameters Syntax
methodName(value, ..., value);
Calling Methods with Parameters Example
public static void main(String[] args) {
box(10, 7); // width = 10, height = 7
box(5, 3); // width = 5, height = 3
}
Calling Methods with Parameters Output
**********
**********
**********
**********
**********
**********
**********
*****
*****
*****