简体   繁体   中英

Question about Java Primitive Types methods

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, eg

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?

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()

因为String不是原始类型,所以它是一个类(具有方法),而integer,short,char等都是原始体(没有方法)。

Because primitive types are just that, primitive. They don't have methods.

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 );

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM