Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 4 ■ OPERATORS

The bitwise complement operator promotes the values of byte, short, and char variables to 32 bits
before applying the ~ operator. The result of the operator is an int in those cases. That's why the binary
strings have 32 characters. This process is called unary numeric promotion. Consider the following code
in Listing 4-4:


Listing 4-4. Unary numeric promotion


byte a = 0;
Byte b = new Byte(a); // no problem
Byte c = new Byte(~a); // won't compile because the Byte constructor cannot accept an int
int d = ~a; // no problem


Casting


Software developers often find that they need a variable of one type to be a variable of another type. In
Java (and most programming languages), you can't change the type of a variable. Instead, you should
create a new variable and convert the existing variable into the new variable's type. That process is called
casting, and Java provides an operator of sorts for doing it. I say, “of sorts,” because the casting operator
differs according to the data type to which you're casting. In particular, you wrap parentheses around
the name of the type to which you're casting and put that operator before the value you want to cast.
Casting is often necessary to prevent the compiler from throwing errors when we convert one data type
to another. As ever, examples go a long way toward clarifying things (see Listing 4-5).


Listing 4-5. Casting


// Cast a byte to an int
byte b = 123;
int bInt = b; // no casting necessary


// Cast an int to a short
int i = 123;
short s = (short) i; //(short) is the casting operator – beware of values that are too large


// Cast a float to an int
float f = 12.34f;
int floatInt = (int) f; // floatInt = 12 – the original value is truncated


// Cast a char to a String – oops
char c = 'c'; // can't directly cast a char to a string
Character cChar = new Character(c); // so get a Character wrapper object for our char
String s = cChar.toString(); // and get a String object from the wrapper


In the first example shown previously, casting a byte to an int does not require a cast operator.
Because there's no possibility of data loss (an int can hold any value that a byte can hold), the JVM does
what's sometimes called “an implicit upcast”—implicit because you don't have to add any syntax to
make it happen and upcast because you've gone from smaller to larger in terms of both value range and
number of bits. It's also called a widening cast.

Free download pdf