Java Reference
In-Depth Information
The statement in Line 15 produces the fourth line of output. Notice that the printed
value is the string "Hello There" , which is the string pointed to by pStr . After this
statement executes, control goes back to the method main at Line 8 (see Figure 7-16).
main
str
Hello There
FIGURE 7-16 Variable after the statement in Line 7 executes
The next statement executed is in Line 8, which produces the last line of the output.
Note that str points to the string "Hello There" .
7
Primitive Type Wrapper Classes as Parameters
As illustrated by the program in Example 7-8, if a formal parameter is of the primitive data
type and the corresponding actual parameter is a variable, then the formal parameter cannot
change the value of the actual parameter. In other words, changing the value of a formal
parameter of the primitive data type has no effect on the actual parameter. So, how do we pass
the values of primitive data types outside the method? As stated earlier, only reference
variables can pass values outside the method (except, of course, for the return value).
Corresponding to each primitive data type, Java provides a class so that the values of primitive
data types can be wrapped in objects. For example, you can use the class Integer to wrap
int values in objects, the class Double to wrap double values in objects, and so on. These
wrapper classes were introduced in Chapter 6, ''Graphical User Interface (GUI) and Object-
Oriented Design (OOD).'' Even though you can use the class Integer to wrap int values
in objects, the class Integer does not provide a method to change the value of an existing
Integer object. The same is true of other wrapper classes. That is, when passed as parameters,
objects of wrapper classes have the same limitations as objects of the class String .Ifwe
want to pass a String object as a parameter and also change that object, we can use the
class StringBuffer . However, Java does not provide any class that wraps primitive type
values in objects and when passed as parameters change their values. If a method returns only
one value of a primitive type, then you can write a value-returning method. However, if you
encounter a situation that requires you to write a method that needs to pass more than one
value of a primitive type, then you should design your own classes. Appendix D provides the
definitions of such classes and shows how to use them in a program.
The file, Chapter7_PrimitiveTypesAsObjects.java , illustrating how to use user-
defined classes to pass primitive type values as objects and change their values, can be found
with the Additional Student Files at www.cengagebrain.com.
 
Search WWH ::




Custom Search