Java Beginnings slides

Download Report

Transcript Java Beginnings slides

Java :
A Gentle Introduction
- presented by Fran Trees
1
Columbia University JETT
3/28/2003
Java Programming
Language
1991

A group led by James Gosling and Patrick Naughton
at Sun Microsystems designed “Green”, a language
for consumer devices (coffee makers, VCRs, etc.).
Didn’t overly excite anyone.
1994

Gosling – HotJava Browser
• could download “applets” from the web and run
them
• applets were written in Java.
• greatly extended capabilities of a web page
2
Columbia University JETT
3/28/2003
Java Advantages
Platform independence
Reuse of code
Security
Automatic garbage collection
Stronger typing of objects and
variables
3
Columbia University JETT
3/28/2003
Java Technology:
Programming language

Syntax and semantics
Development environment

Compiler, interpreter, documentation
generator, class packaging tool
Application environment

Standalone programs- run on any machine
where Java Runtime Environment is
installed (JRE)
Deployment environment

4
JRE supplied by SDK: contains class files,
GUI classes, etc.
Columbia University JETT
3/28/2003
Portability and Security
Java Virtual Machine



5
An imaginary machine that is implemented
by emulating it in software on a real machine
(fake CPU that sits on top of an operating
system). Code for the JVM is stored in .class
files.
Provides hardware platform specifications
Reads compiled byte codes that are platform
independent
Columbia University JETT
3/28/2003
JVM
A JVM has been written for every operating
system.
A compiler takes Java application source code and
generates bytecode (machine code instructions for
JVM).
Java source code
(Car.java)
not readable by humans;
not really machine code…
compiled
bytecode
Car.class
JVM
Mac
6
JVM
Unix
Columbia University JETT
Still platform
dependent
JVM
Windows
3/28/2003
Runtime
JRE
class loader
bytecode verifier
Car.class
interpreter
runtime
hardware
7
Columbia University JETT
3/28/2003
JVM
JVM specification provides concrete
definitions for implementation of:






8
Instruction set
Register set
Class file format
Runtime stack
Garbage collecting heap
Memory area
Columbia University JETT
3/28/2003
SO….
Java uses a mix of compiler and
interpreter
The majority of type checking is done
when the code is compiled.
9
Columbia University JETT
3/28/2003
Garbage Collection
Allocated memory does not need to
be deallocated (delete).
Java provides tracks memory
allocation
Garbage Collection
checks and frees memory no longer
needed
 done automatically

10
Columbia University JETT
3/28/2003
Java promotes
Object-oriented programming
11
Columbia University JETT
3/28/2003
Object-Oriented
Programming
Each object has
its own memory
 belongs to a class (instance of a
class)

Class defines
attributes (defines state)
 behavior (methods)

12
Columbia University JETT
3/28/2003
BlueJ
tool for teaching object-oriented
programming and Java without much
overhead (task overloading for
student)
development environment designed at
Monash University, Australia.
13
Columbia University JETT
3/28/2003
Shapes….
BlueJExamples
BlueJ Time
Activity_01 (#1,2)
BlueJ can be downloaded FREE
Some materials and examples are from
Objects First with Java
by Barnes and Kölling
goto BlueJ
14
Columbia University JETT
3/28/2003
Shapes
…summary after
experimentation
What we see in this BlueJ project:
 ClassesCircle, Square, Triangle, Canvas
 creation of an object : call to Constructor
 invoking (calling) methods
 passing parameters
 method signatures
 data types : int, String, and boolean
 multiple instances of the same class
 changing the state of the object
15
Columbia University JETT
3/28/2003
Picture…Summary after
Experimentation
How many objects?
How many constructors?
What happened when you
commented out the code for the
constructor?
16
Columbia University JETT
3/28/2003
Picture
"Construct" creates an instance of the
Picture class
a Picture

consists of 5 objects
• 2 squares, 1 triangle, 1 circle, 1 canvas

17
Objects can create other objects!
Columbia University JETT
3/28/2003
Constructors
If no constructor is included in the class,
Java provides one.

if values are not set, default values for
instance variables of a class are:
• 0 for int
• 0.0 for double
• null for objects
• false for boolean
If a constructor is included in the class, all
bets are off (no default constructor is
provided)!
18
Columbia University JETT
3/28/2003
Comments
BlueJ : Interface
JavaDoc creates this document

19
(more on this later).
Columbia University JETT
3/28/2003
Comments, White space
Comments
// comment on one line
 /*……*/ comment over several lines
 /** ……*/ javadoc comment

White space

20
ignored; use white space for clarity of
code
Columbia University JETT
3/28/2003
Javadoc
some keywords :
@author*
@version*
@param*
@return*
@throws*
21
Columbia University JETT
3/28/2003
JAVA
Language Basics
22
Columbia University JETT
3/28/2003
Some basics:
Primitive types

logical :
boolean
• no casts between boolean and
int
texual:
 integral:
long
 floating:

23
char
byte, short, int,
double, float
Columbia University JETT
3/28/2003
(not part of AP Subset)
Integral data types
byte
 short
 int
 long
8 bits
16 bits
32 bits
64 bits

-27 to 27 – 1
-215 to 215 – 1
-231 to 231 – 1
-263 to 263 – 1
default is int
24
Columbia University JETT
3/28/2003
(not part of AP Subset)
Floating Point data types
float
 double

32 bits
64 bits
default is double
25
Columbia University JETT
3/28/2003
Everything else
Everything that is not a primitive type is a
reference type
A reference variable contains a reference
to an object
Circle sun = new Circle();




26
allocates memory for this new object
initializes attributes
sun
executes constructor
assigns reference to reference variable
Columbia University JETT
3/28/2003
Order of Precedence
Separators
.
 []
 ()
;
,

27
IMPORTANT
Columbia University JETT
3/28/2003
Operator Order of Precedence
(associativity – operators)
R to L
++ -- + - ~ !
L to R
* / %
L to R
+ -
L to R
<< >> >>>
L to R
< > <= >= instanceof
L to R
==
L to R
&
L to R
^
L to R
|
L to R
&&
L to R
||
R to L
?:
R to L
=
28
!=
*= /=
%=
+=
-=
Columbia University JETT
3/28/2003
Conditionals – branching
if –else if statements
if (boolean expression){
statement or block;
}
if (boolean expression){
statement or block;
}
else if (boolean expression) {
statement or block;
}
else{
statement or block;
}
29
Columbia University JETT
3/28/2003
Conditionals – branching
switch statements (not part of AP subset)
switch (expression){
case constant2:
statements;
break
case constant3:
statements;
break;
default:
statements;
break;
}
note: expression must be assignment compatible with int.
(byte, char, short are OK;
double, long, Strings not OK)
30
Columbia University JETT
3/28/2003
Looping
for(startExp; booleanExp; endExp)
{
statement or block;
}
while(boolean expression){
statement or block;
}
31
Columbia University JETT
3/28/2003
Teaching Tip:
Company Rules:
Have a permanent place in your
classroom with your Company Rules
listed.
 That way everyone knows what is
expected and no one will be
needlessly fired!

32
Columbia University JETT
3/28/2003
Java supports
short circuit evaluation
if ((n != 0) && (x < 1/n))
evaluates first expression
if OK then evaluates second
expression
33
Columbia University JETT
3/28/2003
Looping
do{
statement or block;
} while(boolean expression)
(not part of AP subset)
34
Columbia University JETT
3/28/2003
Looping
When do you use each loop?



35
for
while
do
Columbia University JETT
3/28/2003
Special Loop Flow Control-return
is part of AP subset
36
Columbia University JETT
3/28/2003
More with BlueJ
More with BlueJ – TicketMachines

NaiveTicketMachine
• attributes (fields)
• private int price; //price of ticket
• private int balance; //how much $ put in for ticket
• private int total; //total $ in machine
• Constructor
• Methods
•
•
•
•
37
insertMoney
printTicket
getBalance
getPrice
Columbia University JETT
3/28/2003
Naïve TicketMachine
Is there a default constructor?
How many constructors are there?
What do we mean by a "method signature?"
What methods are the accessors?
What methods are the modifiers (mutators)?
What's wrong with this ticket machine?
What enhancements can we make?
38
Columbia University JETT
3/28/2003
Scope of variables
Fields (attributes)

private
Formal parameters

initialized by actual parameters
Local variables
39
Columbia University JETT
3/28/2003
arrays
Part of AP CS A subset
one- and two- dimensional arrays

more on two-dimensional arrays later
(AB only)
arrays of primitive types
arrays of objects
40
Columbia University JETT
3/28/2003
arrays
Declaring an array variable is similar to
declaring other variables.
int[] a;
 double[] b;
 String[] c;

//array of ints;
//array of doubles;
//array of Strings;
Does not cause Java to allocate memory
(space).
41
Columbia University JETT
3/28/2003
arrays
To allocate memory (space) for your array.
final int MAXNUM = 5;
int [] a = new int [10];
double[] b = new double[20];
String[] c = new String[MAXNUM];
42
Columbia University JETT
3/28/2003
array length
If a is an array variable,
a.length represents the length of
the array a.
43
Columbia University JETT
3/28/2003
array processing
assume an array of ints
rate each of the following on a scale of 1 – 5 where 5 is very
hard to implement :








fill: value of array element filled with index of array
element
find largest value in array
find smallest value in array
find sum of values in array
search for item in array
sort items in an array
count occurrences of a value in an array
insert an item into a sorted array
44
Columbia University JETT
3/28/2003
Initializing arrays
Initialization of named arrays:
int[] a = {1,2,3};
Declaration without initialization gets
default values.
int[] a = new int[10];
filled with 0s.
45
Columbia University JETT
3/28/2003
LabArrayClass class
attributes are private
•
•
•
•
•

private String instructor;
private String room;
private String timeAndDay;
private Student[] students;
private int currentNumberOfStudents
methods are public (for now)
• Constructors
• Accessors
• Mutators
46
Columbia University JETT
3/28/2003
Student[] students;
private field

each LabArrayClass object has this
array of Students
What does this mean?
 What is an array?

47
Columbia University JETT
3/28/2003
A look at the constructor
public LabArrayClass(int maxNumberOfStudents)
{
instructor = "unknown";
room = "unknown";
timeAndDay = "unknown";
students = new Student[maxNumberOfStudents];
currentNumberOfStudents=0;
}
An array is a fixed-length collection of values of the same type.
Access array elements by indexing : students[3]
First element in the array has index 0.
48
Columbia University JETT
3/28/2003
Comparing array elements
Comparing elements in arrays of
primitives is not a problem.

comparison operators are defined.
What about arrays of Strings?

49
Strings are Objects
Columbia University JETT
3/28/2003
Suppose we wanted to
"search?"
We need to search for a String, key…

50
Look at each element in the array of
Strings and check to see if it contains
the same characters as key.
Columbia University JETT
3/28/2003
Comparing Strings
Strings are objects. Do not use == to
compare the values of two strings.
To test if two Objects have the same data,
we use the equals method. (API)
Every Java Object supports the equals
method but its implementation may be
different (more on this later).
if(aString.equals(bString))…
51
Columbia University JETT
3/28/2003
LabArrayClass
A peek at the code……
How can we search for a student by
ID?
How can we remove a student who
has a specified ID?
How can we sort the students
according to ID numbers?
Work with LabArrayClass project
52
Columbia University JETT
3/28/2003
What is an ArrayList???
indexed collection of objects
grows automatically
AP CS A subset methods :
 int size()
 boolean add (Object x)
 Object get(int index)
 Object set(int index, Object x)
 void add(int index,Object x)
 Object remove(int index)
A look at the API !

53
http://www.cs.duke.edu/csed/ap/subset/doc/
Columbia University JETT
3/28/2003
Constructor
public LabClass(int
maxNumberOfStudents)
{
instructor = "unknown";
room = "unknown";
timeAndDay = "unknown";
students = new ArrayList();
capacity =
maxNumberOfStudents;
}
54
Columbia University JETT
3/28/2003
…Recall Java A subset
…Recall API
public void enrolStudent(Student newStudent)
{
if(students.size() == capacity) {
System.out.println("The class is full,
but
the student has been added.");
}
students.add(newStudent);
}
55
Columbia University JETT
3/28/2003
Setters
public void setRoom(String roomNumber)
{
room = roomNumber;
}
public void setTime(String timeAndDayString)
{
timeAndDay = timeAndDayString;
}
public void setInstructor(String instructorName)
{
instructor = instructorName;
}
56
Columbia University JETT
3/28/2003
ArrayList method
public int
numberOfStudents()
{
return students.size();
}
57
Columbia University JETT
3/28/2003
More about objects and
ArrayList
public void printList()
{
…
int i;
for(i = 0; i < students.size(); i++){
Student theStudent = (Student)students.get(i);
theStudent.print();
}
…
}
58
Columbia University JETT
3/28/2003
Activity_01
Complete work!!!
Projectpartners

design
• discuss
• commit
• defend
Talk to your neighbors!
Have FUN !!!
59
Columbia University JETT
3/28/2003