1

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?

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Not Euler
  • 115
  • 4
  • 2
    [`Integer`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/Integer.html) is a class. It is the [wrapper-class](https://docs.oracle.com/javase/tutorial/java/data/numberclasses.html) for the primitive `int`. – Turing85 Jan 26 '20 at 21:58
  • 2
    it is a static method, you don't need an instance to call it, so just the class name https://stackoverflow.com/questions/2671496/java-when-to-use-static-methods – azro Jan 26 '20 at 21:58
  • 1
    @Turing85 Oh! So it is a static method defined for the class Integer? – Not Euler Jan 26 '20 at 22:00
  • Yes. Yes it is. – Turing85 Jan 26 '20 at 22:02
  • 2
    It is a `static` method belonging to the class called `Integer`. Static methods belong to the class itself, not to instances/objects of it. So you call it on the class, `Foo.bar()`. – Zabuzard Jan 26 '20 at 22:08

2 Answers2

2

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.

Mohsen_Fatemi
  • 2,183
  • 2
  • 16
  • 25
0

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.

Roman
  • 4,922
  • 3
  • 22
  • 31