Title: CS2
1CS2
- Module 5
- Category Elements of Java
- Topic Datatypes
- Objectives
- Data typing
- Casting
2CS 2
- Introduction to
- Object Oriented Programming
- Module 5
- Elements of Java
- Data Types
3Data Types
- Interacting with the real world requires
representing a wide variety of different types of
data - Integer, real and imaginary numbers
- Differing precision and range depending on
application - Characters, strings and other textual data
- True, false values
- On/Off
- Stop/Go
4Computer Numbers
- Integers (byte, short, int, long)
- whole numbers
- exact
- Relatively limited in magnitude (1019)
- Floating Point (float, double)
- fractional
- often approximations (0.33333)
- larger magnitude (10308)
- Actually hold signed mantissa exponent
- 6.023 x 1023
5Type Checking
- What happens when data is changed from one
representation to another? - Some languages (such as Java) enforce a strict
set of rules to try and catch problems early - This may seem annoying at first
- Later, it will really get under your skin!
6Built-in Data Types
- Java primitives (whole numbers)
- byte
- short
- int
- long
- Java primitives (real numbers)
- float
- double
7Built-in Data Types
- Java primitives (text)
- char (character, use single quotes b)
- String
- Java primitives (True/False)
- boolean
- String is not a primitive
8Public Service Announcement
- We start by discussing simple primitive data
types - Later we will discuss user defined data types as
part of the Object Oriented portion of the
material - For now, you should know that Java has a
"built-in" type String - We introduce it know as a useful tool but we will
come back later and explain more fully
9Data Type Default Values
Primitive Type Default Value boolean
false char
'\u0000' (null) byte (byte) 0 short
(short) 0 int
0 long
0L float 0f double
0d
10Variable Declarations
- Simple form
- ltdatatypegt ltidentifiergt
- Example
- int total
- Optional initialization at declaration
- ltdata typegt ltidentifiergt ltinit valuegt
- Example
- int total 0
11Examples
- int counter
- int numStudents 583
- float gpa
- double batAvg .406
- char gender
- char gender f
- boolean isSafe
- boolean isEmpty true
- String personName
- String streetName North Avenue
12Primitive Type Facts
Type
Size
Min
Default
Max
boolean
false
1
false
true
char
'\u0000' (null)
16
byte
(byte) 0
8
-128
127
short
(short) 0
16
-32,768
32,767
int
0
32
-2,147,483,648
2,147,483,647
long
0L
64
-9,223,372,036,854,775,808
9,223,372,036,854,775,807
float
0.0F
32
Approx 3.4E38 with 7 significant digits
double
0.0D
64
Approx 1.7E308 with 15 significant digits
void
Not truly min and max.
13Casting
- As noted, Java is a strongly typed language.
- This means
- That precise rules exist as to how arithmetic
expressions are executed - Only certain assignments are legal. Others will
cause errors during compilation - These behaviors can be overridden using casting
14Precise Rules
- Consider
- float f
- int i 5
- int j 2
- f i/j
- Result?
- f 2.0
But what if we wanted 2.5 as a result?
15One way
- Consider
- float f
- int i 5
- int j 2
- float temp1 i
- float temp2 j
- f temp1/temp2
- Result?
- f 2.5
16Better (Easier?) Way
- Consider
- float f
- int i 5
- int j 2
- f (float)i/(float)j
- Result?
- f 2.5
17Casting
- We say "cast i to a float"
- (float)i
- Are we actually changing i???
- No, we are telling Java to convert the value of i
to a float before making the calculation. - We are not actually changing the contents of
variable i.
18We can even...
- Consider
- float f
- int i 5
- int j 2
- f (float)i/j
- Result?
- f 2.5
- When dividing two different types Java will
automatically cast the j for us
19Only certain assignments are legal
- Java will attempt to prevent errors that might
result in loss of data - Smaller sized integer type values may be assigned
to larger sized integer values. The opposite is
not true - Integer type values may be assigned to floating
point values. The opposite is not true - Floats may be assigned to doubles. The opposite
is not true
May be overridden with casting
20The Good and the Bad
Assume byte b short s int i long L float
f double d
- Legal
- s b
- i b
- L b
- f b
- d b
- f i
- etc.
- Illegal
- b s
- s i
- i L
- L f
- f d
- i f
- etc.
21But wait...
- int i 42
- byte b
- b i
- Surely 42 will fit in a byte???
- Yes, we just need to tell Java we know what we're
doing!!! How? Casting
22But wait...
- int i 42
- byte b
- b (byte)i
- This doesn't change the contents of variable i
but it does tell Java that we are taking the
responsibility for problems!
23Test Yourself
Sometimes an explicit cast is required, sometimes
it's not.
float f2 11.234 int y f2
int x 10 float f1 x
Which one requires a cast to compile? Why?
24Understanding Casting
To understand casting, we need to review the
primitive data types in Java.
Let's work with two examples int x char c
Now, how BIG are these data types in memory?
25Recall
We already discussed the sizes of various data
types in Java. You are guaranteed to have four
bytes in each and every int. We can think of an
int as a container--much like a box.
cereal box
Nutritional Facts Serv. Size 1 int Amount per
Serving Calories 0 Daily
Value Total Bytes 4 100
26And recall...
A char on the other hand is only 2 bytes. It's
half the size of an int. We might imagine it as
a smaller container.
tuna can
27So...
A char is two bytes, and an int is four bytes.
So when we code the following int x 86
char c 'A' We have
Symbol Picture of
Memory
x
0000 0000
0000 0000
0000 0000
0101 0110
Each block is one byte
c
0100 0001
0000 0000
28Reality Check
Will a can of tuna fit into a box of cereal?
Yes, the can is smaller.
Will a box of cereal fit into a can of tuna? Not
neatly, the box is larger.
29In a similar vein...
Will a char fit into an int? Will an int fit
into a char?
Symbol Picture of
Memory
x
c
30Reality Check
What if you wanted to fit HALF the box into the
can. That would fit!
For example, if we know the top half of the box
is empty, we can throw it away!
31Explicit Casting Intentional Loss of Precision
int x 45 char c 'A' c (char) x //
cast needed
Symbol Picture of
Memory
x
c
cast needed!
32Testing Yourself
What happens when we do this int first
2000 long second second (long)
first Legal?
33Testing Yourself
What happens when we do this int first
2000 long second second (long)
first Legal? But unnecessary. Java would have
performed the conversion for us.
34Another example
We also have to consider how Java preserves the
sign of a value through casting. Consider the
eight bytes used for an int. The highest bit is
used for a sign (plus or minus, through a 0 or 1).
int
Sign bit
31 bits for data
35Casting and Sign
Casting is not merely cropping one data type into
another. The VM doesn't merely throw away half
of the information. One also has to consider and
preserve the sign value.
Preserves sign bit
byte
int
36Another Example
Suppose we had some very, very old data, where
the date was expressed in a "int" (four byte)
format, such as
19291031
This is very crude, but some old data source
(e.g., tape archives) might have this format.
37public class CutData public static void
main(String args) int iDate 20001225 //
this is how it was read in byte byDay (byte)
(iDate 100) System.out.println ("The day was
" byDay) iDate iDate / 100 byte
byMonth (byte) (iDate 100) System.out.print
ln ("The month was " byMonth) iDate iDate
/ 100 short sYear (short)
iDate System.out.print ("The year was "
sYear) // CutData
38When working in the opposite direction
(accumulating bytes and shorts into an int), no
casting is needed, because we do not lose
precision or information.
public class PackDate public static void
main(String args) byte byMonth
12 byte byDay 25 short sYear
2000 int iDate sYear 10000
byMonth 100
byDay System.out.println ("The date "
iDate) // PackDate
39Casting Test Your Knowledge
- Given
- int iStart 10
- float fTemp 5.5f
- fTemp (int) fTemp iStart
- What does fTemp now hold?
Quick Review
40Test Your Knowledge
- Here's the problem
- int iVar 10
- float fVar 23.26f
- // gives compile-time error
- iVar iVar fVar
- Which solution works best?
3
230
4
1
232
232
2
Quick Review
Same Compile Error
41Initialization
- Java allows multiple assignment.
- int iStart, iEnd
- int iWidth 100, iHeight 45, iLength 12
- This tends to complicate javadoc comments,
however - /
- Declare cylinders diameter and height
- /
- int iDiameter 50, iHeight 34
Javadoc comment gets repeated twice in
output, once above each listed variable!
42Examples
- Note that whole integers appearing in your source
code are taken to be ints. So, you might wish
to flag them when assigning to non-ints - float fMaxGrade 100f // now holds 100.0
- double dTemp 583d // holds double precision
583 - float fTemp 5.5 // ERROR!
- // Java thinks 5.5
is a double - Upper and lower case letters can be used for
float (F or f), double (D or d), and long
(l or L, but we should prefer L) - float fMaxGrade 100F // now holds 100.0
- long x 583l // holds 583, but looks
like 5,381 - long y 583L // Ah, much better!
43Primitive Casting
- Conversion of primitives is accomplished by (1)
assignment with implicit casting or (2) explicit
casting - int iTotal 100
- float fTemp iTotal // fTemp now
holds 100.0 - When changing type results in a loss of
precision, an explicit cast is needed. This is
done by placing the new type in parens - float fTotal 100f
- int iTemp fTotal // ERROR!
- int iStart (int) fTotal
- We will see much, much more casting with
objects (later) . . .
44Questions
45(No Transcript)