Java Reference
In-Depth Information
Signed x = -10
Signed y = -2
Signed x/y = 5
Unsigned x = 4294967286
Unsigned y = 4294967294
Unsigned x/y = 0
The Long class contains methods to perform unsigned operations. The methods are similar to the ones in the
Integer class. Note that you cannot convert the value stored in a long to an unsigned value as you would need a
bigger storage than provided by the long data type to do so, but long is the biggest integer data type provided by Java.
This is the reason that the Byte and Short classes have toUsignedInt() and toUnSignedLong() methods, as int and
long are bigger than byte and short . In fact, to store the value of a signed data type X as an unsigned value in a signed
data type Y , the size of the data type Y needs to be at least twice as big as that of X . Following this storage requirement,
there is a toUnsignedLong() method in the Integer class, but no such method exist in the Long class.
Autoboxing and Unboxing
AutoBoxing and unboxing are features added in Java 5 to work with primitive data types and their corresponding
wrapper classes. They are implemented completely in the compiler. Before we define autoboxing/unboxing, let's
discuss an example. The example is trivial, but it serves the purpose of demonstrating the pain you had to go through
before Java 5, when you were working with conversion between primitive types to their wrapper objects and vice-versa.
Suppose you have a method that accepts two int values, adds them, and returns an int value. You might say,
“What is the big deal about this method?” It should be as simple as the following:
// Only method code is shown
public static int add(int a, int b) {
return a + b;
}
The method can be used as
int a = 200;
int b = 300;
int result = add(a, b); // result will get a value of 500
And you are right that there is no big deal about this method at all. Let's add a bit of a twist to the logic. Think
about the same method working with Integer objects instead of int values. Here is the code for the same method:
public static Integer add(Integer a, Integer b) {
int aValue = a.intValue();
int bValue = b.intValue();
int resultValue = aValue + bValue;
Integer result = new Integer(resultValue);
return result;
}
 
Search WWH ::




Custom Search