03 Primitive Datatypes
03 Primitive Datatypes
James Brucker
Primitive Data Types
A primitive data type has only a value, such as a
number.
Weird:
int
'a'+1 'a' -> int (97) 98
short,char
byte
Type Promotion & Functions
If you invoke a function (method) using a numeric value,
Java may "promote" the values of arguments.
double Example Promotion Then Call
Math.sqrt( 2 ) 2 to 2.0 sqrt(2.0)
Math.max( 2, 10.0F ) 2 to 2.0F max(2F,10F)
float
Math.max(-1, -4L ) -1 to -1L max(-1L,-4L)
Math.max( 3, 2.236 ) 3 to 3.0 max(3.0,2.236)
long
Type Conversion May Lose Precision
int
Java "type promotion" always perform a widening
conversions that will never "overflow" the result data type.
short,char
But it may lose precision (accuracy).
byte Example: (float)123456789 -> 1.2345679E+8
What about boolean?
boolean type (true, false) cannot be converted to
any other type!
int n = 1;
if (n = 2) printf("its true!"); // set n=2, result is true!
should be:
if (n == 2) . . . ;
Common Type Errors
Here are some common errors.
What is the mistake? How to correct it?
// write happyPetOwner
// using only &&, ||, and !
happyPetOwner =
char for character data
The char data type is for character data.
Java uses 2-byte Unicode for character data, in order to
short Short
// print as a string
int Integer
out.println( d2.toString( ) );
long Long
// static method to make a string
float Float
out.println( Integer.toString( 2 ) );
double Double
Why Wrapper Classes?
1. Some methods and data structures only work with
references (e.g. objects).
Example: a List can only contain references.
If we want a List of double, we need to "wrap" each
double in an object.
String s = "2.5";
// convert s to a double?
Range limits of numeric types
What is the largest "int" value?
What is the smallest "long" value?
int biggest =
long smallest =
double minimum =
double maximum =
What happens if you go beyond?
int n = Integer.MAX_VALUE;
n = n + 1;
System.out.println( n );
double d = Double.MAX_VALUE;
d = d + 1;
System.out.println( d );
d = d * 1.000001;
System.out.println( d );
What happens if you go beyond?
int n = Integer.MAX_VALUE;
n = n + 1;
n is -2147483648
double d = Double.MAX_VALUE;
d = d + 1;
no change. +1 insignificant (too small)
d = d * 1.000001;
d is Infinity
C# numerics are different
"int", "float", "double" are struct types.
// This is C#
int n = int.MaxValue;
String s = "Biggest int is "
+ n.ToString( ) ;
// range checking is enforced
n = n + 1;