Converting Primitive and Reference Types to Strings


Converting Primitive and Reference Types to Strings

Let's now discuss how to convert a primitive value or class object into a String . The easiest way to convert a reference type to a String is to use the toString() method. Because this method is defined in the Object class, all Java classes have access to it. The default (i.e., Object class) implementation of toString() returns the class name and its hash code. The toString() method is typically overridden in subclasses to provide a more meaningful description.

An object can also be converted into a String representation by concatenating the object to a String using the + operator. In this case, the toString() method is called by the system to return a String representation of the object. For example ”

 Date date = new Date(); System.out.println("The date and time are: " + date); 

In this code snippet, a Date object containing the current date and time values is converted to a String using the + operator.

The toString() method can only be called on a reference type. A primitive variable cannot invoke toString() . The most convenient way to convert a primitive value to a String is once again to use the + operator. When a primitive variable is concatenated to a String using the + operator, the system will generate a String representation of the primitive value. For instance, the following syntax will assign the character sequence "4" to the String object named value

 int j = 4; String value = "" + j; 

Example: Converting Primitive and Reference Types to Strings

See the "Concatenating Strings" example earlier in this chapter where a double variable is converted to a String . Also see the "Creating Strings" example where the toString() method is used to return a String representation of a Date object.



Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net