Java Reference
In-Depth Information
Did you notice the complexity that is involved when you changed the same method to use Integer objects?
You had to perform three things to add two int values in the Integer objects.
a and b , from Integer objects to int values using their
Unwrap the methods arguments,
intValue() method.
int aValue = a.intValue();
int bValue = b.intValue();
Perform an addition of two
int values.
int resultValue = aValue + bValue;
Wrap the result into a new Integer object and return the result.
Integer result = Integer.valueOf(resultValue);
return result;
Listing 8-2 has the complete code to demonstrate the use of the add() method.
Listing 8-2. Adding Two int Values Using Integer Objects
// MathUtil.java
package com.jdojo.wrapper;
public class MathUtil {
public static Integer add(Integer a, Integer b) {
int aValue = a.intValue();
int bValue = b.intValue();
int resultValue = aValue + bValue;
Integer result = Integer.valueOf(resultValue);
return result;
}
public static void main(String[] args) {
int iValue = 200;
int jValue = 300;
int kValue; /* will hold result as int */
// Box iValue and jValue into Integer objects
Integer i = Integer.valueOf(iValue);
Integer j = Integer.valueOf(jValue);
// Store returned value of the add() method in an Integer object k
Integer k = MathUtil.add(i, j);
// Unbox Integer object's int value into kValue int variable
kValue = k.intValue();
 
Search WWH ::




Custom Search