Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

396 Part II: The Java Library


Converting Numbers to and from Strings
One of the most common programming chores is converting the string representation of a
number into its internal, binary format. Fortunately, Java provides an easy way to accomplish
this. TheByte,Short,Integer, andLongclasses provide theparseByte( ),parseShort( ),
parseInt( ), andparseLong( )methods, respectively. These methods return thebyte,short,

Method Description
static long parseLong(Stringstr)
throws NumberFormatException

Returns thelongequivalent of the number
contained in the string specified bystrin radix 10.
static long parseLong(Stringstr, intradix)
throws NumberFormatException

Returns thelongequivalent of the number contained
in the string specified bystrusing the specifiedradix.
static long reverse(longnum) Reverses the order of the bits innumand returns
the result.
static long reverseBytes(longnum) Reverses the order of the bytes innumand returns
the result.
static long rotateLeft(longnum, intn) Returns the result of rotatingnumleftnpositions.
static long rotateRight(longnum, intn) Returns the result of rotatingnumrightnpositions.
static int signum(longnum) Returns –1 ifnumis negative, 0 if it is zero, and 1 if
it is positive.
short shortValue( ) Returns the value of the invoking object as ashort.
static String toBinar yString(longnum) Returns a string that contains the binar y equivalent
ofnum.
static String toHexString(longnum) Returns a string that contains the hexadecimal
equivalent ofnum.
static String toOctalString(longnum) Returns a string that contains the octal equivalent
ofnum.
String toString( ) Returns a string that contains the decimal equivalent
of the invoking object.
static String toString(longnum) Returns a string that contains the decimal equivalent
ofnum.
static String toString(longnum, intradix) Returns a string that contains the decimal equivalent
ofnumusing the specifiedradix.
static Long valueOf(longnum) Returns aLongobject containing the value passed
innum.
static Long valueOf(Stringstr)
throws NumberFormatException

Returns aLongobject that contains the value
specified by the string instr.
static Long valueOf(Stringstr, intradix)
throws NumberFormatException

Returns aLongobject that contains the value
specified by the string instrusing the specifiedradix.

TABLE 16-6 The Methods Defined byLong(continued)
Free download pdf