Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Introduction to Java
ISM 614
Summer 2001
Dr. Hamid Nemati
What is Java
• A general-purpose programming language
for developing software that can run on
different platforms.
• Sun described Java as follows:
A simple, object-oriented, distributed,
interpreted, robust, secure, architecture
neutral, portable, high-performance,
multithreaded, and dynamic language.
A Bit of History
• Java Language was developed at Sun in
1991 as part of the Green Project
• Green project was of an initiative at Sun to
develop software to control consumer
electronics devices
• The researchers wanted to develop a
programming language that would run the
“smart” appliances of the future, interactive
TV, interactive toasters, etc.
A Bit of History
• They wanted these devices to communicate with
each other.
• Green project researchers developed a prototype
device called “Star 7”.
• The original idea was to develop the operating
system for Star 7 in C++
• James Gosling the project leader used C++ to write a
language for the Star 7.
• He called the new language Oak.
• Oak became Java.
History Continued
• In 1994 Sun developed a Web browser (WebRunner,
later became HotJava) that could run Java applet.
• In 1995, Netscape became the first company to license
Java.
• In 1996, Marc Andreesen said: “Java is a huge
opportunity for all of us”
• 1997, Addition of Application Programming
Interface(API) to support database access, remote
objects, an object component model,
internationalization, printing, encryption, digital
signatures, and many other technologies,
Versions of Java
• Sun has released three major versions of
Java
– Java 1.0.2 is still the most widely used and
widely supported by web browsers
– Java 1.1.5 released in Spring 1997 with
improvements to the user interface, event
handling, and much more
– Java 2, the newest version release in December
1998, include Swing, “look-and-feel”, “drag-and
drop”, enhanced audio and video capabilities.
Why Java
• Qualities that made Java attractive as an
operating system for Start 7 also made it
attractive for developing Web based
applications.
–
–
–
–
–
Java is cross platform
Java is object based
Java is small
Java is secure
Java is portable
Why Study Java?
• Java is a relatively simple language.
• Java is Object Oriented (OO).
– OO languages divide programs into modules
(objects) that encapsulate the program's actions.
– Object Oriented Programming (OOP) is a good
way to build complex software systems.
• Java is robust.
– Errors in Java don't cause system crashes as
often as errors in other languages.
Why Study Java?
• Java is platform independent.
– A Java program can be run without changes on
different kinds of computers.
• Java is a distributed language.
– Java programs can easily be run on computer
networks.
• Java is a relatively secure language.
– Java contains features that protect against viruses
and other untrusted code.
Why (Really) Study Java?
• In Java, even novice programmers can write
sophisticated programs that can be
distributed through the Web to just about
any computer in the world.
• As an example of the type of programs
you’ll be able to write, click here to try the
CyberPet demonstration.
How Java Works on a Server
• Java software is stored on the network
or local disk.
• The Java virtual machine on the server
first does stringent security checks, and
then runs the software.
• The server's operating system provides
machine-specific support for many of
the actual operations and interactions.
• Result: A "servlet" or other Java
program running on the server and
interacting with other systems on the
network. The Java virtual machine
serves as consistent platform.
OO Key Points
• A Java program is a set of interacting
objects. This is the basic metaphor of objectoriented programming (OOP).
• OOP Principles
– Divide and Conquer: Successful problem
solving involves breaking a complex problem
into small, manageable tasks.
– Encapsulation and Modularity: Each task
should be assigned to an object; the object's
function will be to perform that task.
OO Key Points
• OOP Principles
– Interface: Each object should present a clear public
interface that determines how other objects will use it.
– Information Hiding: Each object should shield its users
from unnecessary details of how it performs its task.
– Generality: Objects should be designed to be as general
as possible.
– Extensibility: Objects should be designed so that their
functionality can be extended to carry out more
specialized tasks.
OO Key Points
• Encapsulation Principle
– Problem solving: Each object knows how to
solve its task and has the information it needs.
– Example: Sales agent is the sales expert. The
shipping clerk is the shipping expert.
• Information Hiding Principle
– Objects hide details of their expertise.
– Example: Customer needn’t know how the sales
agent records the order.
Programming Languages
• High-level Language
– Easily readable by humans -- (a + b) / 2
– Used to write most computer software.
– Examples: Java, C, C++, BASIC, Pascal,
COBOL, FORTRAN.
– Cannot be directly understood by a computer.
• Machine Language
– The only language understood by the CPU.
– Binary code -- 0010010010100010101
Language Translators
• Interpreter
– Software than translates a single line of a highlevel language program into machine language.
– BASIC and Perl are interpreted languages.
• Compiler
– Software that translates an entire high-level
program (source code) into an entire machine
language program (object code).
– C, C++, COBOL, FORTRAN are compiled.
• Java uses interpretation and compilation
Java Programs
• A Java program is made up of class
definitions.
• A class definition contains a header and a
body.
• A method is a named section of code that
can be called by its name.
• Multi-line and single-line comments are
used to document the code.
Applications vs. Applets
Java Applications
•
•
•
•
•
Stand-alone program
Runs independently
Has a main() method
No HTML file
Run using JDK’s java
interpreter
Java Applets
•
•
•
•
•
Embedded program.
Runs in a Web browser
No main() method.
Requires an HTML file
Run using JDK’s
appletviewer
The HelloWorld Application
Multi-line
comment block
/*
* The HelloWorld application program
*/
Single-line
comments
public class HelloWorld
// Class header
{
// Start of class body
public static void main(String argv[]) // Main method
{
System.out.println("Hello world!");
} // End of main
} // End of HelloWorld
Execution starts on
the first line of main()
The HelloWorld Applet
/*
* HelloWorld applet program
*/
These statements import
Java class names.
import java.applet.Applet; // Import the Applet class
import java.awt.Graphics; // and the Graphics class
public class HelloWorld extends Applet // Class header
{
// Start of body
public void paint(Graphics g)
// The paint method
{
g.drawString("HelloWorld",10,10);
This statement displays
} // End of paint
} // End of HelloWorld
“HelloWorld” on the
browser window.
The Java Development Process
• Step 1: Editing the Program
– Software: Any text editor will do.
• Step 2: Compiling the Program
– Software: Java Development Kit (JDK)
– JDK: javac HelloWorld.java
• Step 3: Running the Program
– JDK: java HelloWorld (Application)
– JDK: appletviewer file.html (Applet)
Compiling & Executing a Java Program
Text Editor
HelloWorld.java
javac HelloWorld.java
Compile Step
Java Bytecode
Execute Step
Edit
Step
User inputs the Java
source program
Start
Source Code
Syntax
Errors?
HelloWorld.class
java HelloWorld (application)
or
appletviewer (applet)
Error
Messages
Output
Hello World!
Editing a Java Program
• Software: A text editor (vi, emacs, BBEdit).
• Program source code must be saved in a
text file named ClassName.java where
ClassName is the name of the public class
contained in the file.
• Remember: Java class names and file
names are case sensitive.
Compiling a Java Program
• Compilation translates the source program
into Java bytecode.
– Bytecode is platform-independent
• JDK Cmd: javac HelloWorld.java
• Successful compilation will create the
bytecode class file: HelloWorld.class
Running a Java Application
• The class file (bytecode) is loaded into
memory and interpreted by the Java Virtual
Machine (JVM)
• JDK Command: java HelloWorld
Running a Java Applet
• Running an applet requires an HTML file
containing an <applet> tag:
<HTML>
...
<APPLET CODE=“HelloWorld.class”
WIDTH=200 HEIGHT=200>
</APPLET>
...
</HTML>
• JDK Cmd: appletviewer file.html
• Browser: Open the applet’s HTML file.
• Example: Try running HelloApplet
Designing Good Programs
• Always precede coding with careful design.
• Remember: The sooner you begin to type
code, the longer the program will take to
finish.
• Design includes designing classes, data,
methods, and algorithms.
• Design is followed by coding, testing, and
revision.
The Java Development Process
• Problem Specification
• Problem Decomposition
• Design Specification
• Data, Methods, and Algorithms
• Coding into Java
• Testing, Debugging, and Revising
Problem Specification
• What exactly is the problem to be solved?
• What information will the program be given
as input?
• What results will the program be expected
to produce?
Problem Decomposition
• Divide the problem into parts to make the
solution more manageable.
• Divide-and-Conquer repeatedly until
subproblems are simple to solve.
• In Object-Oriented Design, each object will
solve a subproblem.
Design Specification
• What subtask(s) will the object perform?
• What information will it need to perform its task?
• Which actions will it use to process the
information?
• What interface will it present to other objects?
• What information will it hide from other objects?
Design Specification for a Rectangle
• Class Name: Rectangle
• Task: To represent a geometric rectangle
• Information Needed (instance variables)
- Length: A variable to store rectangle’s length (private)
- Width: A variable to store rectangle's width (private)
• Manipulations Needed (public methods)
- Rectangle(): A method to set a rectangle’s length and
width
- calculateArea(): A method to calculate a rectangle’s area
Design Specification (cont)
• An instance variable is a memory location
used for storing the information needed.
• A public method is a block of code used to
perform a subtask or manipulation needed.
Data, Methods, and Algorithms
• What type of data will be used to represent
the information needed by the rectangle?
• How will each method carry out its
appointed task?
Data, Methods, and Algorithms (cont.)
• Method Design
- What specific task will the method
perform?
- What information will it need to perform
its task?
- What result will the method produce?
- What algorithm will the method use?
• An algorithm is a step-by-step description of
the solution to a problem
Method Design: calculateArea()
• Method Name: calculateArea()
• Task: To calculate the area of a rectangle
• Information Needed (variables)
– Length: A variable to store the rectangle's length
(private)
– Width: A variable to store the rectangle's width
(private)
• Algorithm: area = length x width
Coding into Java
• Stepwise Refinement is the right way to code.
- Code small stages at a time, testing in between.
- Errors are caught earlier.
• Syntax rules must be followed.
- Syntax is the set of rules that determine whether
a particular statement is correctly formulated
• Semantics must be understood.
- Semantics refers to the meaning (effect on the
program) of each Java statement.
Testing, Debugging, and Revising
• Coding, testing, and revising a program is
an iterative process.
• The java compiler catches syntactic errors,
producing error messages.
• The programmer must test thoroughly for
semantic errors.
- Semantic errors are errors which manifest
themselves through illogical output or behavior.
- Errors are corrected in the debugging phase
Writing Readable Programs
• Style, in addition to working code, is the mark of a
good programmer. Style consists of:
- Readability.
• Code should be well-documented and easy to
understand.
- Clarity.
• Conventions should be followed and convoluted code
avoided.
- Flexibility.
• Code should be designed for easy maintenance and
change.
In the Laboratory: TimerApplet
• Objectives
– To familiarize you with the process of editing,
compiling, and running a Java applet.
– To introduce the stepwise refinement coding
style.
– To provide some examples of both syntax and
semantic errors.
• TimerApplet Demo: Click here to run the
TimerApplet and read its source code.
Program Walkthrough: Documentation
• The program begins with a comment block:
/*
* File: TimerApplet.java
* Author: Chris LaFata, '93
* Modified by: Java Java Java
* Last Modified: May 1999
* Description: This applet reports how many seconds the user
* has wasted since the applet started running.
*/
• Comments should be used throughout the program
to clarify and document the code.
Program Walkthrough: Documentation
• Documentation comments /** … */ are used to
document the class and its methods.
/**
* The TimerApplet class tells the user how much time is wasting.
* @author Java Java Java
*/
• The JDK javadoc utility can turn such comments
into HTML documentation.
• Example: See TimerApplet.html to see the
documentation generated for this program.
Program Walkthrough: Import Statement
• An import statement is a convenience that lets
you refer to a library class by its short name
(Applet) instead by its fully qualified name.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
• Java library classes are organized into packages.
• In java.applet.Applet we mean the Applet class in
the java.applet package.
• In a qualified name of the form X.Y.Z the last item
(Z) is the referent and (X.Y) are its qualifiers.
Program Walkthrough: Class Definition
• Class definition: header plus body.
TimerApplet class is an
extension of the Applet class
public class TimerApplet extends Applet
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
}
}
TimerApplet
implements
ActionListener
interface.
Header
Body
• A block is a set of statements enclosed
within braces {}.
Program Walkthrough: Variables
• A variable is a memory location that stores a piece
of data or an object.
• A variable declaration gives the variable’s type
(Button) and name (calculate):
private Button calculate;
private TextArea display;
// The button
// The display area
private long startTime;
private long currentTime;
private long elapsedTime;
// When the applet starts
// Time of current click
// Time since it started
• Variable names should be descriptive and
should follow a distinctive style: startTime
Program Walkthrough: init() Method
• A method is a named module that’s called to do
some task.
• The init() method is where the applet starts. It is
called automatically when the applet is executed.
• A method definition has a header and a body.
public void init()
{
startTime = System.currentTimeMillis();
calculate = new Button("Watch How Time Flys!");
calculate.addActionListener(this);
display = new TextArea(4,35);
add(calculate);
add(display);
} // init()
Header
Body
The actionPerformed()Method
• The actionPerformed() method handles user actions
such as button clicks.
public void actionPerformed (ActionEvent e)
{
currentTime = System.currentTimeMillis();
elapsedTime = currentTime - startTime;
display.setText("You have now wasted " + elapsedTime
+ " milliseconds\n" + "playing with this silly Java applet!!");
} //actionPerformed()
Stepwise Refinement
• Stepwise refinement is a coding and testing
strategy that employs the divide-andconquer principle.
• It helps to break a large task into smaller,
more manageable subtasks.
• It helps to localize and identify errors in
your code.
Stepwise Refinement of TimerApplet
• Stage 1: Input the comment block, the
import statements, and class definition.
• Compile and test.
• Stage 2: Input the variable declarations.
• Compile and test.
• Stage 3: Input the init() method.
• Compile and test.
• Stage 4: Complete actionPerformed() method.
• Compile and test.
Key Points
• A Java applet is an embedded program that runs
within the context of a WWW browser. Java applets
are identified in HTML documents by using the
<applet> tag.
• A Java application runs in stand-alone mode.
Applications must have a main() method.
• Java programs are first compiled into bytecode and
then interpreted by the Java Virtual Machine
(JVM).
Key Points
• A Java source program must be stored in a
file that has a .java extension.
• A Java bytecode file has the same name as
the source file but a .class extension.
• The name of the source file must be
identical to the name of the public class
defined in the file.
• Java is case sensitive.
Key Points
• Good program design requires that each
object and each method have a well-defined
task.
• Coding Java should follow the stepwise
refinement approach.
• A stub method is a method with a complete
header and an incomplete body.
Key Points
• A syntax error results when a statement
violates one of Java’s grammar rules.
• A semantic error or logic error is an error in
the program’s design and cannot be detected
by the compiler.
• Testing a program can only reveal the
presence of bugs, not their absence.
• Good programs should be designed for
readability, clarity, and flexibility.
Objectives
• Understand the concept of a class hierarchy.
• Be familiar with the relationship between
classes and objects in a Java program.
• Be able to understand and write simple
programs in Java.
• Be familiar with some of the basic
principles of object-oriented programming.
• Understand some of the basic elements of
the Java language.