Sanjay Idpuganti
Sanjay Idpuganti

Reputation: 320

How is this static method called on a instance value wrong?

How is this legal

System.out.println("".valueOf(1121997));

And this is illegal

System.out.println(1.valueOf("1121997"));

Upvotes: 0

Views: 76

Answers (3)

dumbPotato21
dumbPotato21

Reputation: 5695

"" is a reference to a String Object, therefore has methods like length, valueOf, etc.

1 is an integer literal. It is a primitive data type, therefore you can't call methods on it.

Upvotes: 1

Mike Nakis
Mike Nakis

Reputation: 62045

"" is a string literal, and the java compiler makes sure that a String object will be automatically created for each string literal that you use in your program. So, since "" is an object, it has methods like valueOf().

On the other hand, 1 is an int literal, so there is no object created for it; it is just a primitive. Primitives do not have methods in java.

Upvotes: 5

Abhi Andhariya
Abhi Andhariya

Reputation: 560

Because "" is a String. String Class has a valueOf method, so you can call it.

For your old question,

System.out.println( 1.valueOf("1121997"));

Here 1 is primitive integer value and not Integer Wrapper class. You can not call method on primitive data types.

For your updated Question,

System.out.println((Integer) 1.valueOf("1121997"));

Here you need to wrap (Integer)1 with additional ().

System.out.println(((Integer) 1).valueOf("1121997"));

Also valueOf() is a static method. It is not a good practice to call it with instance. You should call it directly with class name like

Integer.valueOf("1121997");

Upvotes: 2

Related Questions