2.8. Numeric Type Conversions

 
[Page 34 ( continued )]

2.7. Numeric Data Types and Operations

Every data type has a range of values. The compiler allocates memory space to store each variable or constant according to its data type. Java provides eight primitive data types for numeric values, characters , and Boolean values. In this section, numeric data types are introduced.

Table 2.1 lists the six numeric data types, their ranges, and their storage sizes.

Table 2.1. Numeric Data Types
Name Range Storage Size
byte -2 7 (-128) to 2 7 - 1(127) 8-bit signed
short -2 15 (-32768) to 2 15 - 1(32767) 16-bit signed
int -2 31 (-2147483648) to 2 31 - 1(2147483647) 32-bit signed
long -2 63 to 2 63 - 1 64-bit signed
  (i.e., -9223372036854775808 to 9223372036854775807)  
float Negative range: -3.4028235E + 38 to -1.4E-45 32-bit IEEE 754
  Positive range: 1.4E-45 to 3.4028235E + 38  
double Negative range: -1.7976931348623157E+308 to -4.9E-324 64-bit IEEE 754
  Positive range: 4.9E-324 to 1.7976931348623157E+308  

Note

IEEE 754 is a standard approved by the Institute of Electrical and Electronics Engineers for representing floating-point numbers on computers. The standard has been widely adopted. Java has adopted the 32-bit IEEE 754 for the float type and the 64-bit IEEE 754 for the double type. The IEEE 754 standard also defines special values and operations in Appendix F, "Special Floating-Point Values."


Java uses four types for integers: byte , short , int , and long . Choose the type that is most appropriate for your variable. For example, if you know an integer stored in a variable is within a range of byte, declare the variable as a byte .

Java uses two types for floating-point numbers: float and double . The double type is twice as big as float . So, the double is known as double precision , while float is known as single precision . Normally, you should use the double type because it is more accurate than the float type.


[Page 35]

2.7.1. Numeric Operators

The operators for numeric data types include the standard arithmetic operators: addition ( + ), subtraction ( ), multiplication ( * ), division ( / ), and remainder ( % ), as shown in Table 2.2.

Table 2.2. Numeric Operators
Name Meaning Example Result
+ Addition 34 + 1 35
Subtraction 34.0 - 0.1 33.9
* Multiplication 300 * 30 9000
/ Division 1.0 / 2.0 0.5
% Remainder 20 % 3 2

The result of integer division is an integer. The fractional part is truncated. For example, 5/2 yields 2 , not 2.5 , and ”5 / 2 yields ”2 , not ”2.5

The % operator yields the remainder after division. The left-hand operand is the dividend, and the right-hand operand is the divisor. Therefore, 7 % 3 yields 1 , 12 % 4 yields , 26 % 8 yields 2 , and 20 % 13 yields 7 .


The % operator is often used for positive integers but also can be used with negative integers and floating-point values. The remainder is negative only if the dividend is negative. For example, ”7 % 3 yields ”1 , ”12 % 4 yields , ”26 % ” 8 yields ”2 , and 20 % ”13 yields 7 .

Remainder is very useful in programming. For example, an even number % 2 is always , and an odd number % 2 is always 1 . So you can use this property to determine whether a number is even or odd. Suppose today is Saturday, you and your friend are going to meet in 10 days. What day is in 10 days? You can find that day is Tuesday using the following expression:

Listing 2.2 gives a program that obtains minutes and remaining seconds from an amount of time in seconds. For example, 500 seconds contains 8 minutes and 20 seconds.

Listing 2.2. DisplayTime.java
(This item is displayed on pages 35 - 36 in the print version)
 1   import   javax.swing.JOptionPane; 2 3   public class   DisplayTime { 4   public static void   main(String[] args) { 5   int   seconds =   500   ; 

[Page 36]
 6   int   minutes = seconds  /    60   ; 7   int   remainingSeconds = seconds  %    60   ; 8 JOptionPane.showMessageDialog(   null   , 9 seconds +   " seconds is "   + minutes + 10   " minutes and "   + remainingSeconds 11 +   " seconds"   ); 12 } 13 } 

Line 6 obtains the minutes using seconds / 60 . Line 7 ( seconds % 60 ) obtains the remaining seconds after taking away the minutes.

The + and operators can be both unary and binary. A unary operator only one operand; a binary operator has two operands. For example, the operator in ”5 can be considered a unary operator to negate number 5 , whereas the operator in 4 ” 5 is a binary operator for subtracting 5 from 4 .

Note

Calculations involving floating-point numbers are approximated because these numbers are not stored with complete accuracy. For example,

 System.out.println(   1.0   -   0.1   -   0.1   -   0.1   -   0.1   -   0.1   ); 

displays 0.5000000000000001 , not 0.5 , and

 System.out.println(   1.0   -   0.9   ); 

displays 0.09999999999999998 , not 0.1 . Integers are stored precisely. Therefore, calculations with integers yield a precise integer result.


2.7.2. Numeric Literals

A literal is a constant value that appears directly in a program. For example, 34 , 1000000 , and 5.0 are literals in the following statements:

   int   i =   34   ;   long   k =   1000000   ;   double   d =   5.0   ; 

Integer Literals

An integer literal can be assigned to an integer variable as long as it can fit into the variable. A compilation error would occur if the literal were too large for the variable to hold. The statement byte b = 128 , for example, would cause a compilation error, because 128 cannot be stored in a variable of the byte type. (Note that the range for a byte value is from to 127 .)

An integer literal is assumed to be of the int type, whose value is between “2 31 ( ”2147483648 ) and 2 31 “1 ( 2147483647 ). The statement System.out.println (2147483648) , for example, would cause a compilation error, because 2147483648 is too long as an int value.


[Page 37]

To denote an integer literal of the long type, append the letter L or l to it (e.g., 2147483648L ). L is preferred because l (lowercase L) can easily be confused with 1 (the digit one). Since 2147483648 exceeds the range for the int type, it must be denoted as 2147483648L .

Note

By default, an integer literal is a decimal number. To denote an octal integer literal, use a leading (zero), and to denote a hexadecimal integer literal, use a leading 0x or 0X (zero x). For example, the following code displays the decimal value 65535 for hexadecimal number FFFF .

 System.out.println(   ox   FFFF   ); 

Hexadecimal numbers, binary numbers, and octal numbers were introduced in §1.5, "Number Systems."


Floating-Point Literals

Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double type value. For example, 5.0 is considered a double value, not a float value. You can make a number a float by appending the letter f or F , and you can make a number a double by appending the letter d or D . For example, you can use 100.2f or 100.2F for a float number, and 100.2d or 100.2D for a double number.

Note

The double type values are more accurate than the float type values. For example,

 System.out.println(   "1.0 / 3.0 is "   +   1.0   /   3.0   ); 

displays 1.0 / 3.0 is 0.3333333333333333.

 System.out.println(   "1.0F / 3.0F is "   +   1.0F   /   3.0F   ); 

displays 1.0F / 3.0F is 0.33333334 .


Scientific Notations

Floating-point literals can also be specified in scientific notation; for example, 1.23456e+2 , the same as 1.23456e2 , is equivalent to 1.23456 x 10 2 = 123.456 and 1.23456e “2 is equivalent to 1.23456 x 10 -2 = 0.0123456 . E (or e ) represents an exponent and can be either in lowercase or uppercase.

Note

The float and double types are used to represent numbers with a decimal point. Why are they called floating-point numbers ? These numbers are stored into scientific notation. When a number such as 50.534 is converted into scientific notation such as 5.053e1 , its decimal point is moved (i.e., floated) to a new position.


2.7.3. Arithmetic Expressions

Writing numeric expressions in Java involves a straightforward translation of an arithmetic expression using Java operators. For example, the arithmetic expression


can be translated into a Java expression as:

 (   3   +   4   * x) /   5    10   * (y -   5   ) * (a + b + c) / x +   9   * (   4   / x + (   9   + x) / y) 


[Page 38]

The numeric operators in a Java expression are applied the same way as in an arithmetic expression. Operators contained within pairs of parentheses are evaluated first. Parentheses can be nested, in which case the expression in the inner parentheses is evaluated first. Multiplication, division, and remainder operators are applied next . If an expression contains several multiplication, division, and remainder operators, they are applied from left to right. Addition and subtraction operators are applied last. If an expression contains several addition and subtraction operators, they are applied from left to right.

Listing 2.3 gives a program that converts a Fahrenheit degree to Celsius using the formula celsius = ( fahrenheit - 32).

Listing 2.3. FahrenheitToCelsius.java
 1   public class   FahrenheitToCelsius { 2   public static void   main(String[] args) { 3   double   fahrenheit =   100   ;  // Say 100;  4   double   celsius =  (   5.0   /   9   )  * (fahrenheit -   32   ); 5 System.out.println(   "Fahrenheit "   + fahrenheit +   " is "   + 6 celsius +   " in Celsius"   ); 7 } 8 } 

Be careful when applying division. Division of two integers yields an integer in Java. is translated to 5.0 / 9 instead of 5 / 9 5 / 9 in line 4, because 5 / 9 yields in Java.

2.7.4. Shorthand Operators

Very often the current value of a variable is used, modified, and then reassigned back to the same variable. For example, the following statement adds the current value of i with 8 and assigns the result back to i .

 i = i +   8   ; 

Java allows you to combine assignment and addition operators using a shorthand operator . For example, the preceding statement can be written as:

 i  +=    8   ; 

The += is called the addition assignment operator . Other shorthand operators are shown in Table 2.3.

Table 2.3. Shorthand Operators
Operator Name Example Equivalent
+= Addition assignment i += 8 i = i + 8
-= Subtraction assignment f -= 8.0 f = f - 8.0
*= Multiplication assignment i*= 8 i = i * 8
/= Division assignment i /= 8 i = i / 8
%= Remainder assignment i %= 8 i = i % 8

There are two more shorthand operators for incrementing and decrementing a variable by 1. This is handy because that is often how much the value needs to be changed. These two operators are ++ and “ “ . They can be used in prefix or suffix notation, as shown in Table 2.4.


[Page 39]
Table 2.4. Increment and Decrement Operators
Operator Name Description
++var preincrement The expression ( ++var ) increments var by 1 and evaluates to the new value in var after the increment.
var++ postincrement The expression ( var++ ) evaluates to the original value in var and increments var by 1.
--var predecrement The expression ( “ “var ) decrements var by 1 and evaluates to the new value in var after the decrement.
var-- postdecrement The expression ( var “ “ ) evaluates to the original value in var and decrements var by 1 .

If the operator is before (prefixed to) the variable, the variable is incremented or decremented by 1, then the new value of the variable is returned. If the operator is after (suffixed to) the variable, the original old value of the variable is returned, then the variable is incremented or decremented by 1. Therefore, the prefixes ++x and “ “x are referred to, respectively, as the preincrement operator and the predecrement operator ; and the suffixes x++ and x “ “ are referred to, respectively, as the postincrement operator and the postdecrement operator . The prefix form of ++ (or “ “ ) and the suffix form of ++ (or “ “ ) are the same if they are used in isolation, but they cause different effects when used in an expression. The following code illustrates this:

In this case, i is incremented by 1 , then the old value of i is returned and used in the multiplication. So newNum becomes 100 . If i++ is replaced by ++i as follows ,

i is incremented by 1 , and the new value of i is returned and used in the multiplication. Thus newNum becomes 110 .

Here is another example:

   double   x =   1.0   ;   double   y =   5.0   ;   double   z = x “ “ + (++y); 

After all three lines are executed, y becomes 6.0 , z becomes 7.0 , and x becomes 0.0 .

The increment operator ++ and the decrement operator “ “ can be applied to all integer and floating-point types. These operators are often used in loop statements . A loop statement is a structure that controls how many times an operation or a sequence of operations is performed in succession. This structure, and the subject of loop statements, is introduced in Chapter 4, "Loops."

Tip

Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to read. Avoid using these operators in expressions that modify multiple variables or the same variable multiple times, such as this one: int k = ++i + i .



[Page 40]

Note

Like the assignment operator ( = ), the operators ( += , -= , *= , /= , %= , ++ , and ” ” ) can be used to form an assignment statement as well as an expression. For example, in the following code, x = 2 is a statement in the first line and is an expression in the second line.

  x =   2    ;  // statement  System.out.println(  x =  2   );  // expression  

If a statement is used as an expression, it is called an expression statement .


Caution

There are no spaces in the shorthand operators. For example, + = should be += .


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net