1 cs2136: paradigms of computation class 10: java: introduction and/or review copyright 2001, 2002,...
TRANSCRIPT
1
CS2136:Paradigms of Computation
Class 10:Java:
Introduction and/or Review
Copyright 2001, 2002, 2003 Michael J. Ciaraldi and David Finkel
2
Java Programs
Two types of programs: An application runs stand-alone. An applet runs inside a Web browser
Or the utility called “appletviewer.”
Few differences
3
Creating and RunningJava Applications
Create a source file called something.java
Submit it to the compiler javac something.java
This produces an object file called something.class
To run, type [Note: No suffix!] java something
4
A Simple Sample Java Program(Eckel, 1st edition, Chap. 2)
//: Property.javaimport java.util.*;/** The first Thinking in Java example program. Lists system information on current machine. * @author Bruce Eckel * @author http://www.BruceEckel.com * @version 1.0 */public class Property { /** Sole entry point to class & application * @param args array of string arguments * @return No return value * @exception exceptions No exceptions thrown */ public static void main(String[] args) { System.out.println(new Date()); Properties p = System.getProperties(); p.list(System.out); System.out.println("--- Memory Usage:"); Runtime rt = Runtime.getRuntime(); System.out.println("Total Memory = “ + rt.totalMemory() + " Free Memory = “ +
rt.freeMemory()); }}
5
Java Syntax
Semicolon is the statement terminator, not the statement separator.
Comments can be either: Single line, starting with // Block comments, bracketed by /* … */
Within block comments, lines starting with @ are part of javadoc.
Program blocks enclosed by { … }Case is iMpOrTaNt.
6
Structure of the Samplefile Property.java
import java.util.*; We will use the utilitypackage. Could get asingle class instead.
public class Property { Define a class called Property,
visible to all. Must havesame name as file.
…
7
Structure of the Samplefile Property.java II
public static void main(String[] args) {…}For any application, the method
called main is called at start.This method:
returns nothing (void) is visible to all (public) always exists (static)
Command-line arguments in args[].
8
Structure of the Samplefile Property.java III
System.out.println(new Date());Create a new object of type Date, with
default value (current date and time).Within the class System is an object
out, which is the standard output; this has a method called println().
When you pass an argument to println(), it gets printed, then we move to a new line.
9
Structure of the Samplefile Property.java IV
What happens to the newly-created object of type Date? It gets passed to the println(), then it is
not saved anywhere, so it gets garbage collected.
10
Structure of the Samplefile Property.java IV
Properties p = System.getProperties();p.list(System.out);We create a variable called p which
can hold a reference to an object of class Properties.
We invoke the getProperties() method to create an object, and store its reference (handle) in p.
We invoke the list() method on p, which asks it to print itself.
11
Structure of the Samplefile Property.java V
Runtime rt = Runtime.getRuntime();System.out.println(“Total Memory = “
+ rt.totalMemory() + “ Free Memory = “ + rt.freeMemory());
We invoke getRuntime() to get a reference to the current runtime environment (not a copy).
We concatenate with some text to print some of the runtime values.
12
Access Methods
Usually an object has attributes (a.k.a. data fields, a.k.a. instance variables), but you cannot access them directly.
Instead, there are access methods.To see some, check out the API docs at
http://www.cs.wpi.edu/~ciaraldi/jdk1.3/docs/api/
Remember, you don’t know how the data is represented internally.
13
Access Methods Example:The Date Class
long getTime() Returns the number of milliseconds since
January 1, 1970, 00:00:00 GMT represented by this Date object.
String toString() Converts this Date object to a String of
the form: dow mon dd hh:mm:ss zzz yyyy E.g. Tue Mar 21 08:11:13 EST 2000 Note: println() calls toString()
automatically when given a non-string object.
14
Access Methods Example:The Date Class II
void setTime(long time) Sets this Date object to represent a
point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.
15
Allocating an Object
(Almost) every class has a constructor function. We’ll see how to define them later. Constructor has same name as class. Triggered by keyword new.
A constructor might take a variable number of parameters. Including none at all!
16
Constructor Example:The Date ClassDate()
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
Date(long date) Allocates a Date object and initializes it
to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
17
A Warning
Some features of Java are
Deprecated!
18
The Garbage Collector
Really should be called the Recycler!It runs in the background.When it finds an object which is not
referred to, it destroys the object so the memory can be reused.
Can be invoked explicitly with System.gc() Will try its best.
19
Miscellaneous Java Features
20
Variables
Defined using this syntax: type name ;
Can also define and initialize in same statement: type name = value ;
Can hold either: Primitive Reference (“Handle”) to an object.
Not the object itself. Not the object itself.Not the object itself.
21
Variables
1.234
float x
1234
int y
String s
Date d
November 20, 2000.11:00 am
"Hello"String
Date
22
Java Primitive Types(Not Objects)
Integer (only signed) 8-bit byte 16-bit short 32-bit int 64-bit long
Real 32-bit float 64-bit double
char (16 bit) Uses Unicode
boolean Values:
truefalse
23
Assignment
For primitives, = copies the value.For objects, = copies the reference
(handle) to the object.foo a = new foo();
foo b;b = a;
Now, b and a refer to the same object.A very important difference!
24
Assignment
Foo b;
Foo a = new Foo();
b = a;
Foo b
Foo b
Foo a
some Fooish data
Foo
Foo b
Foo a some Fooish dataFoo
After Line 1
After Line 2
After Line 3
25
Kinds of Variables
Instance Variables Defined as part of a class. Allocated as each object is instantiated. Destroyed with the object.
Local Variables Defined as part of a method (within a
class). Allocated when the method is invoked. Destroyed when the method exits.
26
Math Operators
Same as C or C++
27
Relational OperatorsUnlike C or C++, return boolean, not
integer.Use with boolean:
== !=Use with all other primitive types:
< > <= >= == !=Use with objects:
== != Test for same object, not equal value. Can test value with equals(), if
available.
28
Other Operators
BitwiseShiftsString concatenation
+
29
Flow Control
if-elsewhiledo-whilefor
The test must be booleanswitchreturn
30
Next Time
JavadocClasses
Data Methods Encapsulation