THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
int String.valueOf(int) Integer.parseInt(String, int base)

long String.valueOf(long) Long.parseLong(String, int base)

float String.valueOf(float) Float.parseFloat(String)

double String.valueOf(double) Double.parseDouble(String)

To convert a primitive type to a String you invoke one of the static valueOf methods of String, which
for numeric types produces a base 10 representation.


The Integer and Long wrapper classesas described in Chapter 8also provide methods
toBinaryString, toOctalString, and toHexString for other representations.


To convert, or more accurately to parse a string into a primitive type you invoke the static parseType
method of the primitives type's corresponding wrapper class. Each parsing method has its own rules about the
allowed format of the string, for example Float.parseFloat will accept a floating-point literal of the
form "3.14f", whereas Long.parseLong will not accept the string "25L". These numeric parsing
methods have two overloaded forms: one that takes a numeric base between 2 and 32 in addition to the string
to parse; and one that takes only the string and assumes base 10. These parsing methods will also reject the
string if it has characters representing the base of the number, such as "0x12FE" for a hexadecimal value, or
"\033" for an octal value. However, the Integer and Long wrapper classes also provide a static decode
method that will parse a string that does include this base information. For the numeric types, if the string
does not represent a valid value of that type, a NumberFormatException is thrown.


To convert a String to a char you simply extract the first char from the String.


Your classes can support string encoding and decoding by having an appropriate toString method and a
constructor that creates a new object given the string description. The method
String.valueOf(Objectobj) is defined to return either "null" (if obj is null) or the result of
obj.toString. The String class provides enough overloads of valueOf that you can convert any
value of any type to a String by invoking valueOf.


13.2.6. Strings and char Arrays


A String maps to an array of char and vice versa. You often want to build a string in a char array and
then create a String object from the contents. Assuming that the writable StringBuilder class
(described later) isn't adequate, several String methods and constructors help you convert a String to an
array of char, or convert an array of char to a String.


There are two constructors for creating a String from a char array:


publicString(char[] chars, int start, int count)

Constructs a new String whose contents are the same as the chars array,
from index start up to a maximum of count characters.

publicString(char[] chars)

Equivalent to String(chars,0,chars.length).
Free download pdf