Java Reference
In-Depth Information
For instance, the following statement in (a) can be simplified as in (b) due to autoboxing.
Equivalent
Integer intObject = 2 ;
Integer intObject = new Integer( 2 );
(b)
(a)
autoboxing
Consider the following example:
1 Integer[] intArray = { 1 , 2 , 3 };
2 System.out.println(intArray[ 0 ] + intArray[ 1 ] + intArray[ 2 ]);
In line 1, the primitive values 1 , 2 , and 3 are automatically boxed into objects new Inte-
ger(1) , new Integer(2) , and new Integer(3) . In line 2, the objects intArray[0] ,
intArray[1] , and intArray[2] are automatically converted into int values that are
added together.
10.19 What are autoboxing and autounboxing? Are the following statements correct?
Check
Point
a. Integer x = 3 + new Integer( 5 );
b. Integer x = 3 ;
c. Double x = 3 ;
d. Double x = 3.0 ;
e. int x = new Integer( 3 );
f. int x = new Integer( 3 ) + new Integer( 4 );
10.20 Show the output of the following code?
public class Test {
public static void main(String[] args) {
Double x = new Double( 3.5 );
System.out.println(x.intValue());
System.out.println(x.compareTo( 4.5 ));
}
}
10.14 The BigInteger and BigDecimal Classes
The BigInteger and BigDecimal classes can be used to represent integers or
decimal numbers of any size and precision.
Key
Point
If you need to compute with very large integers or high-precision floating-point values, you can
use the BigInteger and BigDecimal classes in the java.math package. Both are immutable .
The largest integer of the long type is Long.MAX_VALUE (i.e., 9223372036854775807 ).
An instance of BigInteger can represent an integer of any size. You can use new BigInte-
ger(String) and new BigDecimal(String) to create an instance of BigInteger and
BigDecimal , use the add , subtract , multiple , divide , and remainder methods to per-
form arithmetic operations, and use the compareTo method to compare two big numbers. For
example, the following code creates two BigInteger objects and multiplies them.
VideoNote
Process large numbers
immutable
BigInteger a = new BigInteger( "9223372036854775807" );
BigInteger b = new BigInteger( "2" );
BigInteger c = a.multiply(b); // 9223372036854775807 * 2
System.out.println(c);
The output is 18446744073709551614 .
 
 
Search WWH ::




Custom Search