1

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?

5 Answers 5

5

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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

Comments

0

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 Comments

altho String.valueOf is more performant than "" + myint as the second uses StringBuilders
@MeBigFatGuy my experience with google caliper has said that "" + myInt is faster. I don't see any benefit of String.valueOf
hmm "" + myint uses an synthetic allocation of a StringBuilder.and two appends, where the int must be changed to a String, which is done by String.valueOf... see download.oracle.com/javase/1.5.0/docs/api/java/lang/…
I'd say JUST doing String.valueOf is likely to be faster, then allocating a StringBuilder, doing some appends, and doing a String.valueOf call, followed by a toString call.
@ MeBigFatGuy Do a microbenchmark with google caliper and post the results.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.