CS 1312 - PowerPoint PPT Presentation

1 / 74
About This Presentation
Title:

CS 1312

Description:

Note: At times, the Java Language Specification refers to void as a primitive, ... Approx 3.4E 38 with 7 significant digits. double. 0.0D. 64 ... – PowerPoint PPT presentation

Number of Views:27
Avg rating:3.0/5.0
Slides: 75
Provided by: alant9
Category:
Tags: forsee

less

Transcript and Presenter's Notes

Title: CS 1312


1
CS 1312
  • Introduction to
  • Object Oriented Programming
  • Lecture 2
  • January 11, 2001

2
Again-da (agenda)
Primitives in Java -- review
3
Computer 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

4
List of Data Types
Primitive Type Default Value boolean
false char
'\u0000' (null) byte (byte) 0 short
(short) 0 int
0 long
0L float 0f double
0d void
N/A
Note At times, the Java Language Specification
refers to void as a primitive, though other parts
(e.g., s. 14.7) say void is not a primitive as
in C/C. One cannot cast to a void type in Java.
5
Data Type Ranges
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.
6
Understanding Casting
Last class, we covered some basics of
casting. Sometimes an explicit cast is required,
sometimes its not.
float f2 11.234 int y f2
int x 10 float f1 x
Which one requires a cast to compile? Why?
7
Understanding Casting
To understand casting, we need to review the
basic data types in Java.
Lets work with two examples int x char c
Now, how BIG are these data types in memory?
8
Recall
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
9
And recall...
A char on the other hand is only 2 bytes. Its
half the size of an int. We might imagine it as
a smaller container.
tuna can
10
So...
A char is two bytes, and an int is four bytes.
So when we code the following int x 86
char c 'A' We get
Symbol Picture of
Memory
x
0000 0000
0000 0000
0000 0000
0101 0110
Each block is one byte
c
0100 0001
0000 0000
11
Reality 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.
12
In a similar vein...
Will a char fit into an int? Will an int fit
into a char?
Symbol Picture of
Memory
x
c
13
Reality 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!
14
Explicit Casting Intentional Loss of Precision
int x 45 char c A c (char) x //
cast needed

Symbol Picture of
Memory
x
c
cast needed!
15
Testing Yourself
Fill in the blank.
What happens when we do this int i
2000 long l l (long) i This is
better know as _____________________
a cast of thousands.
Lesson Casting is subtle, dry business.
16
Another Example
float f int i, j i 9 j 2 f i / j
Returns 4 because of integer truncation!
Two solutions
f (float) i / j
f (float) i / (float) j
17
Another 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
18
Casting and Sign
Casting is not merely cropping one data type into
another. The VM doesnt merely throw away half
of the information. One also has to consider and
preserve the sign value.
Preserves sign bit
byte
int
19
Another 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.
20
public 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
21
When 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
22
Casting Test Your Knowledge
  • Given
  • int iStart 10
  • float fTemp 5.5f
  • fTemp (int) fTemp iStart
  • What does fTemp now hold?

Quick Review
23
Test Your Knowledge
  • Heres 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
24
Shorthand Operators
  • iCounter iCounter 1 OR iCounter
  • iCounter iCounter - 1 OR iCounter--
  • iCounter iCounter 2 OR iCounter2
  • iCounter iCounter 5 OR
    iCounter5Last two examples its op then
    equals (e.g., 2), not equals then op
    (e.g., isnt 2)

Quick Review
Understand this, but please avoid these types of
expressions.
25
The Short End of Shorthand
Be careful to avoid clever expressions with
shorthand notations. For example, we can declare
a variable called _. (Yes, and underline
character alone is a valid name.)
int _ 1 We can then use a combination of
operators to make Morse code _
- --_ - _-- Yes, this is valid however, its
completely unreadable. (Your replacement will not
appreciate this style!)
26
Documentation Comments
Quick Review
  • Three ways to do it
  • // Double slashes comment out everything until
    the end of the line
  • / This syntax comments out everything between
    the / and the /.
  • (There are no nested comments as in C. /
  • /
  • This is syntax for Javadoc comments (similar
    to second style
  • of commenting, but allows for HTML formatting
    features.
  • /
  • For CS1302, use Javadoc comments

Lets work a javadoc example
27
Javadoc Simple Example
import java.util. / HelloComments.java
Created Wed Jan 12 181729 2000
_at_author David Dagon _at_version 98 beta
/ public class HelloComments /
An ltbgt VERY lt/bgt simple variable. /
public int x 10
Javadoc comments must appear above the item they
modify. In the case of class comments, place
them BELOW the import statements.
Recall HTML is OK!
28
Simple Example (contd)
/ This comment is reproduced twice,
because of the comma delimited
declaration of ints. The solution would
be to use separate lines for each
declaration. / public int y 4, z
11 / The Main method. This
method is the starting point of this
program, when this class is run.
_at_param args The arguments from the command line.
/ public static void main(String args)
// HelloComments
29
(No Transcript)
30
Et Voila...
31
Et Voila Part Deux...
32
Et Voila Part III...
33
Enfin
34
Javadoc (Contd)
  • You may include HTML tags (but avoid structuring
    tags, like ltH1gt, etc.)
  • Javadoc comments should immediately preceed the
    declaration of the class, field or method. The
    first sentence should be a summary. Use the
    special javadoc tags--_at_. When '_at_' tags are used,
    the parsing continues until the doc compiler
    encounters the next '_at_' tag.

_at_see ltclass namegt _at_see ltfull-class namegt _at_see
ltfull-class namemethod.namegt _at_versio
n
You might refer back to these notes once you
start writing your own javadoc comments.
_at_author _at_param _at_return
_at_exception
_at_deprecated // jdk 1.1
_at_since
// jdk 1.1 _at_serial // jdk 1.2
35
Question?
Did you know a take home quiz was handed
out during the first class? Did you know its
due next week during recitation? If you need a
copy, see the class web page.
36
Questions?
37
By the way...
  • In CS 1311 or CS 1311X you were introduced to
    Java.
  • What things are you hoping to get cleared up?

38
Constants
Quick Review
  • CS1501/CS1311
  • ltCONST_IDgt is ltconstant valuegt
  • MIN_PASSING is 60
  • PI is 3.14159
  • Java
  • public final static lttypegt ltIDergt ltvaluegt
  • public final static int MIN_PASSING 60
  • public final static float PI (float) 3.14159
  • Details on why this syntax to come soon...

39
Printing to Screen
  • CS1501/CS1311
  • print (ltargumentsgt)
  • Java
  • System.out.println(ltargumentgt)
  • System.out.println( ) // prints blank line
  • System.out.println(5) // prints 5
  • System.out.println(Hello World) // prints
    Hello World
  • println vs. print in Java
  • println includes carriage return at end, next
    print or println on new line
  • print causes next print or println to begin at
    next location on same line

Quick Review
40
Questions
41
MethodMadness
42
Caution
Before we can talk about methods in Java, we need
to look at programming languages in general,
from a very high level. Dont be alarmed by some
of the syntax on the following slides. The big
picture is whats important, not the coding
details....
43
Programming Paradigms
Procedural Programming Imperative
assignment used to create state, and procedures
manipulate state. E.g., C, Assembly, Pascal
int y int x 3 y
manipulateData(x) Functional Programming
Functions (procedures that do not depend on
outside data) are used to provided data. E.g.,
Lisp. (defun check-member (input-item
input-list) (cond ((null input-list)
nil) ((equal input-item
(first input-list)) T) (T
(check-member input-item (rest input-list)))))
44
Programming Paradigms
Object-Oriented Programming All data exists
in objects interaction occurs only between
objects. Even numbers are objects that know how
to add themselves. E.g., SmallTalk array
array Array new 5. rect 0_at_0 corner
8_at_9. 1 to array size do item rect
origin item_at_item. array at item put rect
copy . Java Object-oriented, but not 100
OO, since it contains primitives, and tolerates
some (hopefully small) degree of procedural
programming.
There are other paradigms, but these three help
explain where Java comes from
45
Java Methods
  • There exists in Java a single construct, the
    method, for both procedures and functions
  • when a procedure is called for, specify the
    return type void before method name
  • public void printHelloWorld( )
  • System.out.println(Hello World!)
  • // of printHelloWorld
  • Note All methods must have parentheses for
    parameters . . . even if no parameters!

Note the comment
46
Java Methods
  • Single construct for both procedures and
    functions
  • when a function is called for, specify the
  • appropriate return type before method name
  • public float average (float fNum1, float
    fNum2, float fNum3)
  • float fReturnVal
  • fReturnVal
  • (fNum1 fNum2 fNum3)/ 3
  • return (fReturnVal)
  • // of average

47
Writing Methods A Larger Look
A Java requirement --All methods belong to an
object (or class). --Name of object (or class)
must be unambiguous when method called. --To
run a program, there must be a class (whose
name is the name-of-the-program), containing
a special method called main
for command line parameters
visible to all
nothingreturned
public static void main (String argv)
a class method,not aninstancemethod
Method name
48
class A public static void main(...
Thus, each class may have its own main method.
You pick the one you with to run when invoking
the JVM. This fact become critical when we
learn to write debug test mains.
class B public static void main(...
class C public static void main(...
49
Method Signatures
The signature of a method consists of the name
of the method and the number and types of formal
parameters to the method. A class may not declare
two methods with the same signature, or a compile
time error occurs. --Java Language
Specification s.8.4.2 Method overloading occurs
where identically named methods have subtle
variations in the method parameters. public int
getCube(int iNum) return iNumiNumiNum
public int getCube(float fNum) return
(int)(fNumfNumfNum) public int
getCube(double dNum) return (int)
(dNumdNumdNum)
cs1311 associated two similar methods by
calling one a helper method. Java lets
you overload instead.
50
Methods Common Mistakes
public float average (float fNum1, float fNum2,
float fNum3) float fReturnVal
fReturnVal (fNum1
fNum2 fNum3)/ 3 return (fReturnVal)
// of average
Note ending semicolon -- could be viewed as
abstract method (more on abstract methods
later) -- results in unhelpful error message
about abstract methods (more
on this later) -- You are 100
guaranteed to make this mistake.
51
Where do Methods Go?
Just like the main method we saw last time, any
method we create must appear in classes, as
either class or instance members. More on
creating classes and objects shortly . . . For
now, just know that methods belong in a class.
52
OO Programming Note
Already, weve covered one of the most important
aspects of Object Oriented (OO) programming the
notion that data and methods belong together in a
class. Right now, its sufficient that you
merely know that variables and methods belong in
classes. Later, well see how this enables us to
encapsulate state (the variables) with behavior
(the methods). So, remember this day. Youve
started to learn THE cornerstone of OO
programming.
53
Questions?
54
Conditionals
55
Decision Statements
  • CS 1501/1311 pseudocode
  • if (condition) then
  • statements
  • else
  • other statements
  • endif
  • Java
  • if (condition)
  • single statement
  • else
  • single statement
  • or
  • if (condition)
  • statements
  • else
  • statements

56
Examples
  • CS1311/1501
  • test_grade isoftype Num
  • test_grade lt- 65
  • is_passing isoftype Boolean
  • is_passing lt- TRUE
  • if (test_grade lt 60) then
  • is_passing lt- FALSE
  • endif
  • print (Is , iTestGrade,
  • passing? , is_passing)
  • Java What happens here?
  • int iTestGrade 65
  • boolean bPassing true
  • if (iTestGrade lt 60)
  • bPassing false
  • System.out.println
  • (Is iTestGrade
  • passing?
  • bPassing)

57
Boolean and Relational Operators
  • Boolean CS1311/1501 Java
  • AND AND
  • OR OR
  • NOT NOT
    !
  • Relational
  • equal to
  • not equal to ltgt
    !
  • less than lt
    lt
  • less than or equal to lt
    lt
  • greater than gt
    gt
  • greater than or equal to gt
    gt
  • Note
  • Assignment lt-

58
Example
if (bEnrolled bPassing) // etc.
Java also supports short-circuiting, where only
part of a boolean will be evaluated, as
necessary
if (getEnrolled(iStudentNum)
getPassing(iStudentNum)) // etc.
If first condition is true, it stops evaluation
59
A bit o code
  • public static void main(String args)
  • int quiz1 42
  • int quiz2 99
  • if(isPassing(quiz1) isPassing(quiz2))
  • System.out.println(Passed both quizzes)
  • public static boolean isPassing(int iTestGrade)
  • boolean bPassing true
  • if (iTestGrade lt 60)
  • bPassing false
  • System.out.println(Is iTestGrade
  • passing? bPassing)
  • return bPassing

Output?
60
Final Answer?
a
  • Is 42 passing? false

b
Is 42 passing? false Is 99 passing? true
Why?
61
What?
Java also supports short-circuiting, where only
part of a boolean will be evaluated, as
necessary
if (getEnrolled(iStudentNum)
getPassing(iStudentNum)) // etc.
If first condition is false, it stops evaluation
62
Multiple Selections via switch
  • Use if construct for one selection.
  • Use if/else construct for double selection.
  • Use switch construct for multiple selection.
    (e.g., situations appropriate for
    if-elseif-elseif-else)Note
  • Useful when making a selection among
    multiple values of the same variable.
  • Not useful when selecting among values of
    different variables.

63
Switch
  • switch (ltvariablegt)
  • case ltvaluegt
  • // whatever code you want
  • break // optional
  • case ltvaluegt
  • // whatever code you want
  • break // optional
  • default
  • // whatever code you want
  • break // optional

64
Multiple Selections via switch
Note the optional default case at the end of
the switch statement. It is optional only in
terms of syntax. switch (iNumber) case
1 System.out.println (One) break
case 2 System.out.println (Two) break
case 3 System.out.println
(Three) break default
System.out.println(Not 1, 2, or 3)
break // Needed??? // switch In
practice you should always include a default
case statement. e.g., 1989 ATT phone system
crash
This would work without the default, but would
be poor technique
65
How many days?
  • if(month 4 month 6
  • month 9 month 11)
  • numdays 30
  • else if(month 2)
  • numdays 28
  • if(leap)
  • numdays 29
  • else
  • numdays 31

66
Switch
  • switch (month)
  • case 4
  • case 6
  • case 9
  • case 11
  • numdays 30
  • break
  • case 2
  • numdays 28
  • if(leap)
  • numdays 29
  • break
  • default / Good idea? /
  • numdays 31

67
Multiple Selections via switch--Notes
  • The switch statement can only be used with
  • the following types
  • int, char, short byte
  • (You can cast floats, doubles, etc.)
  • The case values must all be of the same type.
  • The case values must all be FINAL constants.

68
switch (chGrade) case A case a
iCountOfAGrades break case B
case b iCountOfBGrades
break case C case c
iCountOfCGrades break case D
case d iCountOfDGrades
break case F case f
iCountOfFGrades break default
System.out.println(Invalid grade)
break
if (chGradeA chGradea) iCountOfAGrad
es else if (chGradeB chGradeb) iCou
ntOfBGrades else if (chGradeC
chGradec) iCountOfCGrades else if
(chGradeD chGraded) iCountOfDGrades
else if (chGradeF chGradef)
iCountOfFGrades else System.out.println
(Invalid grade)
Multiple Selections via switch
69
Before we go too far...
  • We often take liberties with good coding practice
    just to fit material onto a slide.
  • Your coding style should reflect clearly and
    unambiguously what the code is supposed to do.
  • Keep in mind your two audiences
  • The machine
  • Other programmers

70
IfStyle 1
  • if(ltboolean expressiongt)
  • // code if true
  • // see your TA
  • else
  • // code if false
  • // see your TA

71
IfStyle 2
  • if(ltboolean expressiongt)
  • // code if true
  • // comment
  • else
  • // code if false
  • // comment

72
Conditional Assignment
ltbooleangt ? lttrue conditiongt ltfalse conditiongt
boolean b int iCount b checkCompletion() iC
ount (b) ? 3 1
Note This is not any faster. Its less
readable. It exists only for recovering
C hackers
Must resolve to boolean
If true . . .
. . . if false
73
A Semi Partial Conditional Summary
  • Control structures
  • Two kinds of conditional (summary)
  • if ... else ...
  • branch on boolean expression
  • switch (...) case ... break default ...
  • branch on constant value
  • dont forget to break !!

74
Questions?
75
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com