HELP! * GREY=local Full HTML
for
LOCAL foilset Basic Lectures on Java Language Applets Graphics Networking
Given by Geoffrey C. Fox at Trip to China and Icase Tutorial on July
12-28 and June 10-13 96. Foils prepared July 10 1996
Abstract * Foil Index for this
file
See also color IMAGE
- Overview including History and alpha versus production issues
- Comparison of Java and Javascript
- Overall Java Philosophy and Features including security etc.
- Java Programming Language
- Object Oriented and Class Structure
- Exceptions
- Applet Programming and Threads
- Abstract Windowing Toolkit
- Networking and I/O; native classes
- Futures and HPCC Implications
- Hot Java is not discussed as current version not evaluated
Table of Contents for full HTML of Basic Lectures on Java Language
Applets Graphics Networking
1 Java Tutorial - June 1996
Java Language , Applets ,
Graphics and Abstract Windows Toolkit
Networking etc.
http://www.npac.syr.edu/users/gcf/icasejavajune96/index.html
http://www.npac.syr.edu/projects/cps616spring96/index.html
given at ICASE June 10-13 1996
Trip to China July 12-28 1996
2 Abstract of Java Tutorial
3 Overview and History of Java Development
4 What are Java and HotJava in a NutShell?
5 HotJava Story 1994-1996
6 HotJava Alpha Capabilities
7 HotJava's Future 1996- ?
8 Overview -- Java and the World Wide Web
9 Overview -- What are Java applets in detail?
10 Running a Java Applet
11 History of Java Language and Team
12 History of Java Language and Team (contd)
13 JDK 1.0 -- The Real Java Development
Kit!
14 Java Beta Books -- I
15 Java Beta Books -- II
16 Java Beta Books -- III
17 Java vs. JavaScript
18 Comparison of Java and JavaScript --
I
19 Comparison of Java and JavaScript --
II
20 Overall Java Philosophy and Features
21 Some Key Java Features
22 Java Features -- It's Simple and Familiar!
23 Java Features -- It's Object-oriented
24 Java Features -- It's Architecture-Neutral
25 Java Features -- It's Portable
26 Java Features -- It's Somewhat Interpreted
27 Java Features -- It's Distributed
28 Java Features -- It's Robust
29 Java Features -- It's (Hopefully) Secure
30 Java Features -- High Performance
31 Java Features -- It's Multithreaded
32 Java Features -- It's Dynamic
33 Sun's Comparison of Language Features
34 The Java Programming Language
35 Java Language Discussion -- Table of
Contents
36 Program structure and the simplest examples
37 Java Language -- Program Structure
38 Java Language -- Lexical Issues I
39 Java Language -- Lexical Issues II
40 Java in Practice --
Applets and Applications
Use from HTML
41 Applications Versus Applets - I
42 Applications Versus Applets - II
43 Applet Tag: Calling Applets from HTML
- I
44 Applet Tag: Calling Applets from HTML
- II
45 <param> Tags and Applets
46 Hello World Applet from Sun Tutorial
Getting Started
47 Hello World Application from Sun Tutorial
Getting Started
48 Java Language Basics
An example using arrays is found at the end of the Applet Basics section
of JavaStroll
49 Java Language -- Variable/Expression
Types
50 Java Language -- Types: Array
51 Java Language -- More on Arrays
52 Java Language -- Expressions
53 Java Language -- Control Flow I
54 Java Language -- Control Flow II --
continue
55 Java Language -- Control Flow III --
break and for loop
56 Java Language -- Control Flow IV --
break and switch
57 Java Language -- Control Flow V -- continue
and switch
58 The Java Object Model: Classes, Instances
and Methods
59 The Java Object Model Overview
60 Date Application from Sun Tutorial
Anatomy of an Application
61 Counting Application from Sun Tutorial
Nuts and Bolts of Java
62 Java Language -- Overview of Classes
63 Instantiating an Object from its Class
64 Constructors of Objects
65 Class Finalizers
66 Java Language -- Types of Classes -
I
67 Java Language -- Types of Classes -
II
68 Java Language -- Methods
69 The Java Object Model: Inheritance and
the Class Hierarchy
70 Use of Methods Defined in Parent
71 Use of Methods Defined in Parent but
overridden in child class
72 Comments on Casting
73 Review of the Array Class
74 Array - A Pseudo Class!
75 By value and By reference
76 Comments on Overloading and Overriding
in Classes
77 Object-Oriented
Programming Examples:
Basic Class Operations
78 A little more complicated Paint Method
for Applets
79 Some More Methods for mPoint
80 Inheritance or Subclassing
81 Abstract Methods
and Classes
Interfaces
(classes without implementation)
82 Comments on abstract Methods and Classes
83 Java Language -- Interfaces - Overview
84 Cars as an Examples of Interfaces/ Multiple
Inheritance
85 Picture of Interfaces and Classes for
Cars and their Manufacture
86 Java Language -- Interface Example --
Implementing Storable
87 Interfaces can be used as Classes in
type specification
88 Further Features of Interfaces
89 More on Interfaces -- Why use them
90 More on Interfaces -- Real Examples
91 Packages in Java
92 Overview of Packages and Directory Structure
93 Using packages
94 Java System Packages
95 Somewhat more Detail on Applets and
Graphics
96 The java.awt.Graphics Class
97 The java.awt.Font and FontMetrics Classes
98 The java.awt.Color Classes
99 Some Basic Methods for Applets -- I
100 Some Basic Methods for Applets --
II
101 A Simple Useful Applet from Sun for
Animation
102 Sun's Animator.class Applet
103 Details of Using the Sun animator
Applet --I
104 Details of Using the Sun animator
Applet --II
105 Threads are part of the Java Language!
106 Initial Remarks on Threads
107 Threads as Discussed in Sun's Tutorial
108 Thread Execution and Concurrency
109 The Life of a Thread
110 Sun's Digital Clock Applet to Illustrate
Threads -- I
111 Sun's Digital Clock Applet to Illustrate
Threads -- II
112 Synchronized Method and Blocks
113 Sun's Synchronized Block Example
114 Threads and Synchronization - I
115 Threads and Synchronization - wait()
116 Threads and Synchronization - notify()
117 Threads and Synchronization - Example
118 Useful Basic Java Classes
119 The Overarching Object Class
120 Determining and Testing Class of Object
121 java.lang.Object Wrappers
122 The java.lang.Math class
123 The Date class
124 The String class
125 More on Strings, and the StringBuffer
class
126 ReverseString Class from Sun Tutorial
127 The Vector class
128 Methods for Vectors
129 The Hashtable class
130 More on the Java Language: Exceptions
131 Java Language -- Handling Errors Using
Exceptions
132 Basic Structure of Exception Handling
in Nested Calls
133 Examples of Exception Hierarchy
134 finally illustrated by Handling Exceptions
in Closing a File
135 Classes of Exceptions
136 Exceptions in Applets
137 Summary of Object-Oriented Concepts
138 Summary of Object-Oriented Concepts
- I
139 Summary of Object-Oriented Concepts
- II
140 Back to Details on Graphics and Animation
141 Graphics is Event-Driven: paint method
142 Changing Graphics: repaint method
143 Some Graphics Methods
144 Getting Images the getImage Applet
Method
145 Drawing Images -- the drawImage Graphics
Method
146 Image Downloading -- imageObserver,
MediaTracker
147 Flickering in Applets and its Solution
148 The default Update(Graphics g) Method
149 ColorSwirl -- An Example from Teach
Yourself Java in 21 Days - I
150 ColorSwirl -- An Example from Teach
Yourself Java in 21 Days - run Method
151 ColorSwirl -- An Example from Teach
Yourself Java in 21 Days - paint and update
152 Double Buffering to Reduce Flicker
- I
153 Double Buffering to Reduce Flicker
- II
154 Event Handling
155 Events in the java.awt -- Mouse, Keyboard
Interaction - I
156 Events in the java.awt -- Mouse, Keyboard
Interaction - II
157 Abstract Windowing Toolkit (AWT):
Components such as buttons, textfields, etc.
158 Structure of the java.awt GUI Components
- I
159 Structure of the java.awt GUI Components
- II
160 Picture of the AWT Component Class
and its inheritance
161 Some Simple AWT Components -- label,button
162 AWT Components -- Checkbox
163 AWT Components -- Radio Buttons ,
CheckboxGroup
164 Some Further AWT Components -- typical
subunits of panels
165 Some Further AWT Components -- Canvas,
Window - I
166 Some Further AWT Components -- Canvas,
Window - II
167 Abstract Windowing Toolkit (AWT):
Actions in response to Mouse and Keyboard etc.
168 Actions associated with Components
in AWT - I
169 Actions associated with Components
in AWT - II
170 Abstract Windowing Toolkit (AWT):
Layouts
171 Layout of Components in a Panel
172 Description and Example of BorderLayout
173 Brief Description of Four Other LayoutManager's
174 FlowLayouts in detail
175 Hierarchical use of LayoutManagers
176 Networking, Web Access and I/O
177 Networking, Web Access and I/O in
Java
178 Security Concerns for Applets
179 Table for Java file and network access
180 Accessing URL's in Java -- URL, showDocument
181 Accessing URL's in Java -- URLConnection
182 Input/Output in Java -- InputStreams
-- I
183 Input/Output in Java -- (Filter etc.)InputStreams
-- II
184 Accessing URL's in Java -- InputStreams
and URLConnections
185 Performance
and dreaming about the Future
186 Use of Native Classes to Speed Up
Execution
187 Comments on Native C Methods
188 HPCC and Java -- High Performance
HPjava -- I
189 HPCC and Java -- HPjava -- II
This table of Contents
Abstract
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 1 Java Tutorial - June 1996
Java Language , Applets ,
Graphics and Abstract Windows Toolkit
Networking etc.
http://www.npac.syr.edu/users/gcf/icasejavajune96/index.html
http://www.npac.syr.edu/projects/cps616spring96/index.html
given at ICASE June 10-13 1996
Trip to China July 12-28 1996
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Instructors: Geoffrey Fox ,Wojtek Furmanski,
- Nancy McCracken, Michael Chang, Meryem Ispirli
- Syracuse University
- 111 College Place
- Syracuse
- New York 13244-4100
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 2 Abstract of Java Tutorial
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Overview including History and alpha versus production issues
- Comparison of Java and Javascript
- Overall Java Philosophy and Features including security etc.
- Java Programming Language
- Object Oriented and Class Structure
- Exceptions
- Applet Programming and Threads
- Abstract Windowing Toolkit
- Networking and I/O; native classes
- Futures and HPCC Implications
- Hot Java is not discussed as current version not evaluated
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 3 Overview and History of Java Development
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 4 What are Java and HotJava in a NutShell?
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- What is Java?
- A simple, object oriented, distributed, interpreted, robust, safe,
architechture neutral, portable, high performance, multithreaded, dynamic
language.
- What is HotJava?
- Web browser written entirely in Java-based language
- Toolkit for building Web-aware applications
- Alpha version received a lot of attention from april to november
1995 but the latest version only came in april 1996 and has not been evaluated
in detail by NPAC
- It is clearly less sophisticated than Netscape 2.0/3.0 at the moment!
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 5 HotJava 的历史1994-1996
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- HotJava alpha3 (1994-5)
- 基于Java的概念检验
- 动态 Web 的要旨 (applets)
- 缺少:
- 真正的安全性
- A 一种Well-defined Applet API
- HotJava 1.0 (1996)
- Completely new implementation
- Modular architecture
- Customizable without source code
- Multi-threaded for higher interactivity
- State of the art: HTML 2.0+, applets, installable handlers.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 6 HotJava Alpha Capabilities
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Alpha release of Java/Hotjava included:
- C source code for the Java interpreter (Virtual Machine)
- Java foundation classes (base language support, I/O, networking,
Internet protocols, windowing, graphics, utilities)
- HotJava browser package used to build HotJava in Java. Includes
'hotjava' class which 'is' HotJava application.
- In Short, Alpha Java/HotJava was a complete software release of
all system components, free for research and subject to ($125K) licence
for business use.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 7 HotJava's Future 1996- ?
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- HotJava toolkit (1996-): class libraries for building web-aware
applications i.e. The "Browser" class
- HTML parsing
- Document editing, formating, presentation (MVC-based)
- Web navigation
- Communications
- Natural Use of HotJava is for applications where it is critical
to customize User Interface to a greater degree than Netscape allows
- Netscape hopes you will use JavaScript to customize a core browser
supplied by Netscape
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 8 Overview -- Java and the World Wide Web
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- Browsers (HotJava, Netscape 2.0/3.0 ..) supporting Java allow arbitrarily
sophisticated dynamic multimedia applications inserts called Applets, written
in Java, to be embedded in the regular HTML pages and activated on each
exposure of a given page.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 9 Overview -- What are Java applets in detail?
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Applet constructs are implemented in terms of a
- special HTML tag: <APPLET codebase="URL directory path"
code="Java class file name" width=".." height=".."
>
- where the URL and class file name points to a chunk of server side
software that is to be downloaded and executed at the client side on each
presentation of a page containing this applet which executes in window
specified in size by width and height in picxels.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 10 Running a Java Applet
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Steps to running a Java Applet:
- 1. Write an HTML file that refers to the applet using the APPLET
tag, described in later pages.
- 2. If necessary, write the Java code and compile into class files
- 3. Visit the HTML file with a web browser or with appletviewer.
- Using a Browser
- With a Java-enabled web browser, such as Netscape 2.0/3.0 or HotJava,
you run an applet by "surfing" to a web page containing the APPLET
tag.
- Using appletviewer
- When doing development, use appletviewer to run applets by specifying
the HTML file on the command line:
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 11 History of Java Language and Team
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Starts in 1991 by Project Green --- a group in Sun that detaches
from the main campus as a semi-autonomous task force focused on operating
software for consumer electronic devices such as smart set-top boxes
- Gosling (creator of Sun NeWS which had major conceptual impact both
on current Java and Telescript models) realizes that C++ is not adequate
and initiates development of a new language Oak, later renamed as Java.
- A PDA (Personal Digital Assistant -- codename *7) based on Oak/Java
ready in 1993. Green Team incorporates as FirstPerson, Inc.
- *7 proposal to Time-Warner rejected in 1993. 3DO deal falls through
in 1994. FirstPerson, Inc. dissolves.
- Small group (~30 people, now Java Team) continues development and
decides to adapt Oak as a Web technology.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 12 History of Java Language and Team (contd)
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- An experimental web browser written in Java, called WebRunner and
later renamed as HotJava, ready in 1994.
- Java/HotJava published in April '95.
- Netscape licences Java in May '95 and builds Java into Netscape
2.0 -- This confuses ownership and open-ness of Java
- Beta JDK (Java Development Kit) published in summer/fall '95. It
is better software but lower functionality than Alpha.
- First alpha Java books appear in fall '95 such as a popular overview
by SAMS and technical book "Java!" by Tim Ritchey, edited by
New Riders.
- Dec 4 1995 Business Week cover story on "Software Revolution
--- The Web Changes Everything" exposes Java as a breakthrough force
in the expanding Web/Internet. Also points out that "Java as a business"
is yet to be defined.
- In next week, SGI IBM Adobe Macromedia and finally Microsoft adopt/license
Java. It appears that Java will be open and should be adopted by open Web
community
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 13 JDK 1.0 -- The Real Java Development Kit!
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Version 1.0 of JDK released January 96 by JavaSoft
- 1.0 JDK should be the Internet standard and so compatible with ongoing
Java implementations by all licensees, most notably Netscape. Beta/1.0
JDK includes:
- Java Compiler (.java to .class) for Sun Solaris and Windows NT/95
avaliable as .class itself (Javac written in Java) but no source
- Java source for the foundation classes (modified and incompatible
with alpha)
- appletviewer to run/preview applets
- tools for converting alpha applets to beta applets.
- Source code for the interpreter
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 14 Java Beta Books -- I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Hooked on Java, by Java developers Arthur van Hoff, Sami Shaio,
Orca Starbuck, Addison-Wesley, is the (first) serious (but still rather
high-level) book on beta Java. It contains example applets, but not much
on programming.
- Teach Yourself Java in 21 Days, by Laura Lemay and Charles L. Perkins,
Sams.net Publishing, is a "how-to" book at the intermediate programming
level. It concentrates on applets and windowing more than the object-oriented
part of the language.
- Java in a Nutshell, by David Flanagan, is the language reference
book in the familiar O'Reilly series.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 15 Java Beta Books -- II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- The Java Programming Language, by Ken Arnold and James Gosling,
Addison-Wesley, May 1996, has lots of details on the language basics for
intermediate and advanced programmers. It covers threads and i/o packages,
but not applets or windowing packages.
- All serious computer scientists should read to understand fundamentals
- Java Primer Plus, supercharging Web applications with the Java programming
language, by Paul M. Tyma, Gabriel Torok, and Troy Downing, Sams.net, doesn't
assume a lot of programming background, has chatty explanations and still
covers lots of programming detail.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 16 Java Beta Books -- III
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- There are four books in the Java Series from SunSoft Press, Prentice-Hall.
- instant Java*, by John A. Pew, contains multimedia and animation
applets for HTML authors. This is not a programming book.
- Java by example, by Jerry R. Jackson and Alan L. McClellan, covers
all key features with examples, but not as much detail about the language.
- just Java, by Peter van der Linden, for intermediate programmers,
gives good explanations of key features without going into every detail.
- core Java, by Gary Cornell and Cay S. Horstmann, offers detailed
coverage of the language and packages for advanced programmers.
- * this title is great, but what happened to "express Java",
"Percolating through Java", and "Java for Drips"?
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 17 Java vs. JavaScript
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 18 Comparison of Java and JavaScript -- I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Netscape renames Livescript as Javascript and this is an interesting
variant of Java which is fully interpreted -- use for overall customization
of client
- Use Java for detailed programming and JavaScript for overall integration
of client interface and system
- JavaScript: Interpreted by client and NOT compiled
- Java: Compiled on Server before execution on client
- Note both are reasonably "pure" C/C++ like languages and
do NOT have useful sh/awk text and system enhancements of Perl(5)
- JavaScript: Object based -- no classes or inheritance -- built in
extensible objects
- Java: Object-oriented. Programs consist of object classes with inheritance
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 19 Comparison of Java and JavaScript -- II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- JavaScript: Integrated with HTML as embedded ascii but of course
HTML looks rather irrelevant at times!
- Java: Applets distinct from HTML but invoked from HTML Pages
- JavaScript: do not declare variables' datatypes -- Loose typing
- Java: MUST declare variables' datatypes -- Strong typing
- JavaScript -- Dynamic Binding -- object references computed at runtime
- Java -- Static Binding -- object references must exist at compile
time
- Java and JavaScript are secure and cannot write to disk
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 20 Overall Java Philosophy and Features
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 21 Some Key Java Features
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Document The Java: A White Paper by Sun Microsystems -- October
1995 draft by James Gosling and Henry McGilton -- enumerates the following
main features of Java:
- Simple and Familiar
- Object-oriented
- Architecture-neutral
- Portable
- Somewhat Interpreted
- Distributed
- Robust
- Secure
- High performance
- Multi Threaded
- Dynamic
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 22 Java Features -- It's Simple and Familiar!
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Java omits several rarely used, poorly understood and confusing
features of C++ including operator overloading, multiple inheritance, pointers
and automatic type coercions.
- It adds automatic garbage collection which makes dynamic programming
easier in Java than in C or C++.
- It also adds 'Interface' construct, similar to Objective C concept,
which often compensates for the lack of multiple inheritance by allowing
method calling syntax to be "inherited".
- The resulting language is familiar as it looks like C++ but is simpler
and hence easier to program in.
- It also results in a much smaller kernel which is suitable for planned
Java ports to consumer electronic devices. Base (alpha) interpreter is
~40Kb, libraries and threads add additional 175Kb.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 23 Java Features -- It's Object-oriented
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Java model can be viewed as a C++ subset, with some dynamic elements
inherited from Objective-C (method overloading, garbage collection).
- Structures, Unions and Functions are absorbed into data and methods
of Java classes -- Java is Simple!
- The strength of Java object-oriented model is not is sophistication
but in simplicity and the extensive class library associated with the system
(some 250 public classes were released in both alpha and beta).
- Java class plays also a role of a communication atom in the Web
embedding model. Applet classes identify themselves by names in the HTML
applet tag. Applet downloads other classes, present in the applet source.
Hence, the Java class names play the role of addressing mode for the distributed
Java code database.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 24 Java Features -- It's Architecture-Neutral
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- C/C++ programming in a heterogeneous network environment requires
use and compatibility across several vendor platforms and the corresponding
compilers. This problem is solved in Java by designing platform-independent
binary representation called Java bytecode (or opcode).
- Java compiler (written in Java and platform-independent) reads Java
source and generates Java bytecode. These bytecodes are shipped to client
machines upon browser requests.
- Each client machine must run Java interpreter which performs runtime
execution of Java bytecodes. Java interpreter is written in POSIX compliant
ANSI C and needs to be ported to and conventionally compiled (once) on
each individual platform.
- Once the interpreter is ported, application developers don't need
to worry at all about platform specificity and differences between native
compilers.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 25 Java Features -- It's Portable
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Java language offers a uniform abstract (virtual) machine model
which is identical for all platforms.
- SUN owns the Java Virtual Machine (see online report) -- it is universal
while classes can be added by any user
- Unlike in C/C++ where various integers match the architecture of
a physical machine at hand, Java byte, char short, int and long are always
of the same size, equal to 8, 16, 16(unicode), 32 and 64 bits, respectively.
- No header files, preprocessors,#define etc.
- floating point is always IEEE 754
- Differences between vendor specific windowing environments (X Windows,
MS Windows, Macintosh) are removed in terms of the Abstract Windowing Toolkit
(AWT) metaphor.
- AWT is given by ~60 Java classes (alpha) which offer a universal
GUI programming model, portable between UNIX, PC and Mac, and translated
automatically to native windowing systems on individual platforms by Java
interpreters.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 26 Java Features -- It's Somewhat Interpreted
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Java represents a compromise between fully compiled (like C/C++)
and fully interpreted (like Smalltalk or Perl) models.
- Java "compiler" produces a binary bytecode output which
is portable and much smaller than the real binary for a specific machine
(Typical bytecode size is of order of the original source code, within
a factor of 2).
- Java "interpreter" executes this bytecode and is therefore
less dynamic than e.g. Perl interpreter (which performs an equivalent bytecode
construction internally and on-the-fly when reading the program source).
- In general, the compilation process is: a) time consuming and b)
platform specific. Hence, interpreters are built and used to facilitate
a) rapid prototyping and/or b) portability. Java model is focused on platform
independence but the development throughput is also reasonable since the
Java compiler is fast and generates compact bytecode output.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 27 Java Features -- It's Distributed
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Popular TCP/IP based protocols such as FTP or HTTP are supported
in terms of network protocol classes. This facilitates various forms of
distributed processing. New protocols (e.g. PVM etc.) can added and dynamically
installed.
- Distributed computing model of Java is mainly client-server, with
Java compiler preparing the opcodes at the server side, and Java interpreter
executing it at the client side.
- One can expect more dynamic uses of Java with Java threads on both
Server and Client side communicating with each other. This is illustrated
by Java based Collaboratory developed by Vishal Mehra as NPAC/Ece Master's
Thesis
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 28 Java Features -- It's Robust
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Java enforces compiler-time type checking and eliminates this way
some error prone constructs of C/C++.
- Pointer arithmetic is fully eliminated which allows e.g. for runtime
checking of array subscripts and enforces security of the Java model.
- Explicit declarations are always required, i.e. C-style implicit
declarations are abandoned. This allows the Java complier to perform early
error detection.
- Rapid prototyping in Java is less natural than in JavaScript,Lisp,
Tcl, Smalltalk or Perl, but the software quality assurance of Java is higher
than in these more dynamic and 'forgiving' languages.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 29 Java Features -- It's (Hopefully) Secure
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Java binaries are shipped across the network and executed on client
machines. Security is therefore a critical issue and strongly enforced
in Java.
- Java contains its own networking classes which are designed to be
secure
- Modifications of the C++ model such as eliminating pointer arithmetic
and coercion were dictated mainly by the security requirements.
- Most viruses are based on acquiring access to private/protected
sectors of computer memory which is impossible in Java.
- Java opcodes are executed at the client side by Java interpreter
which operates exclusively on the virtual memory. Hence, unless there are
security bugs in the Java interpreter itself, the model is safe and users
cannot create security holes by incorrectly or maliciously written applets.
- The byte codes sent across network are verified at the client which
prevents evil/corrupted classes from causing problems
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 30 Java Features -- High Performance
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Java interpreter performs on-the-fly runtime execution of the Java
bytecodes which results typically in a satisfactory performance.
- NOT true in initial software which is often 100 times slower than
C but this is expected to improve as true compilers are produced and general
software improves!
- Support for generating native machine code out of Java bytecodes,
viewed as intermediate compiler form, is also provided and useful for performance
demanding applications.
- The performance of the machine code, generated from Java bytecodes,
is comparable to that offered by typical C/C++ compilers on the same platform.
- Several of these concepts are in fact similar as in the OSF/ANDF
project. Using ANDF terminology, we would call Java compiler a 'producer',
and the machine code generator discussed here, an 'installer'. Default
Java working mode doesn't use installers but directly interprets the intermediate
form (this mode is supported in ANDF by GAI -- Generalized ANDF Interpreter).
- ANDF model is in principle applicable to all languages. Java/HotJava
system implements ANDF concepts for the Java language.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 31 Java Features -- It's Multithreaded
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Java model offers preemptive multithreading, implemented in terms
of the Thread class. Thread methods offer a set of synchronization primitives
based on monitor and conditional variable paradigm by C.A.R. Hoare. Java
threads inherit some features from the pioneering Cedar/Mesa System by
Xerox Park that gave birth to Macintosh and object-oriented programming.
- A typical use of Java multithreading in applet programming is to
have several independent but related simulations (e.g. various sorting
algorithms), running concurrently in an applet window. Multithreading is
also used internally by the HotJava browser to handle multiple document
dynamics.
- Another interesting application domain are multi-HotJava environments
to come such as collaboratory or gaming.
- Java threads don't have built-in point-to-point communication primitives.
Various thread communication environments can be provided by coupling the
thread and network protocol objects.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 32 Java Features -- It's Dynamic
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Java model is more dynamic than C++ and closer to Smalltalk or Perl.
- Subclasses don't need to to be recompiled after superclass implementation
is updated.
- Classes have runtime representation (implemented in terms of the
Class class) which allows one to look up type of a given object instance
at runtime (in C cannot know if pointer is to integer or browser!)
- C++ has "fragile superclass" problem where must recompile
children if change anything (method/instance variable) in a superclass
or referenced class -- Java resolves references at runtime and avoids this.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 33 Sun's Comparison of Language Features
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 34 The Java Programming Language
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- The original resource was the The Java Language Specification by
Sun Microsystems, Inc., March 1995 updated to October 1995 but superceded
by Gosling and Arnold Book
- Addison Wesley has several other fundamental Java books on Application
Programming Interface and Language Specification and Virtual Machine (by
end of summer 1996)
- http://www.javasoft.com web site has plenty of references including
- Tutorial: http://www.javasoft.com/books/Series/Tutorial/index.html
- Books:http://www.javasoft.com/java.sun.com/aboutJavaSoft/book-news.html
- Collection of Applets: http://www.gamelan.com
- Most of the books cited earlier have CDROM's with examples or the
JDK.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 35 Java Language Discussion -- Table of Contents
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Program Structure
- Lexical Issues
- Applet versus Application
- Variables and Expressions
- Types and Array
- Control Flow
- Object Model and Classes
- Methods
- Interfaces
- Exceptions
- This is followed by discussion of Implementation in terms of Applet
Programming, Threads, Graphics and the Abstract Windowing Toolkit, Networking
and I/O, Native classes, HPCC implications
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 36 Program structure and the simplest examples
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 37 Java Language -- Program Structure
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Source code of a Java program consists of one or more compilation
units, implemented as files with .java extension.
- Each compilation unit can contain:
- a package statement
- import statements
- class declarations
- interface declarations
- Java compiler (called javac) reads java source and produces a set
of binary bytecode files with .class extensions, one for each class declared
in the source file. For example, if Foo.java implements Foo and Fred classes,
then "javac Foo.java" will generate Foo.class and Fred.class
files.
- Suppose that Foo implements an applet and Fred is an auxiliary class
used by Foo. If HotJava/Netscape encounters a tag <APPLET code="Foo.class">,
it will download Foo.class and Fred.class files and it will start interpreting
bytecodes in Foo.class.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 38 Java Language -- Lexical Issues I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Lexical structure inherits a lot from C/C++. There are however some
notable differences which are listed below.
- Java characters are based on 16--bit wide Unicode Worldwide Character
Encoding rather than the usual 8--bit wide ASCII.
- This allows full support of all alphabets and hence all languages
- Three types of comments are supported:
- // ignore all till the end of this line
- /* ignore all between starts */
- /** an insert into an automatically generated software documentation
*/
- for /** */ one inserts HTML documentation with some simple macros
such as @see (to designate see also) BEFORE the method or class being documented
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 39 Java Language -- Lexical Issues II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Java reserves the following keywords:
- abstract boolean break byte case catch
- char class const continue default do double
- else extends final finally float for
- goto if implements import instanceof int
- interface long native new
- package private protected public return
- short static super switch synchronized this
- throw throws transient try void volatile while
- Note goto is not allowed in Java but its still reserved!
- null true and false are literals with special meaning but not keywords
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 40 Java in Practice --
Applets and Applications
Use from HTML
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- More examples are in the Applet Basics section of JavaStroll
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 41 Applications Versus Applets - I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Applications are .java files with a main class which reads arguments
and is excuted first
- One uses javac to compile the application converting .java to .class
- Then run the interpreter java with the .class file as argument
- .java files are in Java; .class files are in universal bytecodes
- The resources javac and java are part of JDK and are not in Netscape
and so are currently not broadly available. You must log in to our servers
to use them
- So instead in this course we will use applets so all the Java threads
are distributed around and don't grind our servers to a halt
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 42 Applications Versus Applets - II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Applets should NOT have main method but rather init, stop, paint
etc.
- They should be run through javac compiler getting a .class file
as before
- Create an HTML file (say HelloWorld.HTML in same directory as .class
file) and include in this
- <applet code="Example.class" width=500 height=200 >
</applet> in simplest case with no parameters where applet will run
in window of given width and height (in pixels)
- If you have JDK on one's machine, one can run the applet with appletviewer
HelloWorld.html
- Alternatively run Netscape 2.0 essentially anywhere and applet is
interpreted and run by Java interpreter built into Netscape.
- This way we can compile on places with JDK installed but run almost
anywhere!
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 43 Applet Tag: Calling Applets from HTML - I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Given the following HTML
- <APPLET CODE="StockGraph"
- CODEBASE="http://www.javasoft.com/applets/"
- WIDTH=200 HEIGHT=200>
- </APPLET>
- Runs the "StockGraph.class" executable as an applet.
- WIDTH and HEIGHT are attributes that are passed along to the applet.
- If the optional CODEBASE attribute is provided, then load the executable
image from the directory specified by CODEBASE.
- Without the CODEBASE attribute, will look for StockGraph.class in
the local server's hierarchy (relative to where the HTML was loaded)
- With the CODEBASE attribute will look for StockGraph.class on the
given http hierarchy.
- Tag and attribute names are case insensitive.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 44 Applet Tag: Calling Applets from HTML - II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- <APPLET CODE="StockGraph" WIDTH=200 HEIGHT=200
- ALT="-- StockGraph Not Supported --"
- NAME=SUNW ALIGN=top
- VSPACE=5 HSPACE=5>
- Put a bunch of text here to be displayed by browsers such as Netscape
2.0 on Windows 3.1 that do not support Java
- </APPLET>
- ALT specifies text to displayed if the browser understands the applet
tag, but if unable to run applets.
- NAME specifies the name of this instance of the applet; This will
make it possible for applets on the same page to find and communicate with
each other.
- ALIGN specifies the alignment of the applet. The possible values
are the same as those available in the IMG tag (top, middle, bottom, texttop,
absmiddle, baseline, absbottom, left, right).
- Align=top which aligns top of applet with top of tallest item in
the line
- Align=texttop which aligns top of applet with top of the tallest
text in the line
- VSPACE and HSPACE specifies the vertical and horizontal spacing
in pixels, around the applet space.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 45 <param> Tags and Applets
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- <applet .... > can be followed by
- <param name=attributename1 value="attributevalue1"
> .......
- <param name=attributenameN value="attributevalueN"
>
- </applet>
- The Java program accesses this information by
- String attribute;
- attribute = getParamter("attributename1");
- if( attribute == null )
- attribute = yourdefaultvalue; // null is Java way of saying unset
- Typically this processing would be in init() method of Applet
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 46 Hello World Applet from Sun Tutorial
Getting Started
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- This prints in applet window, the classic Hello World string!
- import java.awt.Graphics
- public class HelloWorld extends java.applet.Applet {
- public void paint(Graphics g) {
- g.drawString("Hello world!", 50, 25);
- }
- }
- g which is of class Graphics, is window in which applet runs (i.e.
is displayed)
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 47 Hello World Application from Sun Tutorial
Getting Started
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- This is "application" version of previous applet
- class HelloWorldApp {
- public static void main (String args[]) {
- System.out.println("Hello World!");
- }
- }
- Note args are of class String and needed even though HelloWorldApp
has no command line arguments
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 48 Java Language Basics
An example using arrays is found at the end of the Applet Basics section
of JavaStroll
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 49 Java Language -- Variable/Expression Types
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Each Java variable or expression has a definite type. There are
three "types" of types!
- There are Primitive or Simple types such as integers or booleans
which are built-in.
- New composite types (objects) can be constructed in terms of classes
and interfaces. The type of an object is its class or interface
- Arrays we will see are a sort of "almost" object!
- First we discuss the Primitive Types
- There are 4 integer types: byte, short, int, long of size 8, 16,
32 and 64 bits, respectively.
- Float is 32 bits, double is 64 bits. Floating point arithmetic and
data formats are defined by IEEE754 standard.
- Characters are given by 16bit Unicode charset and represented as
short integers.
- One can use casts such as longint = (long) i; // which can be explicit
as here and sometimes implied (see later)
- Note booleans are either TRUE or FALSE -- they are not 0, 1 ,-1
...
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 50 Java Language -- Types: Array
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Arrays are "true" or "first class" objects in
Java and no pointer arithmetic is supported.
- An Array is declared as:
- int vec[];
- alternative syntax: int[] vec;
- and created by:
- or concisely:
- int vec[] = new int[128];
- Arrays of arbitrary objects can be constructed,
- e.g. Thread myThreadList[] = new Thread[1024];
- The only difference is that in the case of primitive types, the
array elements are actually allocated. In the case of arbitrary objects,
an array of object references is created; before you use array elements,
you must call the constructor of that type for each element.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 51 Java Language -- More on Arrays
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Subscripts are range checked in runtime and so vec[-1] and vec[128]
will generate exceptions.
- Array length can be extracted via the length instance variable,
e.g.
- int len = vec.length will assign len = 128.
- Arrays can have dynamic sizing
- int sizeofarray = 67;
- int vec[] = new int[sizeofarray];
- Multidimensional arrays are arrays of arrays
- char icon[][] = new char[16][16]
- These arrays can be "ragged":
- int graph[][] = new int[2][];
- graph[0][] = new int[4];
- graph[1][] = new int[7];
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 52 Java Language -- Expressions
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Java's expressions are very similar to C and the following are valid:
- 2+3
- (2+3)*i
- i++ /* equivalent to i = i +1 */
- (i > 0 ) && (j>0) /* Boolean */
- i <<1 /* Left shift by 1 binary digit */
- (i>0) ? true:false /* Boolean */
- i >>> 2 /* Signed right shift by 2 binary digits */
- "fred" + "jim" is "fredjim"
- /* + Equivalent to . in Perl */
- (a instanceof B) /* True iff object a is of class B */
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 53 Java Language -- Control Flow I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- if(some boolean expression) {..}
- else if(another boolean) {..}
- else {...}
- while(any boolean) {/*DoStuff*/}
- do {/*Whattodo*/} while(another boolean);
- for(expression1; booleanexpression ; expression2) {...}
- naturally starts with expression1, applies expression2 at end of
each loop, and continues as long as booleanexpression true
- switch (expression) { /* Just as in C */
- case Constant1: /* Do following if expression=Constant1 */
- /* Bunch of Stuff */
- break;
- case Constant2: /* Do following if expression=Constant2 */
- /* Bunch of Stuff */
- break; /* ....... */
- default:
- /* Bunch of Stuff */
- break;
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 54 Java Language -- Control Flow II -- continue
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- One can break out of an iteration of a (nested) for loops in fashion
offered by Perl but with a different syntax
- outer: // label
- for( int j=0; j<10; j++) { /* Note j only defined in for loop
*/
- /* select course j */
- for( int i=0; i<15; i++) {
- if(studentgrade[j][i] == 4.0) {
- /* Celebrate */
- continue outer; // go to next iteration of outer loop
- }
- }
- /* Continue jumps to here to next iteration of loop labelled with
outer */
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 55 Java Language -- Control Flow III -- break and for loop
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- One can break out of (nested) for loops in fashion offered by Perl
with different syntax
- outer: // label
- for( int j=0; j<10; j++) { /* Note j only defined in for loop
*/
- /* select course j */
- for( int i=0; i<15; i++) {
- if(studentgrade[j][i] == 4.0) {
- /* Celebrate */
- break outer; // go to end of outer loop
- }
- }
- }
- /* break jumps to here out of loop labelled by outer */
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 56 Java Language -- Control Flow IV -- break and switch
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- loopstart: // label
- for( int j=0; j <10; j++) {
- switch(j) {
- case 3:
- break;
- default:
- if( studentgrade[j] == 2.5)
- break loopstart; /* go to end of loop */
- /* do some stuff */
- break;
- }
- }
- /* break loopstart goes to here out of loopstart loop */
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 57 Java Language -- Control Flow V -- continue and switch
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- loopstart: // label of following for loop
- for( int j=0; j <10; j++) {
- switch(j) {
- case 3:
- break;
- default:
- if( studentgrade[j] == 2.5)
- continue loopstart; /* go to next iteration of loop */
- /* do some stuff */
- break;
- } // End Switch Block
- /* continue loopstart goes to here for next iteration of loopstart
loop */
- } // End loopstart for loop
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 58 The Java Object Model: Classes, Instances and Methods
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 59 The Java Object Model Overview
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- Objects are instances of Classes which form a template to allow
definition of objects of the
- same type -- Classes are not objects
- although one can define static or class
- variables and methods which are shared
- by all instances of a class
- The data of an object are called instance
- variables and they can be accessed for
- read or write if they are made public
- /* Movable Point Class */
- public class mPoint {
- public int x, y; /* Instance Variable */
- public int dx = 1, dy = 1; /* More Instance Variables */
- Better design is "data encapsulation"; instance variables
are not accessed directly, but access to all necessary values is made via
methods of the class.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 60 Date Application from Sun Tutorial
Anatomy of an Application
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- This invokes the class Date and creates object today as an instance
of this class
- Date() is Constructor of Date class which sets default value (current
date) in today
- Date today declares today to be instance of this class
- import java.util.Date;
- class DateApp {
- public static void main (String args[]) {
- Date today = new Date();
- System.out.println(today);
- }
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 61 Counting Application from Sun Tutorial
Nuts and Bolts of Java
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- This application reads from standard input and counts number of
characters which are then printed
- class Count {
- public static void main(String args[])
- throws java.io.IOException
- {
- int count = 0;
- while (System.in.read() != -1)
- count++;
- System.out.println("Input has " + count + " chars.");
- }
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 62 Java Language -- Overview of Classes
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Class declaration in Java shares common aspects with C++ but there
are also some syntactic and semantic differences.
- Only single inheritance is supported but aspects of multiple inheritance
can be achieved in terms of the interface construct. Interface is similar
to an abstract class with all methods being abstract and with all variables
being static (global). Unlike classes, interfaces can be multiply-inherited.
- ClassModifiers class className [extends superClass] [implements
interfaces] {
- e.g. public class Test extends Applet implements Runnable {
- defines an applet that can use threads which have methods defined
by Runnable interface
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 63 Instantiating an Object from its Class
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- Suppose we have defined a class called mPoint for a movable point
which has position (x,y) Color color and can be moved by amount (dx,dy)
at each step
- mPoint BunchofPoints[2]; /* defines BunchofPoints to be 2 dimensional
array of mPoint objects -- it does not instantiate BunchofPoints */
- FirstPoint = new mPoint(); /* Allocates an instance of mPoint and
invokes Constructor of mPoint to Initialize */
- FirstPoint.dx=5;
- FirstPoint.dy=5; /* Redefines values of instance variables dx,dy
for object FirstPoint */
- mPoint could be defined by
- import java.awt.*;
- public class mPoint {
- int x, y;
- int dx = 1, dy = 1;
- Color color = Color.black;
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 64 Constructors of Objects
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- Methods of identical name to class are special -- they are constructors
- mPoint() { /* Default Constructor */
- }
- We can overload method to define different versions with different
numbers and types of arguments
- mPoint(int x, int y) { /* Constructor to set Specific Initial values
*/
- }
- Note this refers to current object
- mPoint can have other methods to set its instance variables such
as:
- public void setDelta(int _dx, int _dy) {
- } /* where we don't need this as used _dx, _dy */
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 65 Class Finalizers
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- Any class can have an optional finalizer that will perform any necessary
clean-up needed when garbage collector (which is automatic in Java) tries
to delete object and free-up resources it uses
- An example is given for an object that uses an I/O stream and needs
to close it on termination
- protected void finalize() {
- try {
- } catch (Exception e) { /* Catches ANY exception */
- }
- }
- Earlier one might have set this up with syntax such as that on next
foil
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 66 Java Language -- Types of Classes - I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Possible ClassModifiers are:
- abstract -- Contains abstract methods without implementation --
typically such abstract classes have several subclasses that define implementation
of methods
- public -- May be used by code outside the class package and (unix)
file must be called ClassName.java where ClassName is unique public class
in file
- private -- this class can only be used within current file -- i.e
current class
- friendly(i.e. empty ClassModifier) -- class can be used only within
current package
- protected -- Only accessible to subclasses
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 67 Java Language -- Types of Classes - II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- threadsafe: Instance or static variables will never change asynchronously
and so can use compiler optimizations such as assigning to registers. Next
modifier -- final -- is also valuable to compilers
- final -- Cannot have a subclass for classes
- cannot be overridden for methods
- final variables have a constant value e.g.
- final int ageatdeath = 101;
- transient -- specifies that objects are not persistent
- Note most of these modifiers can be used either for a class or an
object -- a particular instance of a class
- abstract only makes sense for a class and transient is perhaps more
useful on an object basis
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 68 Java Language -- Methods
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- MethodModifier ReturnType Name(argType1 arg1, ......)
- Returntypes are either simple types (int, byte etc.), arrays or
class names
- Possible MethodModifiers are:
- public -- This method is accessible by all methods inside and outside
class
- protected -- This method is only accessible by a subclass
- private -- This method is only accessible to other methods in this
class
- friendly(i.e. empty) -- This method is accessible by methods in
classes that are in same package
- final -- a method that cannot be overriden
- static -- This method is shared by ALL instances of this class and
can be invoked with <Class>.method syntax as well as <Instance>.method
- synchronized -- This method locks object on entry and unlocks it
on exit. If the object is already locked, the method waits until the lock
is released before executing -- can be used on methods or statement blocks
- native -- to declare methods implemented in a platform -- dependent
language, e.g. C.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 69 The Java Object Model: Inheritance and the Class Hierarchy
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 70 Use of Methods Defined in Parent
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- Call to method in Object2 (message) from object1 is passed up the
class hierarchy until a definition is found
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 71 Use of Methods Defined in Parent but overridden in child class
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- Call to method in Object2 (message) from object1 is passed up the
class hierarchy until a definition is found
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 72 Comments on Casting
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Casting is supported between types and class types. Syntax:
- Two forms of casting are possible: widening and narrowing
- Widening, where the subclass is used as an instance of the superclass,
is performed implicitly
- Narrowing, where the superclass is used as an instance of the subclass,
must be performed explicitly
- Given Parent: Dot -> DrawableDot (Child):
- Widening: An instance of DrawableDot is used as an instance of Dot
- Narrowing: An instance of Dot is used as an instance of DrawableDot
- Casting between sibling classes is a compile-time error
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 73 Review of the Array Class
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Arrays replace pointer arithmetic. They're created with the new
operator:
- Indexing is 0-based.
- No multi-dimensional arrays. Must use arrays of arrays:
- int i[][] = new int[3][4];
- Brackets may follow array element type. The following are equivalent:
- int iarray[];
- int[] iarray;
- byte f(int n)[];
- byte[] f(int n);
- Array bounds checking occurs at runtime.
- The length of an array can be found by using .length:
- int a[][] = new int[10][3];
- System.out.println(a.length); // prints 10
- System.out.println(a[0].length); // prints 3
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 74 Array - A Pseudo Class!
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Not in any package
- One final instance variable: length
- For each primitive type (and all classes), there's an implicit Array
subclass
- Cannot be extended (subclassed)
- Superclass is Object
- Inherits methods from Object
- (new int[5]).getClass().getSuperclass()
- will return Java.lang.Object
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 75 By value and By reference
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Many languages are confusing as they differ in often unstated distinction
between the value and "handle" -- Java is no exception! (reference,address,pointer)
of an entity
- a = b; // sets value of a to value of b
- However if a or b is an object , b is in fact a reference and so
one sets a to refer to same object as b (i.e. same "location"
in memory)
- if you change b in some way, then a will be changed accordingly
- Note null is value of an object which has not been assigned (constructed)
and so does not point anywhere
- If a and b are primitive types, then they hold "actual literals"
and so if b=66, then a is set to 66
- In this case if you change b, then a is left unchanged
- Arguments to Methods are always passed by value BUT if an object
is an argument, then that value is ALWAYS a reference and so in practice
- Primitive types are passed by value
- Objects are passed by reference
- Arrays reflect properties of what they are arrays of!
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 76 Comments on Overloading and Overriding in Classes
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Overriding Methods
- To override a method, a subclass of the class that originally declared
the method must declare a method with the same name, return type (or a
subclass of that return type), and same parameter list.
- When the method is invoked on an instance of the subclass, the new
method is called rather than the original method.
- The overridden method can be invoked using the super variable.
- Super can be used to refer to instance variables in the superclass
as well.
- Overload Resolution is based on what is called the Signature of
a Method (see Arnold-Gosling book) which reflects:
- Lowest conversion cost of parameter list, based on type and number.
- Return type and declaration order not important.
- Java will declare an error if method is invoked where there is not
one with a unique signature which matches call after removing less specific
methods (use of objects in hierarchy can cause lots of confusing matches!)
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 77 Object-Oriented
Programming Examples:
Basic Class Operations
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- See the entire mPoint example in the Object-Oriented Programming
section of JavaStroll
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 78 A little more complicated Paint Method for Applets
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- paint is an important method in applets which is defined in parent
component class as the null method
- It must be overwritten by any dynamic applets that need to update
display.
- import java.awt.*; // imports all classes in java.awt package --
this applet needs Graphics, Font, Color which could be listed separately
- public class HelloWorld extends java.applet.Applet {
- Font f = new Font("TimesRoman",Font.BOLD,36);
- public void paint(Graphics g) {
- g.setFont(f);
- g.setColor(Color.red);
- g.drawString("Hello world!", 50, 25); }
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 79 Some More Methods for mPoint
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- import java.awt.*; /* Imports Graphics Method for display */
- public class mPoint { /* Continue as before and add */
- public void setColor(Color color) {this.color=color;}
- public void checkBoundry(Rectangle rect) { /* check if object crosses
boundary */
- int nx = x+dx; /* caculate new location */
- int ny = y+dy;
- if ( (nx < rect.x) || (nx >= rect.x+rect.width) ) dx = -dx;
- if ( (ny < rect.y) || (ny >= rect.y+rect.height) ) dy = -dy;
- }
- public void move(Graphics g) { /* move object */
- x += dx; /* update location */
- y += dy;
- paint(g);
- }
- public void paint(Graphics g) /* actually draw point */
- { g.setColor(color);
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 80 Inheritance or Subclassing
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- We can define a new class mRectangle that extends mPoint where (x,y,color)
from mPoint are lower left hand corner/color and we add width and height
- public class mRectangle extends mPoint {
- int w, h;
- public mRectangle(int _x, int _y, int _w, int _h) {
- super(_x, _y); /* call mPoint's constructor */
- w = _w;
- h = _h;
- } /* End mRectangle Constructor */
- /* overwrite the mPoint's checkBoundry method */
- public void checkBoundry(Rectangle rect) {
- int nx = x+dx;
- int ny = y+dy;
- if ( (nx < rect.x) || (nx+w >= rect.x+rect.width) ) dx = -dx;
- if ( (ny < rect.y) || (ny+h >= rect.y+rect.height) ) dy =
-dy;
- }
- public void paint(Graphics g) { /* Override mPoint Method */
- g.setColor(color);
- g.drawRect(x, y, w, h);
- }
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 81 Abstract Methods
and Classes
Interfaces
(classes without implementation)
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 82 Comments on abstract Methods and Classes
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- An abstract method has no body and must be defined in some subclass
of the class in which they are declared.
- Constructors, static methods, private methods cannot be abstract
- A method that overrides a superclass method cannot be abstract
- Classes that contain abstract methods and classes that inherit abstract
methods without overriding them are considered abstract classes
- It is compile-time error to instantiated an abstract class or attempt
to call an abstract method directly.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 83 Java Language -- Interfaces - Overview
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- An interfaces specifies a collection of methods without implementing
their bodies.
- public interface Storable {
- public void store(Stream s);
- public void retrieve(Stream s);
- }
- Interfaces are used to indicate that a class has a certain behavior
(has certain methods) without conveying anything else about the class.
- Interfaces solve some of the same problems as multiple inheritance,
without as much overhead at runtime.
- There is a small performance penalty because interfaces involve
dynamic method binding.
- Interfaces can be implemented by classes on unrelated inferitance
trees, making it unnecessary to add methods to common superclass.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 84 Cars as an Examples of Interfaces/ Multiple Inheritance
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- We could imagine a Ford Mustang as inheriting from two major sources
- Firstly a set of manufacturing companies -- make these interfaces
as "qualitative"
- Secondly from a set of Vehicle types which we will make real classes
as there are non trivial methods involved in constructing cars
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 85 Picture of Interfaces and Classes for Cars and their Manufacture
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- Cars MyFordMustang = new Cars(Lots of Options)
- is a particluar instance of class Cars
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 86 Java Language -- Interface Example -- Implementing Storable
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- A class may implement an interface, in which case it provides the
body for the methods specified in the interface.
- public class Picture implements Storable {
- public void store(Stream s) {
- // JPEG compress image before storing
- }
- public void retrieve(Stream s) {
- // JPEG decompress image before retrieving
- }
- }
- public class StudentRecord implements Storable {
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 87 Interfaces can be used as Classes in type specification
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- Interfaces behave exactly as classes when used as a type.
- The syntax interfaceName variableName declares a variable or parameter
to be an instance of some class that implements interfaceName.
- public class StudentBody {
- Stream s;
- Picture id_photo;
- StudentRecord id_card;
- ...
- public void register() {
- save(id_photo);
- save(id_card);
- }
- public void save(Storable o) {
- o.store(s);
- }
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 88 Further Features of Interfaces
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- Interfaces are either public or have the default friendly access
(public for the package and private elsewhere)
- Methods in an interface are always abstract and have the same access
as the interface. No other modifiers may be applied
- Variables in an interface are public, static, and final. They must
be initialized.
- When a class implements an interface:
- it implements all the methods described in the interface
- or it is an abstract class, which leaves the implementation of some
or all of the interface methods to its subclasses
- Interfaces can incorporate one or more other interfaces, using the
extends keyword:
- public interface DoesItAll extends Storable, Paintable {
- public void doesSomethingElse();
- }
- A class can implement more than one interface:
- public class Picture implements Storable, Paintable {
- public void store(Stream s) {...}
- public void retrieve(Stream s) {...}
- public void refresh() {...}
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 89 More on Interfaces -- Why use them
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Note that Interfaces often play a software engineering as opposed
to required functional role
- For instance, the printable interface (which is fictitious and not
part of current Java release) establishs that any class implementing it
can be "printed" with a standard method -- "print"
- Note that Interfaces are not significantly used in current Java
release where perhaps there are 15 times as many class definitions as interface
definitions
- Two examples are Runnable and Cloneable both of which extend Object
class -- note interfaces like classes can extend existing classes:
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 90 More on Interfaces -- Real Examples
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- The Cloneable Interface has NO methods but is used to indicate that
an instance of this class can be "cloned" i.e. that the clone
method (defined for overarching Object class) can be used
- The Runnable Interface has one method run() which must always be
overwritten and is used to indicate that class with this interface can
use threads without being a subclass of Thread. Applets must use Runnable
if they need explicit threads because they explicitly are a subclass of
panel and as no multiple inheritance, one cannot be a subclass of two classes
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 91 Packages in Java
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 92 Overview of Packages and Directory Structure
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- One file can contain several related classes, but only one of them
can be public. If the public class is called wheat.java, then the file
must be called wheat.
- A set of classes in different files can be grouped together in a
package. Each of the files must be in the same directory and contain the
command
- The name of the directory must also be mill.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 93 Using packages
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- One uses files in a package by inserting
- at the beginning of a file that needs classes from the mill package
- Then classes in the mill package can be refered to by just using
their Classname
- Without the import command, one must explicitly say mill.Classname
- Packages can be grouped hierarchically, with the corresponding directory
tree. For example, the mill package could be a subpackage of agriculture.
Then a class is referred to as agriculture.mill.Classname.
- Except for classes provided with the Java language, all of which
have the form java.X, a class that is imported or used must either be in
the current directory or be accessible to the compiler through the CLASSPATH
environment variable.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 94 Java System Packages
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- java.lang Contains essential Java classes and is by default imported
into every Java file and so import java.lang.* is unnecessary. Thread,
Math, Object and Type Wrappers are here
- java.io contains classes to do I/O. This is not necessary (or even
allowed!) for applets which can't do much I/O in Netscape!
- java.util contains various utility classes that didn't make it to
java.lang. Date is here as are hashtables
- java.net contains classes to do network applications. This will
be important for any distributed applications
- java.applet has the classes needed to support applets
- java.awt has the classes to support windowing -- The Abstract Windows
Toolkit
- java.awt.image has image processing classes
- java.awt.peer is a secret set of classes with platform dependent
details
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 95 Somewhat more Detail on Applets and Graphics
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 96 The java.awt.Graphics Class
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- java.awt has several important classes including Graphics, Color,
Font and FontMetrics
- Graphics class has primitives to construct basic two dimensional
images with methods drawString (text), drawLine, drawRect, fillRect, drawRoundRect
(for a rectangle with rounded corners!), draw3DRect (to get shadow effect
as in buttons), drawPolygon (general polygon), drawOval, fillOval
- There are also Image, Font, Color operations
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 97 The java.awt.Font and FontMetrics Classes
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Graphicsinstance.setFont(particularFont) will set the current Font
in the instance Graphicsinstance of graphics class to the value particularFont
of class Font. There are several other such Font related methods in the
Graphics class
- The class Font has an important constructor used as in
- Font particularFont = new Font("TimesRoman",Font.PLAIN,36);
- where one can use Courier Helvetica etc. instead of Time Roman
- Font.PLAIN, Font.BOLD, Font.ITALIC are possible text styles
- FontMetrics fm = getFontMetrics(particularFont); // allows one to
find out about the font
- fm.stringWidth("text"); // returns pixel width of string
"text"
- fm.getHeight(); // returns total height of one line of Font
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 98 The java.awt.Color Classes
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Color c = new Color (redvalue, greenvalue, bluevalue); // red/green/bluevalue
can be specified as integers in 0.....255 or floating point numbers from
0 to 1.
- c is generated as a Color in RGB format.
- graphicsobject.setColor(c); // sets current color in graphicsobject
which is used for all subsequent operations
- graphicsobject.setFont(particularFont); // similarily sets font
hereafter as on previous page
- There are particular Color instances already defined such as
- Color.white equivalent to Color(255,255,255)
- Color.black as equivalent to Color(0,0,0)
- Color.pink as equivalent to Color(255,175,175)
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 99 Some Basic Methods for Applets -- I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Some of These are in Applet and some in parent (in particular Component)
- public void init() is called ONCE and ONCE only when the applet
is loaded or reloaded. Set initial parameters etc. here.
- public void destroy() is what you do when Applet is entirely finished
and you need to clean up stray threads or connections to be closed.
- public void start() is called whenever the applet is started which
can happen several times during an applet's life-cycle as it starts each
time you revisit a page
- public void stop() is called when we temporarily leave Applet to
visit another page. A wise move would be to suspend running of Threads
to save system resources.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 100 Some Basic Methods for Applets -- II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- public void paint(Graphics g) actually has an argument and draws
what you want on the screen
- There is somewhat confusing other methods update() and repaint()
which need to used in advanced applications. You may need to call repaint()
in a dynamic applet to change display but update() would not need to be
called as invoked by repaint(). However update() is sometimes best overridden
- public void repaint() is a request by you to the Java runtime to
update screen
- public void update(Graphics g) is invoked by repaint() and performs
the screen update which involves clearing screen and invoking paint()
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 101 A Simple Useful Applet from Sun for Animation
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 102 Sun's Animator.class Applet
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Sun distributes a general purpose Animation applet with the Java
Development Kit
- Advantages:
- 1. quick: users don't have to write their own program in order to
get interesting animation effects.
- 2. flexibility: user can assign the directory and the file name
for the image frame and sound files by using imagesource, soundsource,
soundtrack, and sound parameters in applet tag.
- Disadvantage:
- 1. Image blinking: This applet fail to use double buffering and
one can see serious blinking on screen.
- 2. Separating the frames into different files makes it easy to program
but will slow down the image loading process.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 103 Details of Using the Sun animator Applet --I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- 1. Prepare a directory. and cd to this directory.
- 2. Copy Animator.class, ParseException.class, and ImageNotFoundException.class
into your directory.
- 3. create a directory audio and put your audio file in it.
- Your audio files can be called 0.au, 1.au, etc.
- The background soundtrack could be any .au file.
- 4. create a directory images and put your image files in it.
- your image files can be called T1.gif, T2.gif, etc.
- the loading message can be called loading-msg.gif.
- 5. prepare a HTML page which has the following type of applet tag:
- <applet code=Animator.class width=200 height=200>
- <param name=imagesource value="images">
- <param name=endimage value=10>
- <param name=soundsource value="audio">
- <param name=soundtrack value=spacemusic.au>
- <param name=sounds value="1.au|2.au|3.au|4.au|5.au|6.au|7.au|8.au|9.au|0.au">
- <param name=pause value=200>
- </applet>
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 104 Details of Using the Sun animator Applet --II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- the imagesource attribute indicate you put your image files in directory
images.
- the endimage value 10 indicate that you have 10 image files held
in
- T1.gif, T2.gif, ..., to T10.gif
- The soundsource indicate that you put your sound files in audio
directory.
- The sounds attribute lets you express your audio file sequence.
- the pause attribute is the pause (ms) between each image frame.
- There are other parameters which can be set such as:
- <param name=startup value="loading-msg.gif">
- This image will show up first to remind user that image is loading.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 105 Threads are part of the Java Language!
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- See JavaStroll for A Basic Thread Example
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 106 Initial Remarks on Threads
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Java is remarkable for threads being built into the language
- Threads are processes which are typically "light-weight"
(unlike UNIX processes) which communicate by a combination of shared memory
and messaging
- This communication mechanism is what you get from natural access
to methods and variables in Java classes
- The Java Threads do not give all you want and for those coming from
an HPCC background, we note Java threads have no immediate support for
some key parallel computing concepts (see work of Chandy at Caltech) and
distributed memory (threads running in separate operating system instances)
- Java threads are based on basic monitors ("lock mechanism")
for synchronization which was introduced by Hoare
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 107 Threads as Discussed in Sun's Tutorial
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- One can implement threads in two ways
- Firstly subclassing the Thread class and overriding its run() method
- Secondly by creating a Thread with a Runnable object (i. e. that
implements Runnable interface)
- Only the second way is possible for applets as these already extend
Applet class and so cannot multiply inherit from the Thread class
- Threads must have a run method which is code Thread executes.
- If you are using first way, this is written for this particular
thread and overrides run() in Thread class
- In second way, the created Thread automatically takes its run()
method to be the run method of the applet
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 108 Thread Execution and Concurrency
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- Threads enable you to have multiple flows of control, running concurrently.
- Concurrency does not necessarily mean that threads actually run
at the same time, but that the Java interpreter switches between threads.
- Threads may also be assigned priority, in which case the higher
priority thread may pre-empt the lower one.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 109 The Life of a Thread
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- Each thread is always in one of five states, shown in this diagram
with the most common methods for changing state:
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 110 Sun's Digital Clock Applet to Illustrate Threads -- I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- import java.awt.Graphics;
- import java.util.Date;
- public class Clock extends java.applet.Applet
- Thread runner;
- public void start () {
- if (runner == null) {
- runner = new Thread (this, "Clock");
- runner.start ();
- }
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 111 Sun's Digital Clock Applet to Illustrate Threads -- II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- public void run () {
- while (true) {
- repaint ();
- try { runner.sleep(1000);
- } catch (InterruptedException e) {}
- } // end while
- } // end run()
- public void paint (Graphics g) {
- Date now = new Date ();
- g.drawString (now.getHours() + ":"+ now.getMinutes() +
":"+now.getSeconds(), 5, 10);
- }
- public void stop () {
- if (runner != null)
- {runner.stop();runner=null;}
- }
- } // End Digital Clock Applet
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 112 Synchronized Method and Blocks
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Synchronized methods and blocks must acquire a lock before running
- Code will therefore not run at the same time as other code that
needs access to the same resource.
- Each object has one lock associated with it and each class has exactly
one lock
- When invoked, a synchronized method waits until it can acquire the
lock for the current instance (i.e., this); a static synchronized method
waits to acquire the class lock
- Lock is released when code is done executing
- Locks are advisory
- synchronized blocks specify the object on which to synchronize
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 113 Sun's Synchronized Block Example
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- class Coach { // Give the Bunt Signal AFTER setting it!
- Sign sig = new Sign();
- ...
- void setBunt() {
- synchronized (sig) { // Wait for Lock associated with sig
- sig.bunt = true;
- }
- }
- void giveSign() {
- synchronized (sig) { // Wait for Lock associated with sig
- and will not get it until setBunt releases
- System.out.println("bunt is "+sig.bunt);
- }
- } // Continue with coach .....
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 114 Threads and Synchronization - I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- A Synchronized method provides a guarantee that the method is the
only synchronized method in the object running at the time.
- This is useful if the resource is contained completely in the object,
and in general, no waiting for a resource is necessary. (The operation
is contained completely in the method)
- public synchronized void do_it() {
- }
- More fine-grained synchronization can be obtained by synchronizing
on the particular object:
- Object obj;
- public void do_it() {
- synchronized(obj) {
- ... change the state of obj ...
- }
- ... do other time-consuming stuff ...
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 115 Threads and Synchronization - wait()
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- void wait()
- void wait(int timeout)
- The wait() method is part of the Object class, and hence available
for every object.
- This method simply causes the thread to wait until notified or until
the timeout occurs.
- timeout is an optional argument. If missing or zero, thread waits
until notify/notifyall called
- This method must be called from a synchronized method.
- wait() will be called while thread owns lock associated with a particular
object. wait() releases this lock (atomically i.e. safely)
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 116 Threads and Synchronization - notify()
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Threadsafe Variables
- void notify()
- void notifyAll()
- The notify() and notifyall() methods are part of the Object class,
and hence available for every object.
- These methods must be called from a synchronized method.
- These methods simply notifies a thread that is waiting.
- notify() notifies the thread associated with given synchronization
object that has been waiting the longest time
- notifyall() notifies all threads associated with given object
- One can mark a variable as "threadsafe" to notify the
compiler that only one thread will be modifying this variable.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 117 Threads and Synchronization - Example
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- public class AddApplet extends Applet implements Runnable {
- Thread t;
- boolean go_ahead = false;
- int a, b, totle;
- public void start() {
- t = new Thread(this);
- t.start();
- }
- public synchronized void run() {
- while ( true ) {
- while ( !go_ahead ) wait(); // wait for notify signal
- totle = a + b;
- go_ahead = false;
- System.out.println("totle = "+totle);
- }
- }
- public synchronized void adder(int i, int j) {
- a = i; b = j;
- notify(); // Notify the thread that a,b are ready
- }
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 118 Useful Basic Java Classes
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- See the end of the JavaStroll section on Applet Basics for an example
using the Math class
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 119 The Overarching Object Class
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- public class Object is the root of the Class hierarchy. Every java
class has Object as its ultimate parent and so any object (object with
a small o is any instance of any class) can use methods of Object
- Methods of Object (used as object.Method()) include:
- clone() Creates a clone of the object
- equals(another object) compares two objects returning boolean answer
- getClass() returns a descriptor of type Class (a child of Object)
defining class of object
- toString() returns a String which represents "value" of
object. It is expected that each subclass will override this method
- wait() in various forms is used to cause threads to wait
- finalize() contains code to perform when object is deleted by system
(I.e. garbage collected)
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 120 Determining and Testing Class of Object
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Suppose an object is called obj , then we get Class of obj by
- Class itsclass = obj.getClass(); // and the name of this class by:
- String name = itsclass.getName();
- One can also use instanceof in following fashion
- "foo" instanceof String // is evaluated to true but
- mPoint pt = new mPoint(x,y);
- pt instanceof String // is evaluated to false
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 121 java.lang.Object Wrappers
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- "types" such as int char float etc. are NOT classes
- Thus one cannot use methods such as
- int var;
- var.toString
- Thus ALL types have associated wrappers used like
- Character wrappedchar = new Character(char);
- now wrappedchar has lots of good methods you can use such as:
- wrappedchar.equals(anotherobject);
- wrappedchar.toString();
- There are also static (class) functions such as:
- toUppercase(char ch);
- isUpperCase(char ch);
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 122 The java.lang.Math class
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- This class provides the standard mathematical functions, using types
int, long, float and double as appropriate.
- It is a static class, meaning that you only use the methods, never
creating objects from this class.
- The methods include
- IEEEremainder, abs, ceil, cos, exp, floor, log, max, min, pow, random,
sin, sqrt, and other trig functions.
- The random number generator is a linear congruential generator,
which is fast but not random enough for many scientific applications.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 123 The Date class
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- This class exists to provide an implementation of "date"
structures. As is typical of data encapsulation classes, it has methods
to create dates, obtain and set the parts of dates, and convert dates to
other data types.
- The constructor either creates today's date or any other day (and
time) that you provide:
- Date today = new Date();
- Date ancient = new Date(999,12,31); /* Dec. 31, 999 */
- Date deadline = new Date(1996,12,31,23,59,59)
- /* Dec.31,1996 at 23:59:59 */
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 124 The String class
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- Strings are fixed length collections of Unicode characters stored
as an instance of the class.
- Most commonly, a string is created from a string literal or by using
the constructor on an array of characters:
- String greeting = "Hello";
- or
- char[] bunch = {'H','e','l','l','o'};
- String greeting = new String(bunch);
- Once created, individual characters of a string cannot be changed
in place. This example shows using the methods of indexing, catenation
(+), and substring to create a new string with one character changed:
- String test = "Chicken soup with rice";
- int a = test.indexOf('w');
- String newtest = substring(1,a-1)+"is n"+substring(a+5);
- /* getting "Chicken soup is nice" */
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 125 More on Strings, and the StringBuffer class
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- String comparison can be done with the methods equals and equalsIgnoreCase.
Note that == tests if two strings are the same string instance, while equals
tests if two different strings have the same characters.
- Other methods include length, CharAt and toString.
- The StringBuffer class has mutable strings, but is created with
a fixed maximum size. It has methods such as append to extend the length
of the string.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 126 ReverseString Class from Sun Tutorial
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- This class returns object of class String which reverses order of
characters in input object source which is also an instance of class String
- class ReverseString {
- public static String reverseIt(String source) {
- int i, len= source.length();
- StringBuffer dest = new StringBuffer(len);
- for( i= (len-1); i >=0 ; i--) {
- dest.append(source.charAt(i));
- }
- return dest.toString();
- }
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 127 The Vector class
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- In Java, while you can give the size of arrays at run time, you
cannot dynamically change the size of an array during the computation.
The vector class provides a data structure with this property - the restriction
is that all of the elements must be of type Object.
- It is usually simple to insert an element of any type and Java will
convert it to an Object. But when you extract an element, you must explicitly
cast it to convert it back to the type you want.
- A vector is created with an "initial capacity" and a "capacity
increment". It always starts with 0 elements. As you add elements,
if the initial capacity is exceeded, then more memory is automatically
allocated in the size of the capacity increment. The default is an initial
capacity of 10 and an increment which doubles each time.
- Vector shoes = new Vector();
- Vector orders = new Vector(100, 10);
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 128 Methods for Vectors
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Elements are created with the addElement method:
- Order missouri = new Order();
- orders.addElement(missouri);
- The object missouri of type Order is automatically converted to
an Object in vector instance orders defined on previous foil.
- There are methods for indexing vectors. Like arrays, the indexing
is zero-based.
- x = v.elementAt(i);
- v.setElementAt(x,i);
- The length of the Vector can be obtained:
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 129 The Hashtable class
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- This class is similar to the Perl associative array (or hash array
with {} brackets). It can store a set of key and value pairs, neither of
which can be null.
- Hashtable staff = new Hashtable();
- Employee harry = new Employee("Harry Hacker");
- staff.put("987-98-9996", harry);
- Values are retrieved by indexing with a key. Like Vectors, Hashtables
only store things of type Object and you must cast the result.
- steve = (Employee) staff.get("149-26-7355");
- If there was no entry, a null is returned.
- Performance of the Hashtable can also be affected by giving an initialCapacity
and a loadFactor for reallocation.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 130 More on the Java Language: Exceptions
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 131 Java Language -- Handling Errors Using Exceptions
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- The language itself supports concept of an exception
- Java supports a hierarchical model of exceptions which allow and
indeed require user to supply suitable handlers for any exception that
can occur in a Java program
- Note exceptions that can occur in a method must either be caught
(i.e. handled inside method) or thrown (i.e. returned to callee)
- Thrown exceptions are like returned arguments and are for instance
part of interface to a method
- Exceptions are all (at some level in hierarchy) subclasses of Throwable
class
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 132 Basic Structure of Exception Handling in Nested Calls
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- method1 {
- try {
- } catch (Exception3 e) {
- }
- }
- method2 throws Exception3 {
- call method3; // method2 just passes exception through
- }
- method3 throws Exception3 {
- call dividebyzeroorreadfileorsomething; // create exception
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 133 Examples of Exception Hierarchy
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- As Examples of hierarchy:
- catch(InvalidIndexException e) {..} would catch particular exception
whereas
- catch(ArrayException e) {..} would catch all Arrayexceptions
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 134 finally illustrated by Handling Exceptions in Closing a File
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- File file; /* defines file to be object of class File */
- try{
- file = new File("filenameyouwant");
- .......
- file.write("stuff put out");
- } catch (IOException e) {
- /* This catches ALL I/O errors including read and write stuff */
- /* After Handling Some How */
- return; /* but the finally clause will be executed whether or not
code terminates normally */
- } /* We must close file whatever happens */
- finally {
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 135 Classes of Exceptions
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- There are two subclasses of Throwable
- Error such as OutOfMemoryError which do NOT have to be caught as
they are serious but unpredictable and could typically occur anywhere!
- Exception which we have discussed
- Exception has a subclass RuntimeException that need NOT be caught
- Typical RuntimeException subclasses are
- ArithmeticException ClassCastException IndexOutofBoundException
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 136 Exceptions in Applets
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- When writing a Java applet, your code is overriding one of the standard
applet methods, and you are not allowed to throw any exceptions that it
would not. So, in general, you must handle exceptions.
- What to do: The standard trick of writing a message to System.out
works fine for debugging when running with the applet viewer. It also works
fine with the Netscape browser for errors that you don't really expect
to happen in working code (like your code had a null pointer) because Netscape
provides a "Java console" under the Options menu that displays
all messages.
- However, for errors that you really want to bring to the attention
of the user, such as they typed in their URL incorrectly and the network
methods returned a "malformedURLException", you can put up a
pop-up window in the style of professional GUI programs.
- Note that you don't have to micromanage exceptions - you don't have
to put a "try-catch" construct around every statement that can
throw an exception. You can put the "try-catch" around the entire
code with the same catch action or even put different catches for different
actions of the errors.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 137 Summary of Object-Oriented Concepts
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Lets take a breather before next more advanced topics!
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 138 Summary of Object-Oriented Concepts - I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Class: A template for an object which contains variables and methods
which can be inherited from other superclasses and whose calling sequence
and existence can be defined by interfaces
- Object or Instance: A particular realization of some class; different
instances usually have different values for their variables or instances
but the same methods
- Simple types: variables defined by int, char etc. are NOT objects
but each has an associated wrapper class which can be used with greater
power but lower efficiency
- Superclass: A class further up in the inheritance tree
- Subclass: A class further down in the inheritance tree
- Abstract classes:contain abstract methods which are not implemented
and only define interfaces. Subclasses will provide implementations
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 139 Summary of Object-Oriented Concepts - II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Method or Instance Method: the usual type of method which is defined
in a class and operates in instances of class or subclasses of defining
class
- static or class method: A method defined in a class which can operate
on the class itself or on any object
- static or class variable: A variable that is owned by the class
and all its instances as a whole. It is stored in class and not in particular
instances.
- Interface: A collection of abstract behavior(method) specifications
that individual classes can then implement
- Package: A collection of classes and interfaces. Classes or interfaces
from packages other than java.lang must be explicitly imported or referred
to by full package name
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 140 Back to Details on Graphics and Animation
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- See JavaStroll for examples of Graphics Images and Double Buffering
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 141 Graphics is Event-Driven: paint method
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- In every applet or windows application, the windowing system creates
an Image with a Graphics object to keep track of the state of the window.
- In order to draw or write text to the window, you must override
the paint method:
- In this method you put everything you want to draw in the window.
The Graphics object g has things like a current color and current font,
and there are methods for you to change these as well as draw.
- The window system can be interrupted for various reasons - the user
resized it or some other window was put on top of it and then removed -
and it does not save a copy of the pixels. Instead it calls a method called
update, which blanks the screen and then calls paint(g). So even if you
only draw one window, paint can be called many times.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 142 Changing Graphics: repaint method
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Most applets and windows applications want to change what is drawn
on the screen over its lifetime. This can be a sequenced animation, response
to user input or mouse events, and so on.
- Whenever you want to redraw the screen, call
- Repaint gets the graphics context and creates a thread to call update,
which calls your paint function. So all your drawing changes are also put
into paint.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 143 Some Graphics Methods
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Changing the current state:
- g.setColor(Color.blue);
- Font f = new Font("Helvetica", Font.ITALIC, 14);
- g.setFont(f);
- There are many other attributes of text that can be affected by
FontMetrics fm = g.getFontMetrics(f);
- such as leading, height, and kerning.
- Drawing text: g.drawString
- Drawing shapes: g.drawLine, g.drawRect, g.drawOval, g.drawArc -
and filled shape versions: g.fillRect, etc.
- One draws a sequence of text and shapes to define the screen, where
the position of the object in the screen is given by pixel coordinates.
If one object overlaps another, the latest one drawn covers up the area
of overlap.
- The exception to this is XOR graphics, which may be used to temporarily
highlight a particular color. This is an advanced technique as other colors
will also be affected.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 144 Getting Images the getImage Applet Method
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- The Applet class provides a method getImage, which retrieves an
image from a web server and creates an instance of the Image class.
- Image img = getImage(new URL("http://www.tc.com/image.gif"));
- Another form of getImage retrieves the image file relative to the
directory of the HTML or the directory of the java code.
- Image img = getImage(getDocumentBase(), "images/image.gif");
- Image img = getImage(getCodeBase(), "images/image.gif");
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 145 Drawing Images -- the drawImage Graphics Method
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Important Information in
IMAGE
Full HTML Index
- The Graphics class provides a method drawImage to actually display
the image on the browser screen.
- You can also scale the image to a particular width and height.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 146 Image Downloading -- imageObserver, MediaTracker
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- When drawImage is called, it draws only the pixels of the image
that are already available.
- Then it creates a thread for the imageObserver. Whenever more of
the image becomes available, it activates the method imageUpdate, which
in turn which call paint and drawImage, so that more of the image should
show on the screen.
- The default imageUpdate doesn't work if you are double buffering
the window in which the image appears.
- More control over showing the image as it downloads can be obtained
by working with the imageObserver class and the new MediaTracker class.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 147 Flickering in Applets and its Solution
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Unless you are careful, dynamic applets will give flickering screens
- This is due to cycle
- paint(g)
- update(g) clearing screen
- paint(g) drawing new screen .....
- where flicker caused by rapid clear-paint cycle.
- There are two ways to solve this problem which involve changing
update in different ways
- 1: Change update() either not to clear screen at all (because you
know paint() will write over parts that are to be changed) or to just clear
the parts of the screen that are changed
- or 2:Double Buffering
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 148 The default Update(Graphics g) Method
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- This sets background color and initializes applet bounding rectangle
to this color
- public void update(Graphics g) {
- g.setColor(getBackground());
- g.fillRect(0,0,width,height));
- g.setColor(getForeground());
- paint(g);
- }
- getBackground() and getForeground() are methods in component class
- fillRect() is a method in Graphics class
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 149 ColorSwirl -- An Example from Teach Yourself Java in 21 Days
- I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- This example draws a text message in color and cycles through a
series of colors. It doesn't require blanking the screen.
- public class ColorSwirl extends java.applet.Applet
- implements Runnable {
- Font f= new Font ("TimesRoman", Font.BOLD, 48);
- Color colors [] = new color [50];
- Thread runThread;
- public void start () {
- if (RunThread == null) {
- runThread = new Thread (this);
- runThread.start ();
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 150 ColorSwirl -- An Example from Teach Yourself Java in 21 Days
- run Method
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- public void run () {
- float c = 0; // initialize the color array
- for (int i = 0; i < colors.length; i++) {
- colors [i] = Color.getHSBColor (c, (float) 1.0, (float) 1.0);
- c +=.02; }
- int i = 0; // cycle through the colors
- while (true) { setForeground (colors [i]);
- repaint ();
- i++;
- try {Thread.sleep(50);}
- catch (InterruptedException e) {}
- if (i == color.length) i = 0;
- } // End while(true)
- } // end run()
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 151 ColorSwirl -- An Example from Teach Yourself Java in 21 Days
- paint and update
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- public void stop () {
- runThread.stop();
- runThread = null;
- }
- public void paint(Graphic g) {
- g.setFont(f);
- g.drawString ("All the Swirly Colors", 15,50);
- }
- public void update(Graphics g) {
- paint(g); } // No need to clear background as unchanged! -- only
color of letters changes
- } // end Applet ColorSwirl
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 152 Double Buffering to Reduce Flicker - I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Here you have two "graphics contexts" (frame buffers of
the size of the applet), and you construct the next image for an animation
"off-line" in the second frame buffer.
- This frame buffer is then directly copied to the main applet Graphics
object without clearing image as in default update()
- In init(), you would create the frame buffer:
- Image OffscreenImage; // Place to hold Image
- Graphics offscreenGraphics; /* The second graphics context of offscreenImage
*/
- offscreenImage = createImage(width,height);
- offscreenGraphics = offscreenImage.getGraphics();
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 153 Double Buffering to Reduce Flicker - II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- In paint(), one will construct applet image in offscreenGraphics
as opposed to the argument g of paint(). So one would see statements such
as:
- offscreenGraphics.drawImage(img,10,10,this);
- Finally at end of paint(), one could transfer the double buffered
image to g by
- g.drawImage(offscreenImage,0,0,this);
- One would also need to override the update() method by
- public void update(Graphics g) {
- paint(g);
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 154 Event Handling
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- See JavaStroll for a complete example of mouse handling events for
moving objects.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 155 Events in the java.awt -- Mouse, Keyboard Interaction - I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Events ( distinguish these from Exceptions!) are the way the AWT
interacts with the user at mouse or keyboard.
- The AWT calls particular event handlers (analogous to exception
or interrupt handlers) when user interacts with system in particular ways.
- The handling is defined in packages java.awt and java.awt.peer (the
machine dependent stuff) with method handleEvent() in class Component(peer)
- One could add additional capability here for systems with nifty
virtual reality and other user interfaces but we won't cover this here!
- public boolean keyDown(Event evt, int key) {} method is called when
you press keyboard.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 156 Events in the java.awt -- Mouse, Keyboard Interaction - II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- The Event class has various special class (static) variables defined
including
- Event.F1 -- the F1 key
- Event.UP The Up arrow etc.
- The Component class (grandparent of Applet) has a rich set of Event
handlers which you should override if you wish to process particular input
- public boolean mouseDown(Event evt, int x, int y) {
- anchor = new Point(x,y); // record position of mouse click
- return true; // must do this
- }
- Other handlers are mouseDrag, mouseEnter (enters current component),
mouseExit, mouseMove (with its button up), keyUp, keyDown
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 157 Abstract Windowing Toolkit (AWT): Components such as buttons,
textfields, etc.
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- See JavaStroll for an example with Layouts and Buttons
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 158 Structure of the java.awt GUI Components - I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- In Java, the GUI (Graphical User Interface) is built hierarchically
in terms of Components -- one Component nested inside another starting
with the smallest Buttons, including Menus, TextFields etc. and ending
with full Window divided into Frames, MenuBars etc.
- Not all useful Classes are inherited from Component. For instance
Menu inherits from MenuComponent (interface) --> MenuItem --> Menu
- One also needs a set of methods and classes to define the layout
of the Components in a particular Panel
- LayoutManager is a java.awt interface with several particular layout
strategies implemented as classes under this interface
- The Container class has methods to interact with LayoutManager classes
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 159 Structure of the java.awt GUI Components - II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- In the simplest use of AWT, one could add a Button to an Applet
(grandchild of Container) using in the init() method for Applet
- Button b = new Button("Are You Feeling well");
- add(b); // add() is a Container method
- The various added Components are put in the panel by the LayoutManager
using order in this they were added
- A Final critical part of the AWT is the actions generated by these
components which are processed by overriding the action() method in Component
- action(Event e, Object Anyargemightliketoreturn);
- We define extra events -- such as those connected with scrolling
or selecting buttons to those of basic mouse/keyboard
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 160 Picture of the AWT Component Class and its inheritance
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 161 Some Simple AWT Components -- label,button
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- add(new Label("aligned left")); // default alignment
- produces a text string using constructor Label of Label class
- add(new Button("Grade is A"));
- add(new Button("Grade is B")); // surely this is lowest
grade for a course on such an easy language?
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 162 AWT Components -- Checkbox
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- Checkbox's are on-off toggles implemented as
- add(new Checkbox("Red")); // defaulted to false as initial
value which can be changed by user
- add(new Checkbox("Green")); // defaulted to false
- add(new Checkbox("Blue"),null, true); // set to true --
second argument required but ignored here
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 163 AWT Components -- Radio Buttons , CheckboxGroup
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Radiobuttons are identical to Checkbox's but grouped so that only
one in a group can be on at a time. They use same class for buttons but
add CheckboxGroup class
- CheckboxGroup cbg = new CheckboxGroup(); // cbg is group for one
set of radiobuttons
- add(new Checkbox("Red", cbg, false)); // cbg is second
argument!!
- add(new Checkbox("Green", cbg, false));
- add(new Checkbox("Blue", cbg, true)); // Only one in group
cbg can be true
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 164 Some Further AWT Components -- typical subunits of panels
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Choice is a class that gives a menu where you choose from various
items
- TextField is a simple class where user can enter information into
fields
- TextArea is a somewhat more sophisticated text entry area which
are scrollable and so useful where amount of data to be entered is unlimited
- List is another child of Component that is similar in use to Choice
but gives a fixed size list which can be scrolled and where you can select
one or more entries
- Scrollbar is a class that defines a horizontal or vertical scrollbar.
Note this is distinct from scrollbars that come with TextArea and List
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 165 Some Further AWT Components -- Canvas, Window - I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Canvas is a simple class which are used to draw on as in artist's
canvas. They cannot contain other components
- Upto now, we have described how to build typical Applet panels inside
browser window. There are classes that allow one to generate complete windows
separately from the browser window
- Window Class has subclasses Frame and Dialog
- Frame("TitleofWindow"); // creates a window with memubar
and given title
- Note Frame is a Container and can thereof be defined hierarchically
with components that are laid out by LayoutManagers
- Note a Frame in Java is NOT THE SAME as a frame in Netscape 2.0
and higher
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 166 Some Further AWT Components -- Canvas, Window - II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- MenuBar(); // defines a menubar which can be used in a frame
- Menu("Type"); // defines a menu which can itself have
hierarchically defined submemus
- Dialog(Frame, String Title, boolean mustbeansweredatonceornot);
// defines a dialog box
- Dialog boxes are used for transient data
- Issue warning to user or require (third argument true) user to verify
some action etc.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 167 Abstract Windowing Toolkit (AWT):
Actions in response to Mouse and Keyboard etc.
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- See JavaStroll for Examples
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 168 Actions associated with Components in AWT - I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- We already discussed handling Mouse and Keyboard Events. These AWT
components come with new actions which need to be handled with an action()
method in your applet
- Put action ( a method of class Component) in Container instance
that is at lowest possible level so you can customize action to things
in that Container
- action(Event evt, Object arg)'s are looked for in same fashion as
exceptions. Scan up Containers looking for a method of this name. Scanning
stops when you find an action and that method returns true
- evt.target holds the object that caused the Event
- Object Arg returned depends on particular Component invoked
- There are further evt.id's associated with the various peculiar
Components -- see description of class Event for current detailed description.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 169 Actions associated with Components in AWT - II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Suppose we have a bunch of buttons in a particular Container saying
Red, Green, Blue as we illustrated earlier. Then a good action method would
be
- public boolean action(Event evt, Object arg) {
- if( evt.target instanceof Button)
- changeColor((String) arg); // changeColor Supplied by the user processes
color defined by text string used in defining buttons
- return true; // tell runtime that this event fully processed
- }
- void changeColor(String bname) { // A suitable user routine to be
called by above action
- if( bname.equals("Red")) setBackground(Color.red);
- else if (bname.equals("Green")) setBackground(Color.green);
- else if (bname.equals("Blue")) setBackground(Color.blue);
- else setBackground(Color.pink); // our favorite color
- }
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 170 Abstract Windowing Toolkit (AWT):
Layouts
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 171 Layout of Components in a Panel
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- The various panels in a container are laid out separately in terms
of their subcomponents
- One can lay components out "by hand" with positioning
in pixel space
- However this is very difficult to make machine independent. Thus
one tends to use general strategies which are embodied in 5 LayoutManger's
which all implement the LayoutManager Interface. One can expect further
custom LayoutManager's to become available on the Web
- setLayout(new FlowLayout()); // creates a basic flow layout in your
panel -- actually unnecessary as default
- Other available LayoutManager's are GridLayout(), BorderLayout()
(default for Frame's), CardLayout() (Used for dynamic layouts) and GridBagLayout()
(the most flexible)
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 172 Description and Example of BorderLayout
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- BorderLayout has five cells called North South East West Center
and components are assigned to these cells with the add method. As used
in a window, one would naturally use:
- add("North", new TextField("Title",50));
- add("South", new TextField("Usuallyreservedforstatusmessage",50));
- Remember this is default for a Frame Container
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 173 Brief Description of Four Other LayoutManager's
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- FlowLayout is a one dimensional layout where components are "flowed"
into panel in order they were defined. When a row is full up, it is wrapped
onto next row
- GridLayout is a two dimensional layout where you define a N by M
set of cells and again the components are assigned sequentially to cells
starting at top left hand corner -- one component is in each cell
- GridBagLayout uses a new class GridBagConstraints to customize positioning
of individual components in one or more cells
- CardLayout lays out in time not space and each card (Displayed at
one time) can be laid out with one of spatial layout schemes above
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 174 FlowLayouts in detail
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- This simple layout manager starts putting components in the window
from the top left, continues across the row until there is no more room,
starts the next row, and so on. The components can be aligned, and space
between them given by the arguments hgap and vgap.
- setLayout(new FlowLayout(FlowLayout.LEFT, 5, 1);
- setLayout(new FlowLayout(FlowLayout.CENTER);
- setLayout(new FlowLayout(FlowLayout.RIGHT);
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 175 Hierarchical use of LayoutManagers
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- Layout's can be made very sophisticated using an hierarchical approach
- setLayout(new GridLayout(1,3,10,5)); // Number of cells in y, Number
in x, Horizontal gap, Vertical Gap
- subpanel1 = new MysubpanelClass(); // Add arguments to make subpanel1
special
- subpanel2 = new MysubpanelClass();
- add(Some Simple Component such as a Button);
- add(subpanel1);
- add(subpanel2);
- ..........
- Class MysubpanelClass extends panel { // has constructor
- MysubpanelClass() { // that includes another layout such as
- setLayout(new GridLayout(2,2,5,5); // etc.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 176 Networking, Web Access and I/O
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 177 Networking, Web Access and I/O in Java
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- This area will evolve rapidly as existing I/O systems get linked
to Java with special classes such as those needed to link MPI (HPCC Message
Passing) or Nexus (Well known distributed memory thread package)
- One can establish Web Connection with URL class and access documents
there
- One can set up a more general URLConnection for more general input/output
operations through Web(HTTP) protocol
- One can set up a Socket link which is permanent rather than on again
off again Web client-server interaction
- One can send messages and so transfer information between different
Applets
- One can (outside Netscape) access same functionality as usual UNIX
stdio library
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 178 Security Concerns for Applets
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- One aspect of Java security is language restrictions designed not
to let a Java applet or application access memory on the machine outside
of its own space.
- Applets have additional restrictions:
- they can never run a local executable program;
- they cannot communicate with any host other than the server from
which they were downloaded (the originating host);
- they cannot read or write to the local computer's file system, except
through the browser mechanism;
- they cannot find out information about the local computer (see table
on next slide for details).
- As of summer 1996, no known applets have seriously broken security
to steal client information or trash the local disk. Exceptions:
- applets have been written to use up arbitrary amounts of client
cpu.
- applets with native code can trash the local disk. So far, native
code is disallowed on publicly released browsers.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 179 Table for Java file and network access
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- This table shows what Java programs can do in the following four
cases:
- NL - Netscape loading a URL for applet
- NF - Netscape loading a local file for applet
- AV - Applet viewer
- JA - Java application (not an applet)
- read local file no no yes yes
- write local file no no yes yes
- get file information no no yes yes
- delete file no no no yes
- run another program no no yes yes
- read the user.name proper no yes yes yes
- connect to network port on server yes yes yes yes
- connect to network port on other host no yes yes yes
- load Java library no yes yes yes
- call exit no no yes yes
- create a pop-up window with warning yes yes yes
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 180 Accessing URL's in Java -- URL, showDocument
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- First you set the URL in various ways using something like
- String npacurl = "http://www.npac.syr.edu/index.html";
- try {theinputurl=newURL(npacurl);} // URL class is in java.net
- catch ( MalformedURLException e) {
- System.out.println("Bad URL: " + npacurl); }
- where you are meant to test to see if URL is legal!
- The simplest thing to do now is to see this page with
- getAppletContext().showDocument(theinputurl, Frame targetdisplayframe);
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 181 Accessing URL's in Java -- URLConnection
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- More interesting is to access a URL and process the information
there!
- This is done using a stdio like stream (generalizes pipe) which
is supported in java.io package with usual buffering capabilities
- There are methods in class URL -- InputStream in = instanceofURL.openStream();
// opens an InputStream associated with given url
- More general is instanceofURL.openConnection() establishes a general
connection and returns an instance of class URLConnection
- This provides most general HTTP connectivity and indeed has some
advantages over sockets as these are subject to special security restrictions
in Netscape's current implementation
- Note that one can connect not just to HTML files but also to CGI
scripts i.e. programs at server and so obtain flexible connectivity
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 182 Input/Output in Java -- InputStreams -- I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- In java.io, there are several classes that throw IOExceptions --
please catch them!
- The class InputStream is basic and it has methods such as read()
skip() (bytes in a stream) available() (bytes remaining in stream) close().
- InputStreams can be created from memory
- InputStream s = new ByteArrayInputStream(buffer, 100, 300); // creates
a stream of 300 bytes in locations 100 to 399
- More usefully, they can be created from a UNIX file
- InputStream s = new FileInputStream("/usr/gcf/greatidea");
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 183 Input/Output in Java -- (Filter etc.)InputStreams -- II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- There is a clever class called FilterInputStream which can be used
to add value to a raw InputStream. You can define your own filters but
important ones provided are:
- BufferedInputStream -- establishs an intermediate buffer to service
stream
- DataInputStream -- allows one to address stream in terms of higher
level constructs -- namely read a line, read a long integer etc.
- LineNumberInputStream -- adds line numbers to a stream
- PushbackInputStream -- allows one to "unread" a character
and put it back on the input stream
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 184 Accessing URL's in Java -- InputStreams and URLConnections
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- String line; // Here is a useful example
- try { URLConnection conn = npacurl.openConnection();
- conn.connect(); // could set options after creation of conn in above
line and before connect method invoked
- InputStream in = conn.getInputStream(); // establish an InputStream
on this connection
- DataInputStream data = new DataInputStream(new BufferedInputSream(in));
// set up two filters allowing both buffering and line access to InputStream
- while ((line = data.readline()) != null ) {
- System.out.println("line"); } // print out line -- obviously
put your favorite line processing here
- } catch (IOException e) {processerror}
- Note one useful exception EOFException which can be caught and remove
testing in read loops
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 185 Performance
and dreaming about the Future
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 186 Use of Native Classes to Speed Up Execution
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* Critical Information in IMAGE
Full HTML Index
- One can essentially augment supplied Java Runtime by supplying your
own C or other code implementing a particular functionality in a higher
performance mode
- This of course generates machine dependence and should only be used
if really needed
- First for classes you wish to implement in native fashion, put in
your java code lines like:
- public native mustgofast(arguments); // default functions
- static {System.loadLibrary("faststuffhere");} // static
and in class and so runs only ONCE! and loads the native code
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 187 Comments on Native C Methods
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Advantages
- May call resources available from C
- Window/Graphic Systems
- Database
- Networking
- Other Third Party Libraries
- Disadvantages
- Classes with native methods, or library linking calls, may not be
downloaded across the network.
- Libraries may not be downloaded across the network.
- Programmer must write a native library for every platform used.
- So usually user defined native method can not be used remotely in
Applet.
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 188 HPCC and Java -- High Performance HPjava -- I
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- The activities that has gone into defining High Performance Fortran
(HPF) and HPC++ can be reexamined for Java which is quite well suited for
parallelism as
- It essentially has task parallelism built in with Applet mechanism
- As there are no pointers, it is easier to define data and other
implicit parallelism so it can be efficiently implemented
- Interesting Compiler challenge independent of parallelism, is to
produce efficient code from bytecodes. Here a technique called "just
in time" compilation does compilation at runtime and can probably
increase performance of Java code by a factor of 10 or so to become comparable
with performance of C
- Surely many will produce Fortran C PASCAL to Java translators so
you can webify your existing applications
- This is an alternative to wrapper technology as in native classes
HELP! * GREY=local
HTML version of LOCAL Foils prepared July 10 1996
Foil 189 HPCC and Java -- HPjava -- II
From Basic Lectures on Java Language Applets Graphics Networking
Trip to China and Icase Tutorial -- July 12-28 and June 10-13 96.
* See also color IMAGE
Full HTML Index
- Current runtime (java Threads) assume shared memory but there are
interesting possible distributed memory and distributed shared memory implementations
- One can imagine a dataparallel interface where methods would implement
array and other data parallel operations with distributions specified by
annotations as in HPF
- Here one has a HPJava translator that produces java "plus message
passing" code
- Important implication for parallel CORBA using Java classes to interface
with CORBA
- Java based servers will allow data and task parallel Java to implement
World Wide compute webs
Northeast Parallel Architectures Center, Syracuse University, npac@npac.syr.edu
If you have any comments about this server, send e-mail to webmaster@npac.syr.edu.
Page produced by wwwfoil on Tue Sep 17
1996