|
Another challenge is sometimes encountered when a method returns a reference
to an object, and you would like the returned value to be a primitive type.
For example:
package example;
public class ReturnIntTest
{
public static Integer returnValue()
{
return new Integer(42);
}
public static void main(String[] args)
{
int intValue = returnValue();
System.out.println(intValue);
}
}
|
which will result in a compile-time error:
"ReturnIntTest.java": incompatible types; found :
java.lang.Integer, required: int at line 12, column 20
In this case, you can make use of convenience methods provided by the wrapper
classes:
| Wrapper Class |
Method |
Boolean |
public boolean booleanValue() |
Byte |
public byte byteValue() |
Character |
public char charValue() |
Short |
public short shortValue() |
Integer |
public int intValue() |
Long |
public long longValue() |
Float |
public float floatValue() |
Double |
public double doubleValue() |
Void |
(not applicable) |
For example:
package example;
public class ReturnIntTest
{
public static Integer returnValue()
{
return new Integer(42);
}
public static void main(String[] args)
{
int intValue = returnValue().intValue();
System.out.println(intValue);
}
}
|
The above code will compile and run correctly.
|