Page 469 - Introduction to Programming with Java: A Problem Solving Approach
P. 469

                11.2 Integer Types and Floating-Point Types 435
 Type
 Storage
 Wrapper Class’s
MIN_VALUE
 Wrapper Class’s
MAX_VALUE
 byte
 8 bits
 􏰀128
 127
 short
 16 bits
 􏰀32,768
 32767
 int
 32 bits
 􏰀2,147,483,648
 2,147,483,647
 long
 64 bits
 􏰏 -9*1018
 􏰏 9*1018
  Figure 11.1 Properties of Java integer data types
To access an integer’s minimum and maximum values, use the MIN_VALUE and MAX_VALUE named constants that come with the integer’s wrapper class. As you learned in Chapter 5, Integer and Long are the wrapper classes for the int and long data types. And as you might expect, Byte and Short are the wrapper classes for the byte and short data types. So here’s how to print the maximum byte value:
System.out.println("Largest byte = " + Byte.MAX_VALUE);
The default type for an integer constant is int. But you might have a need for an integer constant that is too big for an int. In that case, you can explicitly force an integer constant to be a long by adding an l or L
Apago PDF Enhancer
suffix to the integer constant. For example, suppose you’re writing a solar system program, and you want to store the age of the earth in a variable named ageOfPlanet. The earth is 4.54 billion years old and 4.54 billion is larger than Integer.MAX_VALUE’s 2,147,483,647. This generates a compilation error:
long ageOfPlanet = 4540000000;
But this, with the L suffix, works just fine: long ageOfPlanet = 4540000000L;
When you declare a numeric variable, be sure that the type you select is large enough to handle the largest value that your program might put into it. If a value can’t fit in the memory space provided, that’s called overflow. Overflow errors are dramatic, as the ByteOverflowDemo program in Figure 11.2 illustrates.
Integer overflow reverses the sign, so the ByteOverflowDemo program prints negative 128 rather than the correct result, positive 128. In this example, the magnitude of the error is approximately twice as big as the magnitude of the largest allowable value! Overflow also causes sign reversal for types short, int, and long. In such cases, the compiler does not find the problem, and the Java Virtual Machine (JVM) does not find it either. Java runs the program with no complaints and happily generates a massive error. In the end, it’s up to you. Whenever there is any doubt, use a larger type!
Floating-Point Types
As you know, floating-point numbers are real numbers—numbers that allow for non-zero digits to the right of a decimal point. This means you can use floating-point numbers to hold fractional values—values that are smaller than one. Figure 11.3 shows the two floating-point types—float and double.
































































   467   468   469   470   471