问题
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?
回答1:
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()
回答2:
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).
回答3:
Because primitive types are just that, primitive. They don't have methods.
回答4:
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 );
回答5:
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.
来源:https://stackoverflow.com/questions/4113041/question-about-java-primitive-types-methods