简体   繁体   中英

Why can't I call toString() on a double value?

In Java it was my understanding that every class inherits from Object. But if I call the following code, it balks:

Math.PI.toString()

It gives the error : "Static Error: No method in double has name 'toString'"

Does this mean that double does not inherit from Object? So what is double then?

Does this mean that double does not inherit from Object ?

Yes.

So what is double then?

It is a primitive type built into the language itself. There are other primitive types like char , short , int , float , boolean .

Although, the language does provide wrappers built around each of the primitive types, that extends from Object - Integer , Character , Short , Double , etc.
You can use Double.toString(double) method to get string representation.

Math.PI is double and double is primitive type which means it doesn't have any methods. If it would be Double then you would be able to call its toString method but I don't see any reason for that.

If you want to create String representation of double use

String value = String.valueOf(Math.PI);

or

String value = Double.toString(Math.PI) 

BTW String.valueOf(d) returns result of Double.toString(d) .

不,Math.PI是double(原语,而不是Double(Object),因此它不会从Object继承

That's because double is a primitive. It does not inherit from Object and doesn't have it's behavior. You can still call toString() on Double which in turn is an object.
Read more on primitives and objects in Java. This might be useful.

double is not an object, but a primitive. Therefore it does not have Object's methods such as toString() etc.

There is an Object version of double called Double which is an Object wrapper around a double .

You can create a Double by calling Double myDouble = Double.valueOf(primative);

Double also has static helper methods for common operations on primvatives such as toString

Calling Double.toString(Math.PI); is probably what you want

double is a primitive type, but you can use the Java Double class to help.

This should do what you need:

Double.toString(Math.PI)

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