Download Primitives and wrapper classes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java Note
Primitive Types and Wrapper Classes
1
2
3
1
Assignment rule.......................................................................1
Assign a primitive to its wrapper class and back ................................1
Methods of the wrapper classes ....................................................2
3.1
Constructor ......................................................................2
3.2
Primitive to wrapper: valueOf() methods ...................................2
3.3
Wrapper to primitive: <type>Value() methods .............................3
3.4
Autoboxing .......................................................................3
3.5
Convert string to primitive (parse methods) ................................4
3.6
Convert primitive to string (toString methods) .............................4
3.7
Other useful methods ..........................................................5
3.7.1
Bit representation of floating-point value .............................5
3.7.2
Numerical comparison: compareTo() method .........................5
3.7.3
Other methods .............................................................6
Assignment rule
You cannot use a direct typecast to assign a primitive to its wrapper object
or vice versa
You can only typecast a primitive type to another primitive type, or a
wrapper class to another wrapper class
To assign a primitive to its wrapper class, pass the primitive as a parameter
to the constructor, or use valueOf()
To assign a wrapped value back to a primitive, use the wrapper class
<type>Value() method
2
Assign a primitive to its wrapper class and back
Examples:
int k = 0xFE;
Integer ki = new Integer(k);
int j = ki.intValue();
System.out.println(j);
long k = 0xFE;
Long ki = new Long(k);
long j = ki.longValue();
System.out.println(j);
3
Methods of the wrapper classes
3.1
Constructor
This is the second-best method to create a wrapper object from a primitive.
The valueOf() method is better; see below.
The constructor is used to assign the value of the primitive, e.g.
Integer ival = new Integer(-1);
The wrapper classes also have a second constructor, which accepts a string in
decimal only:
Integer fifteen = new Integer("15");
System.out.println(fifteen.intValue());
When assigning constants to wrappers other than Integer, don't forget that an
integer constant is by default an int:
3.2
Long fifteenBillion = new Long(15000000000);
wrong
Byte fifteen = new Byte(15);
wrong

Long fifteenBillion = new Long(15000000000L);
correct
Byte fifteen = new Byte((byte)15);
correct



Primitive to wrapper: valueOf() methods
As of Java 1.5 autoboxing can be used to convert between a primitive and its
associated wrapper class; see 3.4 below.
These are static methods, which return a wrapper object based on the
primitive passed as argument. Example:
Integer io = Integer.valueOf(4567);
System.out.println(io.floatValue());
This method for instantiating a wrapper object is preferable over using the
constructor. The reason is that the VM caches frequently requested values (e.g.
the lowest integers), which results in better space usage and performance.
3.3
Wrapper to primitive: <type>Value() methods
As of Java 1.5 autoboxing can be used to convert between a primitive and its
associated wrapper class; see 3.4 below.
The "<type>Value" method returns the numeric value held in the wrapper class
in the specified type. Each wrapper class has such a method for its
corresponding primitive type: Integer.intValue(), Long.longValue(),
etc. Apart from these, the classes also have return methods for other primitive
types. If necessary, truncation takes place. Examples:
Long.byteValue(), Long.shortValue(), Long.intValue()
truncates if necessary
Byte.intValue(), Byte.shortValue(), Byte.longValue()

There are also value methods to assign integer wrappers to floating-point
primitives and vice versa:
Integer.floatValue(), Integer.doubleValue()
etc.
Float.byteValue(), Float.intValue(), etc.
Example of converting a float to an integer:
float rval = (float)(Math.sqrt(2) * 1000.0);
System.out.println("Primitive:" + rval);
System.out.println("Via wrapper:" + new
Float(rval).intValue() );
Output:
Primitive:1414.2136
Via wrapper:1414
Conversion of a floating-point to an integer type truncates the decimals:
Float(3.875F).intValue()
3.4
 gives 3
Autoboxing
Autoboxing, introduced in Java 5, is the automatic conversion the Java
compiler makes between the primitive (basic) types and their corresponding
object wrapper classes (e.g., int and Integer, double and Double, etc). The
underlying code that is generated is the same, but autoboxing provides a sugar
coating that avoids the tedious and hard-to-read casting typically required by
Java Collections, which can not be used with primitive types.
With Autoboxing
int i;
Integer j;
i = 1;
j = 2;
i = j;
j = i;
3.5
Without Autoboxing
int i;
Integer j;
i = 1;
j = new Integer(2);
i = j.intValue();
j = new Integer(i);
Convert string to primitive (parse methods)
The wrapper classes have two static parse methods for their own primitive
type. These methods accept a string and return a primitive of the given type.
See Hexadecimal and octal.doc for a description. The first method takes the
string as the only argument and treats this string as a decimal number. The
second method also takes a radix. Example:
static int Integer.parseInt(String s);
static int Integer.parseInt(String s, int radix);
3.6
Convert primitive to string (toString methods)
The integer types have two or three toString() methods:
static String Integer.toString(int i);
String Integer.toString();
static String Integer.toString(int i, int radix);
The first method is static and directly converts the passed primitive to a string.
The second method is the non-static equivalent of the first and converts the
current value. The third method is static and converts the passed primitive
using the specified radix. This last method exists only for the Integer and Long
classes, not for Short and Byte.
The floating point classes also have only the first two methods, e.g.
static String Double.toString(double d);
String Double.toString();
The classes define when to use decimal and exponential notation. The latter is
used when the magnitude (absolute value) is less than 10 -3 or greater than or
equal to 107.
Some types also have "shortcut" methods to convert in a specified radix, e.g.
toHexString(). See Hexadecimal and octal.doc for a discussion. The table
below shows which methods exist in each wrapper class (JSE 1.6):
Integer
Long
Short
Byte
Float
Double
toHexString() toOctalString() toBinaryString()
X
X
X
X
X
X
X (*)
X (*)
-
(*) The output format for float and double is peculiar. Consult the Java API
documentation for details.
3.7
Other useful methods
3.7.1 Bit representation of floating-point value
To obtain the internal format of a floating-point primitive, you can use the
toHexString() method of Float and Double. However, as mentioned above,
this method returns a special format, which needs some explanation (see Java
API).
The two wrapper classes also contain methods that return the straight bit
pattern into an int (for float) or a long (for double):
static int Float.floatToIntBits();
static int Float.floatToRawIntBits();
static long Double.doubleToLongBits();
static long Double.doubleToRawLongBits();
The second method (with "Raw" in the name) differs from the first in that it
returns the actual bit pattern for a NaN. The first method returns a predefined
constant in case the floating-point value is a NaN; see Java API.
3.7.2 Numerical comparison: compareTo() method
This method performs a numerical comparison between two wrapper objects of
the same type. The return value is 0 if both are numerically equal, < 0 if the
object whose method is called is numerically less than the object passed as
argument, and > 0 if it is numerically greater.
Example:
Integer iBig = Integer.valueOf(32000);
Integer iSmall = Integer.valueOf(-1000);
System.out.println(iBig.compareTo(iSmall));
 outputs 1
3.7.3 Other methods
The wrapper classes have many other methods; see the Java API for a
description.