Java Reference
In-Depth Information
Q: So you need the cast operator only when working with numeric
values?
A: No. In fact, the cast operator is probably used more often when
working with object references, as we will see in Chapter 8, “Poly-
morphism and Abstraction.” By the way, the Java compiler rarely
gives warnings. There is typically only one way to do something in
Java, and anything that doesn't follow the rules generates a com-
piler error. That is part of the reason why Java is easier to learn and
understand than C++.
Integral Types
Of the eight primitive data types, four of them are integer types that differ only
by their size: byte, short, int, and long. All four of them are signed, meaning
that they store both positive and negative numbers.
The following IntegerDemo program demonstrates using the integral types.
Study the program and try to determine what the output is.
public class IntegerDemo
{
public static void main(String [] args)
{
int x = 250;
System.out.println(“x is “ + x);
short a, b, c;
c = 21;
b = 9;
a = (short) (b + c); //why cast to a byte?
System.out.println(“a is “ + a);
long y = 12345678987654321L; //notice the “L”
System.out.println(“y is “ + y);
y = x;
byte s;
s = (byte) c;
System.out.println(“y is now “ + y + “ and s is “ + s);
}
}
Search WWH ::




Custom Search