Java Reference
In-Depth Information
intObj = 100
byte from intObj = 100
double from intObj = 100.0
doubleObj = 329.78
double from doubleObj = 329.78
float from doubleObj = 329.78
int from doubleObj = 329
long from doubleObj = 329
Java 8 has added some methods like
sum()
,
max()
, and
min()
in some of the numeric wrapper classes such as
Integer
,
Long
,
Float
, and
Double
. For example,
Integer.sum(10, 20)
simply returns the result of
10 + 20
. At first,
you might think, "Did the wrapper class designers not have any useful things to do instead of adding these trivial
methods? Did we forget using the addition operator + to add two numbers, so we will use the
Integer.sum(10, 20)
?”
Your assumption is wrong. These methods have been added for a greater purpose. They are not intended to be used as
Integer.sum(10, 20)
. Their references are used in lambda expressions working with collections. I cover them in the
lambda expression discussion in the topic
Beginning Java Language Features
(ISBN 978-1-4302-6658-7).
Your program may receive numbers as strings. You may want to obtain primitive values or wrapper objects
from those strings. Sometimes the integer values in a string may be encoded in different bases (also called radix), for
example, decimal, binary, hexadecimal, etc. Wrapper classes help in working with strings containing primitive values.
valueOf()
methods to convert strings into wrapper objects.
•
Use the
parseXxx()
methods to convert strings into primitive values.
•
Use the
The
Byte
,
Short
,
Integer
,
Long
,
Float
, and
Double
classes contain
parseByte()
,
parseShort()
,
parseInt()
,
parseLong()
,
parseFloat()
and
parseDouble()
methods to parse strings into primitive values, respectively.
The following snippet of code converts a string containing an integer in binary format into an
Integer
object and
an
int
value:
String str = "01111111";
int radix = 2;
// Creates an Integer object from the string
Integer intObject = Integer.valueOf(str, radix);
// Extracts the int value from the string
int intValue = Integer.parseInt(str, 2);
System.out.println("str = " + str);
System.out.println("intObject = " + intObject);
System.out.println("intValue = " + intValue);
str = 01111111
intObject = 127
intValue = 127
All numeric wrapper classes contain several useful constants. Their
MIN_VALUE
and
MAX_VALUE
constants
represent the minimum and maximum values that can be represented by their corresponding primitive type. For
example,
Byte.MIN_VALUE
constant is -128 and
Byte.MAX_VALUE
constant is 127, which are the minimum and
maximum value that can be stored in a
byte
. They also have a
SIZE
constant that represents the size in bits that a
variable of the corresponding primitive type occupies. For example,
Byte.SIZE
is 8 and
Integer.SIZE
is 32.