Reputation: 115
I'm new to Java so this question might sound stupid. I understand calling a method using an object:
Foo obj = new Foo();
obj.method();
But I don't understand the syntax for Integer.parseInt()
or Character.isDigit()
. What do the prefixes do in these cases? Is there any similarity between this and calling a method using an object of its class?
Upvotes: 1
Views: 411
Reputation: 5210
Let's imagine we want to parse a String
into an int
:
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.
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
.
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
.
Upvotes: 0
Reputation: 3391
Integer
, Float
, Double
, Character
, ... are classes for the primitive types int
, float
, double
, char
, ... and each of them have some predefined methods to use.
In this case parseInt()
method takes an String
as input and converts it into its equivalent integer. for more description take a look at this link.
Here is the Original documentation for it.
Upvotes: 2