Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Converting Objects and Simple Variables 127

Converting Objects and Simple


Variables


One of the most common tasks you need to accomplish in Java is to con-
vert information from one form into another. Several types of conversions
you can do include


. 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 expres-
sions. Amethod that expects a Calendarobject must receive a Calendar
object, for instance. If you used a method that takes a single integer argu-
ment and you sent it a floating-point number instead, an error would
occur when you attempted to compile the program.


Converting informationto 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 termssourceand destinationare 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 ver-
sion of the source in a new form.


Casting Simple Variables


Withsimple variables, casting occurs most commonly between numeric
variables such as integers and floating-point numbers. One type of variable
that cannot be used inany casting is Boolean values.


NOTE
When a method such as
System.out.println()
requires a string argument,you
can use the +operator to com-
bine several different types of
information in that argument.
As long as one of the things
being combined is a string,the
combined argument is convert-
ed into a string.
Free download pdf