Java Tutorial/Data Type/Wrapper Classes
Содержание
Autoboxing/unboxing int
<source lang="java">
class AutoBox {
public static void main(String args[]) { Integer iOb = 100; // autobox an int int i = iOb; // auto-unbox System.out.println(i + " " + iOb); // displays 100 100 }
}</source>
Demonstrate a type wrapper.
<source lang="java">
class Wrap {
public static void main(String args[]) { Integer iOb = new Integer(100); int i = iOb.intValue(); System.out.println(i + " " + iOb); // displays 100 100 }
}</source>
Primitive Wrappers in detail
For the sake of performance, not everything in Java is an object. There are also primitives, such as int, long, float, double, etc.
java.lang.Integer
- The java.lang.Integer class wraps an int.
- The Integer class has two static final fields of type int: MIN_VALUE and MAX_VALUE.
- MIN_VALUE contains the minimum possible value for an int (-2^31) and
- MAX_VALUE the maximum possible value for an int (2^31 - 1).
Integer class has two constructors:
<source lang="java">
public Integer (int value)
public Integer (String value)</source>
Use Integer constructor to convert int primitive type to Integer object.
<source lang="java">
public class Main {
public static void main(String[] args) { int i = 10; Integer intObj = new Integer(i); System.out.println(intObj); }
}</source>
Wrapped Class: boolean, int, long
<source lang="java">
public class WrappedClassApp {
public static void main(String args[]) { Boolean b1 = new Boolean("TRUE"); Boolean b2 = new Boolean("FALSE"); System.out.println(b1.toString() + " or " + b2.toString()); for (int j = 0; j < 16; ++j) System.out.print(Character.forDigit(j, 16)); System.out.println(); Integer i = new Integer(Integer.parseInt("ef", 16)); Long l = new Long(Long.parseLong("abcd", 16)); long m = l.longValue() * i.longValue(); System.out.println(Long.toString(m, 8)); System.out.println(Float.MIN_VALUE); System.out.println(Double.MAX_VALUE); }
}</source>
Wrapper classes for the primitive types
Basic TypeWrapper ClassbyteByteshortShortintIntegerlongLongfloatFloatdoubleDoublebooleanBooleancharCharacter