One of the most common tasks you need to accomplish in Java is to convert information from one form into another. Several types of conversions you can do include
When a method such as System.out.println()
requires a string argument, you can use the +
operator to combine several different types of information in that argument. As long as one of the things being combined is a string, the combined argument is converted into a string.
• Converting an object into another object
• Converting a simple variable into another type of variable
• Using an object to create a simple variable
• Using a simple variable to create an object
Simple variables are the basic data types you learned about during Hour 5, “Storing and Changing Information in a Program.” These types include int
, float
, char
, long
, and double
.
When using a method or an expression in a program, you must use the right type of information that’s expected by these methods and expressions. A method that expects a Calendar
object must receive a Calendar
object, for instance. If you used a method that takes a single integer argument and you sent it a floating-point number instead, an error would occur when you attempted to compile the program.
Converting information to a new form is called casting. Casting produces a new value that is a different type of variable or object than its source. You don’t actually change the value when casting. Instead, a new variable or object is created in the format you need.
The terms source and destination are useful when discussing the concept of casting. The source is some kind of information in its original form—whether it’s a variable or an object. The destination is the converted version of the source in a new form.
With simple variables, casting occurs most commonly between numeric variables such as integers and floating-point numbers. One type of variable that cannot be used in any casting is Boolean values.
To cast information into a new format, you precede it with the new format surrounded by parentheses marks. For example, if you want to cast something into a long
variable, you precede it with (long)
. The following statements cast a float
value into an int
:
float source = 7.06F;
int destination = (int) source;
In variable casting where the destination holds larger values than the source, the value is converted easily, such as when a byte
is cast into an int
. A byte
holds values from –128 to 127, whereas an int
holds values from –2.1 billion to 2.1 billion. No matter what value the byte
variable holds, the new int
variable has plenty of room for it.
You sometimes can use a variable in a different format without casting it at all. For example, you can use char
variables as if they were int
variables. Also, you can use int
variables as if they were long
variables, and anything can be used as a double
.
In most cases, because the destination provides more room than the source, the information is converted without changing its value. The main exceptions occur when an int
or long
variable is cast to a float
, or a long
is cast into a double
.
When you are converting information from a larger variable type into a smaller type, you must explicitly cast it, as in the following statements:
int xNum = 103;
byte val = (byte) xNum;
Here, casting converts an integer value called xNum
into a byte
variable called val
. This is an example where the destination variable holds a smaller range of values than the source variable. A byte
holds integer values ranging from –128 to 127, and an int
holds a much larger range of integer values.
When the source variable in a casting operation has a value that isn’t enabled in the destination variable, Java changes the value to make the cast fit successfully. This can produce unexpected results if you’re not expecting the change.
You can cast objects into other objects when the source and destination are related by inheritance. One class must be a subclass of the other.
Some objects do not require casting at all. You can use an object where any of its superclasses are expected. All objects in Java are subclasses of the Object
class, so you can use any object as an argument when an Object
is expected.
You also can use an object where one of its subclasses is expected. However, because subclasses usually contain more information than their superclasses, you might lose some of this information. If the object doesn’t have a method that the subclass would contain, an error results if that missing method is used in the program.
To use an object in place of one of its subclasses, you must cast it explicitly with statements such as the following:
Graphics comp = new Graphics();
Graphics2D comp2D = (Graphics2D) comp;
This casts a Graphics
object called comp
into a Graphics2D
object. You don’t lose any information in the cast, but you gain all the methods and variables the subclass defines.
One thing you can’t do is cast an object to a simple variable or a simple variable to an object. There are classes in Java for each of the simple variable types include Boolean
, Byte
, Character
, Double
, Float
, Integer
, Long
, and Short
. All these classes are capitalized because they are objects, not simple variable types.
Using methods defined in each of these classes, you can create an object using a variable’s value as an argument. The following statement creates an Integer
object with the value 5309:
Integer suffix = new Integer(5309);
After you have created an object like this, you can use it like any other object. When you want to use that value again as a simple variable, the class has methods to perform that conversion. To get an int
value from the preceding suffix
object, the following statement could be used:
int newSuffix = suffix.intValue();
This statement causes the newSuffix
variable to have the value 5309, expressed as an int
value. One common casting from an object to a variable is to use a string in a numeric expression. When the string’s value could become an integer, this can be done using the parseInt()
method of the Integer
class, as in this example:
String count = "25";
int myCount = Integer.parseInt(count);
This converts a string with the text “25” into an integer with the value 25. If the string value was not a valid integer, the conversion would not work.
The next project you create is an application that converts a string value in a command-line argument to a numeric value, a common technique when you’re taking input from a user at the command line.
Return to your Java24 project in NetBeans, choose File, New File, and then create a new Empty Java File named NewRoot
. Enter Listing 10.1 in the source editor and remember to save the file.
1: class NewRoot {
2: public static void main(String[] args) {
3: int number = 100;
4: if (args.length > 0) {
5: number = Integer.parseInt(args[0]);
6: }
7: System.out.println("The square root of "
8: + number
9: + " is "
10: + Math.sqrt(number) );
11: }
12: }
Before you run the program, you must configure NetBeans to run it with a command-line argument. Choose the menu command Run, Set Project Configuration, Customize. The Project Properties window opens. Enter NewRoot
as the Main Class and 169
in the Arguments field. Click OK to close the dialog.
To run the program, choose Run, Run Main Project (instead of Run, Run File). The program displays the number and its square root, as shown in Figure 10.3.
The NewRoot
application is an expansion of an earlier tutorial from Hour 4, “Understanding How Java Programs Work,” that displayed the square root of the integer 225.
That program would have been more useful if it took a number submitted by a user and displayed its square root. This requires conversion from a string to an integer. All command-line arguments are stored as elements of a String
array, so you must cast them to numbers before using them in mathematical expressions.
To create an integer value based on the contents of a string, the Integer.parseInt()
method is called with the string as the only argument, as in Line 5:
number = Integer.parseInt(args[0]);
The args[0]
array element holds the first command-line argument submitted when the application is run. When the program was run with “169” as an argument, the string “169” was cast to the int
169.
Every one of the basic data types in Java has a corresponding object class: boolean
(Boolean
class), byte
(Byte
), char
(Character
), double
(Double
), float
(Float
), int
(Integer
), long
(Long
), and short
(Short
).
For each of these pairs, the information has identical value. The only difference between them is the format the value takes. An integer value such as 413 could be represented by either an int
or the Integer
class.
Java’s autoboxing and unboxing capabilities make it possible to use the basic data type and object forms of a value interchangeably.
Autoboxing casts a simple variable value to the corresponding class.
Unboxing casts an object to the corresponding simple value.
These features work behind the scenes, assuring that when you are expecting a simple data type like float
, an object is converted to the matching data type with the same value. When you’re expecting an object like Float
, a data type is converted to an object as necessary.
The following statements show where autoboxing and unboxing come in handy:
Float total = new Float(1.3F);
float sum = total / 5;
In early versions of Java (before Java 1.5), this would be an error—the use of a Float
object in the second statement is not possible. Java now unboxes total
to make the statement work, resulting in sum
being equal to 0.26.
18.217.105.174