Sie sind auf Seite 1von 2

MISCELLANOUS

IMPLICIT CASTING VS EXPLICIT CASTING


An implicit cast means you don't have to write code for the cast
An implicit cast happens when you're doing a widening conversion.
public class MainClass{
public static void main(String[] argv){
int a = 100;
long b = a; // Implicit cast, an int value always fits in a long
}
}
An explicit casts looks like this:
public class MainClass{
public static void main(String[] argv){
float a = 100.001f;
int b = (int)a; // Explicit cast, the float could lose info
}
}

THE SHIFT OPERATORS


The shift left operator in Java technology is "<<". There are two operators for doing
the right shift - signed right shift (>>) and zero fill right shift (>>>).
The left shift operator fills the right bits by zero. The effect of each left shift is
multiplying the number by two. The example below illustrates this int i = 13; // i is 00000000 00000000 00000000 0000 1101
i = i << 2; // i is 00000000 00000000 00000000 0011 0100

After this left shift, i becomes 52 which is same as multiplying i by 4


Zero fill shift right is represented by the symbol >>>. This operator fills the leftmost
bits by zeros. So the result of applying the operator >>> is always positive. (In two's
complement representation the leftmost bit is the sign bit. If sign bit is zero, the
number is positive, negative otherwise.) The example below illustrates applying the
operator >>> on a number.
int b = 13; // 00000000 00000000 00000000 0000 1101
b = b >>> 2; // b is now 00000000 00000000 00000000 0000 0011

So the result of doing a zero fill right shift by 2 on 13 is 3. The next example explains
the effect of applying the operator >>> on a negative number.
int b = -11; //11111111 11111111 11111111 1111 0101
b = b >>> 2; // b now becomes 00111111 11111111 11111111 1111 1101

So the result of applying zero fill right shift operator with operand two on -11 is
1073741821.
Signed right shift operator (>>) fills the left most bit by the sign bit. The result of
applying the signed shift bit has the same sign as the left operand. For positive
numbers the signed right shift operator and the zero fill right shift operator both give
the same results. For negative numbers, their results are different. The example below
illustrates the signed right shift.
int b = -11; // 11111111 11111111 11111111 1111 0101
b = b >> 2; // 11111111 11111111 11111111 1111 1101 (2's complement
of -3)
// Here the sign bit 1 gets filled in the two most significant bits.

The new value of b becomes -3

Das könnte Ihnen auch gefallen