Data Type Conversion
Introduction.
Now that we have seen some primitive data types we need to be able to
convert between them. In Java and many other programming languages
this is called casting. These
conversions, particularly when they are numeric in nature, are done with
the following sort of operation. (dataTypeName) expression
It can be very important to be able to switch variables and values between data types. Oftentimes, even the simplest mathematical expressions need to work with data that was originally of different types. The following program takes the inputs for a linear equation in one variable and finds the solution. We will start with integer inputs, then cast these to floats to see the solution, then cast them to double to see how this impacts our solutions. You should call the application program DataCasting.java. |
/* program to get inputs from a
user to solve an equation of the form ax + b = c */ import javax.swing.JOptionPane; public class DataCasting {
} // end class DataCasting |
This program has our usual basic structure for
applications. Rather than going over this again I will focus on the
code which can be divided into five sections.
You need to follow the usual steps of
Then you should try this program with a variety of input values, but in particular use a = 3, b = 7, c = 13 Notice the strange solution you get when using integers. Also notice there is no apparent difference between the floating point solution and the double precision solution. This is because the double precision isn't important in this simple of a situation. The DataCasting Applet. Now for the experience you want to create the following applet. Make sure to notice how similar it is to the application. You should call the file DataCastingApplet.java. |
/* applet to get inputs from a
user to solve an equation of the form ax + b = c */ import javax.swing.JOptionPane; import javax.swing.JApplet; public class DataCastingApplet extends JApplet {
} // end class DataCastingApplet |
Notice how you must
Not much else is different. You also need a file called DataCastingApplet.html. It should look like the following. |
<APPLET CODE="DataCastingApplet.class" WIDTH=200 HEIGHT=100> </APPLET> |
The steps for running the applet are the following
You should try a variety of outputs, but a = 13, b = 67, c = 23 shows some distinctions between solutions in each precision level. |