Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
1Lecture 2
Quick Review of Java Concepts
Paul Chew
CS 211 – Fall 2005
2
Announcements
„ Assignment 1 is online and 
is due Friday at 5pm
„ Next topic: Induction
3
Overview
„ Goals
z Review some of the key 
constructs of Java 
(especially those useful for 
Assignment 1)
z Discuss some of
the new features of J2SE 
5.0
„ Contents
z Classes & Objects (brief 
review)
z Reference Types vs. 
Primitive Types
z Arrays (brief review)
z Array vs. ArrayList vs. 
HashMap
z Command Line Interface
z New features of J2SE 5.0 
(generics, enhanced for, 
enum)
z Debugging and 
experimentation
4
Classes & Objects (brief review)
„ A program usually consists 
of several classes
„ Each class has some fields 
and some methods
„ A typical class declaration:
class ClassName {
field declarations;
method(parameters) {
local variable declarations;
body;
}
method(parameters) {
local variable declarations;
body;
}
}
5
The Main Method
„ To run as an application, a class must have a main 
method, which is always declared as
public static void main (String[ ] args) {
... body ...
}
„ There are other specific methods needed for a 
class to run as, for instance, an applet or a thread
6
Instance Fields vs. Static Fields
„ Instance fields
z Belong to individual 
instances of a class
z Each instance of the 
class has a different 
version of the field
„ Static fields
z Belong to the entire 
class 
z A single static field is 
shared by all instances 
of the class
z Are declared using 
keyword "static“
27
Static vs. Instance Example
class Widget {
static int nextSerialNumber = 10000;
int serialNumber;
Widget() {serialNumber = nextSerialNumber++;}
Widget(int sn) {serialNumber = sn;}
public static void main(String[] args) {
Widget a = new Widget();
Widget b = new Widget();
Widget c = new Widget();
Widget d = new Widget(42);
System.out.println(a.serialNumber);
System.out.println(b.serialNumber);
System.out.println(c.serialNumber);
System.out.println(d.serialNumber);
}        
}
8
Instance Methods vs. Static Methods
„ Instance methods are called
z Via
instance.method(args)
z Or, when called from 
within an instance method 
via
method(args)
„ Static methods 
z Cannot refer to instance 
fields or instance methods 
(except via qualified name)
z Can be called even if no 
objects of the class have 
been created
„ Static methods are called
z Via
Classname.method(args)
z Or, when called from 
within any method in same 
class via
method(args)
9
Parameters and Local Variables
„ Parameters and local variables exist only while the 
method is running
z Use parameters to pass input data to a method
z Use local variables for temporary data used in a 
method
„ Use fields for persistent data or data shared by 
several methods
10
Names
„ Reference fields, methods in own class by unqualified name
serialNumber
nextSerialNumber
„ Reference static fields in another class by qualified name
Widget.nextSerialNumber
„ Reference instance fields with qualified name
a.serialNumber
„ Example
System.out.println(a.serialNumber)
™ out is a static field in class System
™ The value of out is an instance of a class that has a method
println(int)
„ If an object has to refer to itself, use this
11
Overloading of Methods
„ A single class can have several methods of the 
same name as long as they have different 
signatures
„ Look at String.valueOf(...) in Java API
z There are 9 of them, one for each of 9 different 
argument types
z Think of argument types as part of the name of 
the method
12
The Class Hierarchy
„ The class hierarchy is a 
tree 
z Object is at the root 
(top)
z E.g., String and
StringBuilder are 
subclasses of Object
„ The hierarchy is a tree 
because 
z Each class has at most 
one superclass
z Each class can have 
zero or more 
subclasses
„ Within a class, methods 
and fields of its superclass 
are available
z But must use super for 
access to overridden
methods
313
Primitive Types vs. Reference Types
„ Primitive types
z int, long, float, byte, 
char, boolean, ...
z Take a single word or 2 
words of storage
z Are not objects in the 
Java sense
z A variable of that type 
contains the actual data
„ Reference types
z Arrays and objects (e.g. 
String, StringBuffer, 
HashSet)
z Usually take more 
storage
z A variable of that type 
contains a pointer to the 
actual data
z null is a reference type
14
== vs. equals( )
„ Use == for primitive types
„ For reference types (e.g., 
Strings), use == only if you 
mean actual identity of the 
two objects 
z This is ALMOST 
NEVER what you want!
„ E.g., can have two different 
strings, both with value 
"hello“
z Use 
x.equals("hello")
z Not 
x == "hello".
15
Arrays
„ Arrays are reference types
„ Array elements can be 
reference types or primitive 
types
z E.g., int[] or String[]
„ If a is an array, a.length is 
its length
„ Its elements are a[0], a[1], 
..., a[a.length - 1]
„ Multidimensional arrays are 
really arrays of arrays
z E.g., int[][] is an array of 
integer arrays
z Multidimensional arrays 
can be ragged (i.e., all 
the arrays in the 2nd 
dimension need not be 
the same length)
16
Ragged Multidimensional Array
class MultiArray {
static int[ ][ ][ ] a = new int[2][3][ ];
public static void main(String[ ] args) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = new int[i+j];
}
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.println(a[i][j].length);
}
}
}
}
> java MultiArray
0
1
2
1
2
3
17
Array vs. ArrayList vs. HashMap
„ Three extremely useful 
constructs (see Java API)
„ Array
z Storage is allocated 
when array created; 
cannot change
„ ArrayList (in java.util)
z An "extensible" array 
z Can append or insert 
elements, access ith
element, reset to 0 
length
z Can get an iteration of 
the elements
„ HashMap (in java.util)
z Save data indexed by 
keys
z Can lookup data by its 
key
z Can get an iteration of 
the keys or the values
„ Older versions (retrofitted 
to be part of Java 
Collections)
z Vector (≈ ArrayList)
z Hashtable (≈ HashMap)
18
HashMap Example
„ Create a HashMap of numbers, using the names of the numbers 
as keys:
HashMap numbers = new HashMap();
numbers.put("one", new Integer(1));
numbers.put("two", new Integer(2));
numbers.put("three", new Integer(3));
To retrieve a number:
Integer n = (Integer)numbers.get("two");
if (n != null) System.out.println("two = " + n);
„ Caveat: returns null if does not contain the key
- can use numbers.containsKey(key) to check this
419
Command Line Interface
„ Command line arguments are 
contained in the String array parameter 
of the main method
class CmdLineArgs {
public static void main(String[] args) {
System.out.println(args.length);
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}
„ > java Foo
0
> java Foo asdf zxcv ss
3
asdf
zxcv
ss
> java Foo hello world
2
hello
world
„ Try your programs in a 
command window, not just 
in DrJava
z That's how we'll be 
testing them  
z Behavior may be a little 
different
20
New Feature of J2SE 5.0: Generics
„ Old
HashMap h = new HashMap();
h.put("one",new Integer(1));
Integer s = (Integer)h.get("one");
„ New
HashMap h = new HashMap();
h.put("one",new Integer(1));
Integer s = h.get("one");
„ No longer necessary to do a class cast each time you take an 
element out of the HashMap
21
New Feature of J2SE 5.0: Enhanced for
„ Old
String[] a = {"hello","world"};
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
„ New
String[ ] a = {"hello","world"};
for (String s : a) {
System.out.println(s);
}
„ Also works generics (using HashMap h from previous example):
for (String key : h.keySet()) {
System.out.println(key);
}
22
New Feature of J2SE 5.0: Enum
„ Old
class Enum1 {
public static final int WINTER = 0;
public static final int SPRING = 1;
public static final int SUMMER = 2;
public static final int FALL   = 3;
public static void main(String[ ] args) {      
System.out.println(WINTER);
}
}
„ New
enum Season { WINTER, SPRING, SUMMER, FALL }
class Enum2 {
public static void main(String[ ] args) {      
System.out.println(Season.WINTER);
}
}
„ The first program prints 0; the second prints WINTER
23
Experimentation and Debugging 
„ Don't be afraid to 
experiment if you don't 
know how things work
z An IDE (e.g., DrJava) 
makes this easy by 
providing an 
Interactions Panel
„ Debugging
z Isolate the bug using, 
for example, print 
statements combined 
with binary search
z An IDE makes this easy 
by providing a 
Debugging Mode
™ Can step through the 
program while 
watching chosen 
variables