Static predefined methods & the static keyword (course memo + handout)
Java.
The static keyword
static marks an element as belonging to the class itself, not to individual object instances. A static field is created once and shared across every instance of the class; static can apply to fields and methods (among other things).
public class MrMeeseeks {
private static int numberOfMeeseeks = 0;
private String task;
public MrMeeseeks(String task) {
this.task = task;
numberOfMeeseeks++;
}
public static int getNumberOfMeeseeks() {
return numberOfMeeseeks;
}
public String doTask() {
return "I will " + task;
}
}numberOfMeeseeksis shared by allMrMeeseeksinstances ever created.getNumberOfMeeseeks()is static and callable without any instance:MrMeeseeks.getNumberOfMeeseeks().doTask()is not static — it can only be called on a specific instance (meeseeks1.doTask()), since it depends on that instance's owntask.
class MrMeeseeksTest {
@Test
void testNumberOfMeeseeks() {
Assertions.assertEquals(0, MrMeeseeks.getNumberOfMeeseeks());
MrMeeseeks meeseeks1 = new MrMeeseeks("do the laundry");
Assertions.assertEquals(1, MrMeeseeks.getNumberOfMeeseeks());
Assertions.assertEquals("I will do the laundry", meeseeks1.doTask());
MrMeeseeks meeseeks2 = new MrMeeseeks("do the dishes");
Assertions.assertEquals(2, MrMeeseeks.getNumberOfMeeseeks());
}
}Static members are accessed via the class name, not an instance: MrMeeseeks.getNumberOfMeeseeks(). Course guidance: avoid using static in your own classes until you have more experience — it's easy to misuse (shared mutable state across every instance, harder-to-test code).
Collections static methods
Collections.reverse(collection), Collections.sort(collection), Collections.shuffle(collection).
Given names = [Lisa, Mona, Sam, Anton]:
| Call | Result |
|---|---|
Collections.reverse(names) | [Anton, Sam, Mona, Lisa] |
Collections.sort(names) | [Anton, Lisa, Mona, Sam] (via each element's compareTo) |
Collections.shuffle(names) | randomly rearranged |
These mutate the list in place rather than returning a new one — so the list passed in must be mutable (e.g. an ArrayList, not one made with List.of(...)). To get a mutable copy of an immutable list: new ArrayList<>(immutableList).
Math static methods
Math.ceil(double) — rounds up, returns a double (Math.ceil(3.5) → 4.0). Math.floor(double) — rounds down, returns a double (Math.floor(3.5) → 3.0). Math.abs(number) — absolute value, works for int or double.
Converting between types
| Method | Notes |
|---|---|
Integer.valueOf(String) | parses to an int-backed object; throws if the string isn't a valid number |
Double.valueOf(String) | parses to a double-backed object; throws if invalid |
String.valueOf(Object) | converts anything to its string form; safe — never throws |
Integer.valueOf/Double.valueOf only work when the input is genuinely numeric-looking; String.valueOf always succeeds regardless of input.