JDEP 183H

Handout 2:  Numerical Data

 

August 24, 2006

 

Table 2.1  Java numerical data types and their precisions.

 

Data Type

Content

Default Value*

Minimum Value

Maximum Value

byte

Integer

0

-128

127

short

Integer

0

-32768

32767

int

Integer

0

-2147483648

2147483647

long

Integer

0

-9223372036854775808

9223372036854775807

float

Real

0.0

-3.40282347E+38

3.40282347E+38

double

Real

0.0

-1.79769313486231570E+308

1.79769313486231570E+308

* No default value is assigned to a local variable

 

Table 2.2  Arithmetic operators.

 

Operation

Java Operator

Example

Value

(x = 10, y = 7, z = 2.5)

Addition

+

x + y

17

Subtraction

-

x - y

3

Multiplication

*

x * y

70

Division

/

x / y

x / z

1

4.0

Modulo Division (Remainder)

%

x % y

3

 

Table 2.3  Precedence rules for arithmetic operators and parentheses.

 

Order

Group

Operator

Rule

High

 

 

 

 

Low

Subexpression

( )

Subexpressions are evaluated first.  If parentheses are nested, the innermost subexpression is evaluated first.  If two or more pairs of parentheses are on the same level, then they are evaluated from left to right.

Unary operator

-, +

Unary minuses and pluses are evaluated second.

Multiplicative operator

*, /, %

Multiplicative operators are evaluated third.  If two or more multiplicative operators are in an expression, then they are evaluated from left to right.

Additive operator

+, -

Additive operators are evaluated last.  If two or more additive operators are in an expression, then they are evaluated from left to right.

 


Table 2.4  Rules for arithmetic promotion.

 

Operator Type

Promotion Rule

Unary

  1. if the operand is of type byte or short, then it is converted to int.
  2. Otherwise, the operand remains the same type.

Binary

  1. if either operand is of type double, then the other operand is converted to double.
  2. Otherwise, if either operand is of type float, then the other operand is converted to float.
  3. Otherwise, if either operand is of type long, then the other operand is converted to long.
  4. Otherwise, both operands are converted to int.

 

Table 2.5  Common wrapper classes and their conversion method.

 

Class

Method

Example

Integer

parseInt

Integer.parseInt(“25”) à 25

Integer.parseInt(“25.3”) à error

Long

parseLong

Long.parseLong(“25”) à 25L

Long.parseLong(“25.3”) à error

Float

parseFloat

Float.parseFloat(“25.3”) à 25.3F

Float.parseFloat(“ab3”) à error

Double

parseDouble

Double.parseDouble(“25”) à 25.0

Double.parseDouble(“ab3”) à error

 

Based on (Wu 2004)