Title: CS2
1CS2
- Module 6
- Category Elements of Java
- Topic Datatypes
- Objectives
- Data typing
- Casting
2CS 2
- Introduction to
- Object Oriented Programming
- Module 6
- 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
5Built-in Data Types
- Java primitives (whole numbers)
- byte
- short
- int
- long
- Java primitives (real numbers)
- float
- double
6Built-in Data Types
- Java primitives (text)
- char (character, use single quotes b)
- String
- Java primitives (True/False)
- boolean
- String is not a primitive
7Public 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
8Data 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
9Variable Declarations
- Simple form
- ltdatatypegt ltidentifiergt
- Example
- int total
- Optional initialization at declaration
- ltdata typegt ltidentifiergt ltinit valuegt
- Example
- int total 0
10Examples
- 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
11Primitive 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.
12Space Time
- Why so many data types?
- Performance
- Smaller data items (byte, short, float) take up
less space - Integer calculations are faster than floating
point calculations - Nevertheless, sometimes we need to convert data
from one type into another
13Type 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!
14Problems?
- Let's say that you have a floating point number
in a variable f and you decide to store it in an
integer variable i -
- i f
- Any problems possible?
15Problems
- There is the possibility of loss of information
- 6.1 ? 6
- 6.5 ? 6
- 6.999999 ? 6
- Because of this, the Java compiler will not
compile your code!!! - Demo.java7 possible loss of precision
- found float
- required int
- i f
-
- 1 error
16Casting
- 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
17Problems?
- Casting to let Java know that you are aware of
potential problem and want to override the error -
- i (int)f
- But we often must use a cast in the middle of an
expression to control behavior
18Precise 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?
19One way
- Consider
- float f
- int i 5
- int j 2
- float temp1 i
- float temp2 j
- f temp1/temp2
- Result?
- f 2.5
20Better (Easier?) Way
- Consider
- float f
- int i 5
- int j 2
- f (float)i/(float)j
- Result?
- f 2.5
21Casting
- 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.
22We 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
23Only 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
24The 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.
25But 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
26But 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!
27Test 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?
28Understanding Casting
To understand casting, we need to review the
primitive data types in Java.
Let's work with two examples int x byte c
Now, how BIG are these data types in memory?
29Recall
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.
small cereal box
Nutritional Facts Serv. Size 1 int Amount per
Serving Calories 0 Daily
Value Total Bytes 4 100
30And recall...
A byte on the other hand is only a byte. It's a
quarter the size of an int. We might imagine it
as a smaller container.
tuna can
31So...
A byte is a byte (8 bits), and an int is four
bytes. So when we code the following int
x 86 byte b 65 We have
Symbol Picture of
Memory
x
0000 0000
0000 0000
0000 0000
0101 0110
Each block is one byte
b
32Reality 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.
33In a similar vein...
Will a byte fit into an int? Will an int fit
into a byte?
Symbol Picture of
Memory
x
b
34Reality Check
What if you wanted to fit just part of the box
into the can. That would fit!
For example, if we know the top 3/4 of the box is
empty, we can throw it away!
35Explicit Casting Intentional Loss of Precision
int x 45 byte b b (byte) x // cast
needed
Symbol Picture of
Memory
x
b
cast needed!
36Testing Yourself
What happens when we do this int first
2000 long second second (long)
first Legal?
37Testing 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.
38Another 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
39Casting 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
40Another 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.
41public 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
42When 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
43Casting Test Your Knowledge
- Given
- int iStart 10
- float fTemp 5.5f
- fTemp (int) fTemp iStart
- What does fTemp now hold?
Quick Review
44Test 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
45Initialization
- Java allows multiple assignment.
- int iStart, iEnd
- int iWidth 100, iHeight 45, iLength 12
- This tends to complicate comments, however
- /
- Declare cylinders diameter and height
- /
- int iDiameter 50, iHeight 34
Java has an automatic documentation feature
called Javadoc. (You'll get it when you install
Java.) We'll talk about it soon. The Javadoc
comment shown here will get repeated in the
output of the Javadoc utility, once above each
listed variable!
46Examples
- 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!
47Primitive Casting
- Conversion of primitives is accomplished by
- Assignment with implicit casting
- or 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) . . .
48Questions
49(No Transcript)