1 / 54

Introduction to Java

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:

quyn-gray
Download Presentation

Introduction to Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

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

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

  5. 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,

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

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

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

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

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

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

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

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

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

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

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

  17. 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-lineandsingle-linecomments are used to document the code.

  18. 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 Applications vs. Applets

  19. The HelloWorld Application Multi-line comment block /* * 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 Single-line comments Execution starts on the first line of main()

  20. The HelloWorld Applet /* * HelloWorld applet program */ 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); } // End of paint } // End of HelloWorld These statements import Java class names. This statement displays “HelloWorld” on the browser window.

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

  22. Compiling & Executing a Java Program User inputs the Java source program Start Edit Step Text Editor HelloWorld.java Source Code Syntax Errors? Error Messages javac HelloWorld.java Compile Step HelloWorld.class Java Bytecode Output Hello World! java HelloWorld (application) or appletviewer (applet) Execute Step

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

  24. Compiling a Java Program • Compilation translates the source programinto Java bytecode. • Bytecode is platform-independent • JDK Cmd: javac HelloWorld.java • Successful compilation will create the bytecode class file: HelloWorld.class

  25. Running a Java Application • The class file (bytecode) is loaded into memory and interpreted by the Java Virtual Machine (JVM) • JDK Command: java HelloWorld

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

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

  28. The Java Development Process • Problem Specification • Problem Decomposition • Design Specification • Data, Methods, and Algorithms • Coding into Java • Testing, Debugging, and Revising

  29. 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?

  30. Problem Decomposition • Divide the problem into parts to make the solution more manageable. • Divide-and-Conquerrepeatedly until subproblems are simple to solve. • In Object-Oriented Design, each object will solve a subproblem.

  31. 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?

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

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

  34. 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?

  35. 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 algorithmis a step-by-step description of the solution to a problem

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

  37. Coding into Java • Stepwise Refinementis the right way to code. • Code small stages at a time, testing in between. • Errors are caught earlier. • Syntaxrules must be followed. • Syntax is the set of rules that determine whether a particular statement is correctly formulated • Semanticsmust be understood. • Semantics refers to the meaning (effect on the program) of each Java statement.

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

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

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

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

  42. 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.htmlto see the documentation generated for this program. /** * The TimerApplet class tells the user how much time is wasting. * @author Java Java Java */

  43. Program Walkthrough: Import Statement • An importstatement 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. • Injava.applet.Appletwe mean theAppletclass in thejava.appletpackage. • 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.*;

  44. Program Walkthrough: Class Definition • Class definition: header plus body. TimerApplet implements ActionListener interface. TimerApplet class is an extension of the Applet class public class TimerApplet extends Applet implements ActionListener { public void actionPerformed(ActionEvent e) { } } Header Body • A block is a set of statements enclosed within braces {}.

  45. 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 button private TextArea display; // The display area private long startTime; // When the applet starts private long currentTime; // Time of current click private long elapsedTime; // Time since it started • Variable names should be descriptive and should follow a distinctive style: startTime

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

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

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

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

  50. Key Points • A Java appletis 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 applicationruns in stand-alone mode. Applications must have a main() method. • Java programs are first compiled into bytecodeand then interpretedby the Java Virtual Machine(JVM).

More Related