Converting other datatypes to String
suggest change- You can get the value of other primitive data types as a
Stringusing one of theString.valueOfmethods.
For example:
int i = 42;
String string = String.valueOf(i);
// string now equals "42"
valueOf is also overloaded for float, double, boolean, and Object. String.valueOf((Object) null) returns "null".
- You can also get any other Object (any instance of any class) as a String by calling
.toStringon it. For this to give useful output, the class must overridetoString(). Most of the standard Java library classes do, such asDateand others.
For example:
Foo foo = new Foo(); // any class
String stringifiedFoo = foo.toString();
Here stringifiedFoo contains a representation of foo as a String. If the class does not override toString(), the result is the class name, @, and a hex hash code.
You can also convert any number type to String with short notation like below.
int i = 10;
String str = i + "";
Or, more simply:
String str = 10 + "";
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents