Reputation: 57
I'm confused with primitive types in Java and the methods of converting one type to another. If, say, I have an integer and I want to convert it to a string, I need to use a static method of Integer or String, e.g.
String.valueOf(some_integer);
But if I want to convert a stirng to a char array I can use something like,
some_string.toCharArray();
My question is why? Why do I need to use a static method for the first one?
Upvotes: 1
Views: 5014
Reputation: 109
Primitive types doen't have member methods in them. Moreover they are not object. In order to make a primitive type as an Object we can make use of Wrapper Classes. Using wrapper classes you can convert int to Integer object and char to Character object and this list continues.
Answering to you question String is not a primitive type. So you can make of Instance methods of String. Whereas int is a primitive type so you have to make use of static methods to acheive the same.
Upvotes: 0
Reputation: 15347
But to be realistic, you don't need to use String.valueOf( some int ). You can either do
when building a big string:
logger.debug("I did " + myInt + " things today!" );
or if by itself
logger.debug( "" + myInt );
Upvotes: 0
Reputation: 597076
Because the argument you pass - an int
is a primitive, and primitives are not objects - you can't invoke methods on them.
If the integer was of the wrapper type Integer
, you could've used someInteger.toString()
Upvotes: 5
Reputation: 182792
Because primitive types are just that, primitive. They don't have methods.
Upvotes: 1
Reputation: 15141
Because String isn't a primitive type, it's a class (which has methods), whereas integer, short, char etc. are all primitives (which don't have methods).
Upvotes: 3