Scenario
Let's imagine we want to parse a String
into an int
:
The Wrong Way
public static void main(String[] args) {
String asString = "1";
int asNumber = parseInt(asString); // Error
System.out.println(asNumber);
}
In this scenario we (and the compiler) don't know how the owner of the method parseInt
is and don't know the logic to execute.
The Correct Way
public static void main(String[] args) {
String asString = "1";
int asNumber = Integer.parseInt(asString); // Correct
System.out.println(asNumber);
}
Now, we (and the compiler) know that the method parseInt
is declared on Integer
.
Syntax
You are already familiar with calling method on an instance of a class (obj.method()
).
The difference to Integer.parseInt()
is, that we do not need to create an instance of Integer
to call the method parseInt
because it is a static method.
public class Integer {
public static parseInt(String value) { /* ... */ }
}
A method or variable that is declared with static
is a class member instead of a instance member. Class members are accessed by ClassName.member
.