54
Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

Embed Size (px)

Citation preview

Page 1: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

Introduction to JavaISM 614

Summer 2001

Dr. Hamid Nemati

Page 2: 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.

Page 3: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 4: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 5: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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,

Page 6: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 7: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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

Page 8: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 9: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 10: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 11: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 12: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

OO Key Points

• A Java program is a set of interacting objects. This is the basic metaphor of object-oriented 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.

Page 13: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 14: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 15: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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

Page 16: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

Language Translators

• Interpreter – Software than translates a single line of a high-

level 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

Page 17: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 18: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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

Page 19: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

The HelloWorld Application

/* * The HelloWorld application program */

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

Multi-linecomment block

Single-line comments

Execution starts on the first line of main()

Page 20: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

The HelloWorld Applet

/* * HelloWorld applet program */

import java.applet.Applet; // Import the Applet classimport 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); } // End of paint

} // End of HelloWorld

These statements import Java class names.

This statement displays “HelloWorld” on the browser window.

Page 21: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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)

Page 22: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

Compiling & Executing a Java Program

Text Editor

HelloWorld.java

javac HelloWorld.java SyntaxErrors?

Error Messages

User inputs the Javasource program

HelloWorld.class

java HelloWorld (application)or

appletviewer (applet)

Hello World!

EditStep

Compile Step

Execute Step

Start

Source Code

Java Bytecode Output

Page 23: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 24: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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

Page 25: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

Running a Java Application

• The class file (bytecode) is loaded into memory and interpreted by the Java Virtual Machine (JVM)

• JDK Command: java HelloWorld

Page 26: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

Running a Java Applet

• Running an applet requires an HTML file containing an <applet> tag:

• JDK Cmd: appletviewer file.html

• Browser: Open the applet’s HTML file.

• Example: Try running HelloApplet

<HTML>...<APPLET CODE=“HelloWorld.class” WIDTH=200 HEIGHT=200></APPLET>...</HTML>

Page 27: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 28: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

The Java Development Process

• Problem Specification

• Problem Decomposition

• Design Specification

• Data, Methods, and Algorithms

• Coding into Java

• Testing, Debugging, and Revising

Page 29: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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?

Page 30: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 31: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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?

Page 32: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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

Page 33: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 34: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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?

Page 35: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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

Page 36: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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

Page 37: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 38: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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

Page 39: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 40: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 41: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

Program Walkthrough: Documentation

• The program begins with a comment block:

• Comments should be used throughout the program to clarify and document the code.

/* * 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. */

Page 42: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

Program Walkthrough: Documentation

• Documentation comments /** … */ are used to document the class and its methods.

• The JDK javadoc utility can turn such comments into HTML documentation.

• Example: See TimerApplet.html to see the documentation generated for this program.

/** * The TimerApplet class tells the user how much time is wasting. * @author Java Java Java */

Page 43: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

• 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.

import java.applet.Applet;import java.awt.*;import java.awt.event.*;

Page 44: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

Program Walkthrough: Class Definition

• Class definition: header plus body.

public class TimerApplet extends Applet implements ActionListener{ public void actionPerformed(ActionEvent e) { }}

TimerApplet class is an extension of the Applet class

TimerApplet implements ActionListener interface.

• A block is a set of statements enclosed within braces {}.

Header

Body

Page 45: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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; // The buttonprivate TextArea display; // The display area

private long startTime; // When the applet startsprivate long currentTime; // Time of current clickprivate long elapsedTime; // Time since it started

• Variable names should be descriptive and should follow a distinctive style: startTime

Page 46: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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

Page 47: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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()

Page 48: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

Stepwise Refinement

• Stepwise refinement is a coding and testing strategy that employs the divide-and-conquer principle.

• It helps to break a large task into smaller, more manageable subtasks.

• It helps to localize and identify errors in your code.

Page 49: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 50: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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).

Page 51: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 52: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 53: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.

Page 54: Introduction to Java ISM 614 Summer 2001 Dr. Hamid Nemati

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.