Now that it is clearer how Strings assignments and concatenation work, we will turn our attention to performing miscellaneous but frequently useful String operations. Convert Different Variables to Strings In this section we'll look at a couple of ways to convert different kinds of things into Strings. Using valueOf() Often you need to convert certain types to Strings in order to pass them to a method that accepts only a String. You can do this using the valueOf() method of the String class. System.out.println(String.valueOf(Math.PI)); //prints 3.141592653589793 There are several valueOf() methods defined for the String class, each of which takes different parameters (which means that the valueOf() method is overloaded ). All of them are static. That means that they are called on the class, not on any particular instance of the class. That is, you don't need to make an object, you can just write: String.valueOf( Math.PI); as in the preceding code. There is a separate valueOf() method for each of the primitive types, for char arrays, and one for Object . Math.PI returns a primitive double in case you were curious . | FRIDGE Psst. Remember this from Chapter 9? When you pass an object of any type into System.out.println() , that method automatically calls the toString() method of that object. So, if you don't override the toString() method, you might get something less than useful printed out. | | Using toString() A second way to convert objects to Strings is by calling the toString() method on the object. An obvious difference from the valueOf() method is that for toString() you need to have an object, whereas valueOf() is static. Here's an example. Object o = new Object(); String s = o.toString(); String d = new Double(12).toString(); System.out.println("s: " + s + " D: " + d); //prints s: java.lang.Object@194df86 D: 12.0 We create a generic object and call its toString() method. Then, we create an object of type Double, and pass a primitive double to its constructor. Its toString() method returns "12.0". What is the difference between the two? Object 's toString() method prints the name of the class, followed by the @ sign, followed by a hexadecimal representation of the hashcode for the object, which means it prints a value equivalent to the following: getClass().getName() + '@' + Integer.toHexString(hashCode()); You can do something more meaningful by implementing toString() in your own way (overriding it). Like this: public String toString() { return "Some unique-ish field:" + this.someField; } |