The applet below demonstrates some of the capabilities of the
wrapper class methods. An integer and Boolean strings pass to the
applet via the <param=
> tags. We then need to convert
the strings to primitive type values.
The Integer
and Boolean
classes provide methods to convert the strings to their respective
primitive values. For the Integer
class a single method - parseInt(param1)
- can do the operation. The Boolean
wrapper, however, does not include a "parseBoolean"
type of method to go directly from a string of "true"
or "false"
strings to a boolean value. Instead two Boolean
methods are required.
WrapperApplet.java
(Output goes to browser's Java
console.) |
The tag in the web page will look like:
<applet
code="WrapperApplet.class" codebase = "../../Code/Java/Wrappers/Basic/"
width=100 height=50>
<param name="param1" value="1234">
<param name="param2" value="true">
</applet>
|
public
class WrapperApplet extends java.applet.Applet
{
public void init () {
//Create an instance of the Test
class
Test test = new Test ();
// First parameter is an integer
string
String param1= getParameter ("param1");
// Use a method in the Integer wrapper
to convert the
// string to an int type value.
int val1 = Integer.parseInt (param1);
// Second parameter is a boolean
string.
String param2 = getParameter ("param2");
// Use the methods in the Boolean
wrapper class
// to convert the "true" or "false"
strings to
// boolean values in 2 steps:
Boolean b = Boolean.valueOf (param2);
boolean flag = b.booleanValue ();
// Java 5.0 added the parseBoolean()
method
// so you can now do this in one
step:
//
// boolean flag = b.parseBoolean(param2);
// Now that you have the two parameters
converted
// to their respective primitive
type values, you
// could, for example, use the boolean
as a flag
// to select between 2 different
initialization methods
// and pass the integer value to
either.
if (flag)
test.aMethod
(val1);
else
test.bMethod
(val1);
}
// Paint message in Applet window.
public void paint (java.awt.Graphics g) {
g.drawString ("WrapperApplet",
20, 20);
}
}
// Use Test to examine various aspects of class design
class Test
{
void aMethod (int i) {
// Use the explicit String method
to convert
// an int to a String object.
String iStr = String.valueOf (i);
System.out.println (iStr + " in
aMethod");
System.out.println ();
}
void bMethod (int i) {
String iStr = String.valueOf (i);
System.out.println (iStr + " in
bMethod");
System.out.println ();
}
}
|
|
Latest update: Oct. 19, 2004
|