Java Reference
In-Depth Information
Listing 3-6. Integer example
// declare an int
int myInt = 1;
// and a String that contains a number
String myString = "1";
// turn myInt into a String
String myIntString = Integer.toString(myInt);
// turn myString into an int
int myStringInt = Integer.parseInt(myString);
// turn myString into an Integer
// be prepared for an exception if myString does not hold a number
Integer myStringInteger = new Integer(myString);
// and then turn myStringInteger into an int
int myOtherStringInt = myStringInteger.intValue();
// Now for more unusual things
// convert an int to a float (perhaps for further floating-point work)
float myFloat = new Integer(myInt).floatValue();
// convert an int to a byte
// be prepared for an exception if the value is out of byte's range
byte myByte = new Integer(myInt).byteValue();
// convert an int to a long
// no need to worry about an exception this time
long myLong = new Integer(myInt).longValue();
// just for fun, get the binary string representation of myInt
// creates a String object that holds "1"
String myIntBinary = Integer.toBinaryString(myInt);
The other numeric primitives ( byte , short , long , float , and double ) all work in a similar way. You
can convert any of them to any other, though you might have to handle an exception if the conversion
can't be done with the value you provide. For example, if you have an int variable that holds a value of
300, converting it to a byte gives an error, because a byte can't hold that value. We cover this concept in
greater detail in the next chapter, when discussing casting values.
The Boolean and Character classes work a little differently. You can still convert strings to boolean or
char values and vice-versa, but you can't convert boolean and char primitives into other primitives. Also,
the Boolean class includes an equals method, and the Character class includes many methods for
dealing with issues such as characters that are meant to be read from right to left (for example,
characters from Arabic and Hebrew) and other special issues that relate only to characters. All of those
operations are fairly unusual, though, so we don't cover them. If you want to learn more about them
(and good for you if you do), look at the Javadoc for the Boolean and Character classes. As you might
recall from Chapter 1, JavaDoc is a special kind of documentation that is built into the code itself. Oracle
(the company that makes Java) provides extensive JavaDoc for all the standard Java libraries. You can
find the JavaDoc for the Boolean class at http://download.oracle.com/javase/7/docs/api/java/
Search WWH ::




Custom Search