Docstoc

Introduction to Java

Document Sample
Introduction to Java Powered By Docstoc
					                                               A Bit of History

                                               • Java Language was developed at Sun in
                                                 1991 as part of the Green Project

Introduction to Java                           • Green project was of an initiative at Sun to
                                                 develop software to control consumer
                                                 electronics devices
                   ISM 614                     • The researchers wanted to develop a
                Summer 2001                      programming language that would run the
               Dr. Hamid Nemati                  “smart” appliances of the future, interactive
                                                 TV, interactive toasters, etc.




What is Java                                   A Bit of History

• A general-purpose programming language      • They wanted these devices to communicate with
  for developing software that can run on       each other.
  different platforms.                        • Green project researchers developed a prototype
                                                device called “Star 7”.
• Sun described Java as follows:
                                              • The original idea was to develop the   operating
  A simple, object-oriented, distributed,       system for Star 7 in C++
  interpreted, robust, secure, architecture   • James Gosling the project leader used C++ to write a
  neutral, portable, high-performance,          language for the Star 7.
  multithreaded, and dynamic language .       • He called the new language Oak.
                                              • Oak became Java.




                                                                                                       1
History Continued                                         Why Java

• In 1994 Sun developed a Web browser (WebRunner,         • Qualities that made Java attractive as an
  later became HotJava) that could run Java applet.
                                                            operating system for Start 7 also made it
• In 1995, Netscape became the first company to license
                                                            attractive for developing Web based
  Java.
• In 1996, Marc Andreesen said: “Java is a huge
                                                            applications.
  opportunity for all of us”                                 – Java is cross platform
• 1997, Addition of Application Programming                  – Java is object based
  Interface(API) to support database access, remote          – Java is small
  objects, an object component model,
                                                             – Java is secure
  internationalization, printing, encryption, digital
  signatures, and many other technologies,                   – Java is portable




Versions of Java                                                          Why Study Java?

• Sun has released three major versions of                • Java is a relatively simple language.
  Java                                                    • Java is Object Oriented (OO).
   – Java 1.0.2 is still the most widely used and
                                                             – OO languages divide programs into modules
     widely supported by web browsers
                                                               ( objects) that encapsulate the program's actions.
   – Java 1.1.5 released in Spring 1997 with
                                                             – Object Oriented Programming (OOP) is a good
     improvements to the user interface, event
                                                               way to build complex software systems.
     handling, and much more
   – Java 2, the newest version release in December
                                                          • Java is robust .
     1998, include Swing, “look-and-feel”, “drag-and         – Errors in Java don't cause system crashes as
     drop”, enhanced audio and video capabilities.             often as errors in other languages.




                                                                                                                    2
                Why Study Java?                                             How Java Works on a Server

                                                                           •   Java software is stored on the network
• Java is platform independent .                                               or local disk.
   – A Java program can be run without changes on                          •   The Java virtual machine on the server
     different kinds of computers.                                             first does stringent security checks, and
                                                                               then runs the software.
• Java is a distributed language.
                                                                           •   The server's operating system provides
   – Java programs can easily be run on computer                               machine-specific support for many of
     networks.                                                                 the actual operations and interactions.
                                                                           •   Result: A "servlet" or other Java
• Java is a relatively secure language.
                                                                               program running on the server and
   – Java contains features that protect against viruses                       interacting with other systems on the
     and other untrusted code.                                                 network. The Java virtual machine
                                                                               serves as consistent platform.




          Why (Really) Study Java?                                         OO Key Points

• In Java, even novice programmers can write               • A Java program is a set of interacting
  sophisticated programs that can be                         objects. This is the basic metaphor of object-
  distributed through the Web to just about                  oriented programming (OOP).
  any computer in the world.                               • OOP Principles
                                                             – Divide and Conquer : Successful problem
• As an example of the type of programs                        solving involves breaking a complex problem
  you’ll be able to write, click here to try the               into small, manageable tasks.
  CyberPet demonstration.                                    – Encapsulation and Modularity : Each task
                                                               should be assigned to an object; the object's
                                                               function will be to perform that task.




                                                                                                                           3
                   OO Key Points                                          Programming Languages

• OOP Principles                                                • High-level Language
   – Interface : Each object should present a clear public
                                                                  – Easily readable by humans -- (a + b) / 2
     interface that determines how other objects will use it.
   – Information Hiding : Each object should shield its users     – Used to write most computer software.
     from unnecessary details of how it performs its task.        – Examples: Java, C, C++, BASIC, Pascal,
   – Generality : Objects should be designed to be as general       COBOL, FORTRAN.
     as possible.
                                                                  – Cannot be directly understood by a computer.
   – Extensibility : Objects should be designed so that their
     functionality can be extended to carry out more            • Machine Language
     specialized tasks.                                           – The only language understood by the CPU.
                                                                  – Binary code -- 0010010010100010101




OO Key Points                                                                Language Translators

• Encapsulation Principle                                       • Interpreter
   – Problem solving: Each object knows how to                    – Software than translates a single line of a high-
     solve its task and has the information it needs.               level language program into machine language.
                                                                  – BASIC and Perl are interpreted languages.
   – Example: Sales agent is the sales expert. The
     shipping clerk is the shipping expert.                     • Compiler
• Information Hiding Principle                                    – Software that translates an entire high-level
                                                                    program ( source code ) into an entire machine
   – Objects hide details of their expertise.                       language program ( object code ).
   – Example: Customer needn’t know how the sales                 – C, C++, COBOL, FORTRAN are compiled.
     agent records the order.                                   • Java uses interpretation and compilation




                                                                                                                        4
                 Java Programs                                           The HelloWorld Application

• A Java program is made up of class
                                                                                                                                Multi-line
  definitions.                                     /*
                                                       * The HelloWorld application program                                     comment block
                                                       */
• A class definition contains a header and a                                                                                          Single-line
  body.                                            public class HelloWorld                   // Class header                          comments
                                                   {                                    // Start of class body

• A method is a named section of code that              public static void main(String argv[]) // Main method
  can be called by its name.                                {
                                                                System.out.println("Hello world!");
• Multi-line and single-line comments are                   } // End of main


  used to document the code.                       } // End of HelloWorld                                                 Execution starts on
                                                                                                                          the first line of main()




          Applications vs. Applets                                              The HelloWorld Applet

 Java Applications            Java Applets         /*
                                                                                                                  These statements import
                                                       * HelloWorld applet program
• Stand-alone program    • Embedded program.           */
                                                                                                                  Java class names.

• Runs independently     • Runs in a Web browser   import java.applet.Applet;                // Import the Applet class
                                                   import java.awt.Graphics;                 // and the Graphics class
• Has a main() method    • No main() method.
                                                   public class HelloWorld extends Applet // Class header
• No HTML file           • Requires an HTML file
                                                   {                                                  // Start of body
• Run using JDK’s java   • Run using JDK’s
                                                        public void paint(Graphics g)                     // The paint method
  interpreter              appletviewer                     {
                                                                g.drawString( " H e l l o W o r l d ",10,10);
                                                                                                                           This statement displays
                                                            } // End of paint
                                                                                                                           “HelloWorld” on the
                                                   } // End of HelloWorld
                                                                                                                           browser window.




                                                                                                                                                     5
        The Java Development Process                                                 Editing a Java Program

• Step 1: Editing the Program                                             • Software: A text editor (vi, emacs, BBEdit).
   – Software: Any text editor will do.
                                                                          • Program source code must be saved in a
• Step 2: Compiling the Program
                                                                            text file named   ClassName.java     where
   – Software: Java Development Kit (JDK)
                                                                            ClassName   is the name of the   public   class
   – JDK:     javac HelloWorld.java
                                                                            contained in the file.
• Step 3: Running the Program
   – JDK:     java HelloWorld         (Application)                       • Remember: Java class names and file
   – JDK:     appletviewer file.html          (Applet)                      names are case sensitive.




Compiling & Executing a Java Program                                               Compiling a Java Program

                         Edit     User inputs the Java
                                                                 Start    • Compilation translates the source program
     Text Editor
                         Step      source program                           into Java bytecode.
   HelloWorld.java              Source Code
                                                                            – Bytecode is platform-independent
                                      Syntax               Error
 javac HelloWorld.java
                                      Errors?             Messages        • JDK Cmd:     javac HelloWorld.java
  Compile Step

                                  HelloWorld.class
  Java
  Bytecode                                                   Output       • Successful compilation will create the
                          java HelloWorld (application)                     bytecode class file: HelloWorld.class
                                                           Hello World!
     Execute Step                       or
                               appletviewer (applet)




                                                                                                                              6
        Running a Java Application                               Designing Good Programs

• The class file (bytecode) is loaded into               • Always precede coding with careful design.
  memory and interpreted by the Java Virtual             • Remember: The sooner you begin to type
  Machine (JVM)                                            code, the longer the program will take to
                                                           finish.
• JDK Command:            java HelloWorld                • Design includes designing classes, data,
                                                           methods, and algorithms.

                                                         • Design is followed by coding, testing, and
                                                           revision.




           Running a Java Applet                               The Java Development Process

• Running an applet requires an HTML file
  containing an <applet> tag:                            • Problem Specification
           <HTML>
           ...
                                                         • Problem Decomposition
           < A P P L E T C O D E = “ HelloWorld.class”
                WIDTH=200 HEIGHT=200>                    • Design Specification
           </APPLET>
           ...
           </HTML>                                       • Data, Methods, and Algorithms

• JDK Cmd:       appletviewer file.html                  • Coding into Java
• Browser: Open the applet’s HTML file.                  • Testing, Debugging, and Revising
• Example: Try running HelloApplet




                                                                                                        7
              Problem Specification                              Design Specification

• What exactly is the problem to be solved?     • What subtask(s) will the object perform?

                                                • What information will it need to perform its task?
• What information will the program be given
                                                • Which actions will it use to process the
  as input?                                       information?

                                                • What interface will it present to other objects?
• What results will the program be expected
  to produce?                                   • What information will it hide from other objects?




          Problem Decomposition                     Design Specification for a Rectangle

• Divide the problem into parts to make the     • Class Name: Rectangle
  solution more manageable.                     •   Task: To represent a geometric rectangle
                                                •   Information Needed (instance variables)
                                                    -   Length: A variable to store rectangle’s length (private)
• Divide-and-Conquer repeatedly until
                                                    -   Width: A variable to store rectangle's width (private)
  subproblems are simple to solve.
                                                •   Manipulations Needed (public methods)
                                                    - Rectangle(): A method to set a rectangle’s length and
                                                      width
• In Object-Oriented Design, each object will
                                                    - calculateArea(): A method to calculate a rectangle’s area
  solve a subproblem.




                                                                                                                   8
         Design Specification    (cont)            Data, Methods, and Algorithms             (cont.)


• An instance variable is a memory location     • Method Design
  used for storing the information needed.        - What specific task will the method
                                                    perform?
                                                  - What information will it need to perform
• A public method is a block of code used to
                                                    its task?
  perform a subtask or manipulation needed.
                                                  - 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




     Data, Methods, and Algorithms                   Method Design: calculateArea()

• What type of data will be used to represent   • Method Name: calculateArea()
  the information needed by the rectangle?      • Task: To calculate the area of a rectangle

• How will each method carry out its            • Information Needed (variables)
  appointed task?                                 – 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




                                                                                                         9
                 Coding into Java                                   Writing Readable Programs

• Stepwise Refinement is the right way to code.           • Style, in addition to working code, is the mark of a
                                                            good programmer. Style consists of:
    - Code small stages at a time, testing in between.
                                                             - Readability .
    - Errors are caught earlier.
                                                                • Code should be well-documented and easy to
• Syntax rules must be followed.                                  understand.
    - Syntax is the set of rules that determine whether      - Clarity .
      a particular statement is correctly formulated            • Conventions should be followed and convoluted code
                                                                  avoided.
•   Semantics must be understood.
                                                             - Flexibility .
    - Semantics refers to the meaning (effect on the            • Code should be designed for easy maintenance and
      program) of each Java statement.                            change.




      Testing, Debugging, and Revising                           In the Laboratory: TimerApplet

• Coding, testing, and revising a program is              • Objectives
  an iterative process.                                      – To familiarize you with the process of editing,
                                                               compiling, and running a Java applet.
• The java compiler catches syntactic errors ,
                                                             – To introduce the stepwise refinement coding
  producing error messages.                                    style.
• The programmer must test thoroughly for                    – To provide some examples of both syntax and
  semantic errors .                                            semantic errors.
    - Semantic errors are errors which manifest
                                                          • TimerApplet Demo: Click here to run the
      themselves through illogical output or behavior.
    - Errors are corrected in the debugging phase
                                                            TimerApplet and read its source code.




                                                                                                                       10
  Program Walkthrough: Documentation                                  Program Walkthrough: Import Statement

• The program begins with a comment block:                            • 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.
 * File: TimerApplet.java
 * Author: Chris LaFata, '93                                                          import java.applet.Applet;
 * Modified by: Java Java Java
                                                                                      import java.awt.*;
 * Last Modified: May 1999
                                                                                      import java.awt.event.*;
 * Description: This applet reports how many seconds the user
 * has wasted since the applet started running.
 */
                                                                      • Java library classes are organized into packages .
                                                                      • In                    we mean the Applet class in the
                                                                             java.applet.Applet

• Comments should be used throughout the program                        java.applet package .
  to clarify and document the code.                                   • 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: Documentation                                   Program Walkthrough: Class Definition

• Documentation comments /** … */ are used to                         • Class definition : header plus body .
  document the class and its methods.                                                                                    TimerApplet
                                                                                                                         implements
  /**                                                                 TimerApplet class is an
                                                                                                                         ActionListener
   * The TimerApplet class tells the user how much time is wasting.   extension of the Applet class
   * @author Java Java Java                                                                                              interface.
   */
                                                                        public class TimerApplet extends Applet
                                                                                                                                      Header
• The JDK javadoc utility can turn such comments                        {
                                                                                             implements ActionListener


  into HTML documentation.                                                public void actionPerformed( ActionEvent e)
                                                                          {                                                    Body
                                                                          }
• Example: See TimerApplet.html to see the                              }

  documentation generated for this program.
                                                                      • A block is a set of statements enclosed
                                                                        within braces {}.




                                                                                                                                               11
      Program Walkthrough: Variables                                   The actionPerformed() Method

• A variable is a memory location that stores a piece                  • The actionPerformed() method handles user actions
  of data or an object.                                                  such as button clicks.
• A variable declaration gives the variable’s type
  ( Button) and name ( calculate):                                       public void actionPerformed ( ActionEvent e)
                                                                         {
                                                                             currentTime = System.currentTimeMillis();
    private Button calculate;    // The button                               elapsedTime = currentTime - startTime;
    private TextArea display;    // The display area                         display.setText("You have now wasted " + elapsedTime
                                                                                + " milliseconds\n" + "playing with this silly Java applet!!");
    private long startTime;     // When the applet starts                } //actionPerformed()
    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




    Program Walkthrough: init() Method                                                      Stepwise Refinement

• A method is a named module that’s called to do                       • Stepwise refinement is a coding and testing
  some task.
                                                                         strategy that employs the divide-and-
• The init() method is where the applet starts. It is
  called automatically when the applet is executed.
                                                                         conquer principle.
• A method definition has a header and a body .                        • It helps to break a large task into smaller,
          public void init()
                                                                         more manageable subtasks.
                                                              Header
          {
            startTime = System.currentTimeMillis();                    • It helps to localize and identify errors in
            calculate = new Button("Watch How Time Flys!");
            calculate.addActionListener(this);                           your code.
            display = new TextArea(4,35);                      Body
            add(calculate);
            add(display);
          } // init()




                                                                                                                                                  12
   Stepwise Refinement of TimerApplet                                     Key Points

• Stage 1: Input the comment block, the                • A Java source program must be stored in a
  import statements, and class definition.               file that has a .java extension.
      • Compile and test.
                                                       • A Java bytecode file has the same name as
• Stage 2: Input the variable declarations.              the source file but a .class extension.
      • Compile and test .
                                                       • The name of the source file must be
• Stage 3: Input the    init()   method.
                                                         identical to the name of the public class
      • Compile and test.
                                                         defined in the file.
• Stage 4: Complete     actionPerformed()   method.
      • Compile and test.
                                                       • Java is case sensitive .




                    Key Points                                            Key Points

• A Java applet is an embedded program that runs
  within the context of a WWW browser. Java applets
                                                       • Good program design requires that each
  are identified in HTML documents by using the          object and each method have a well-defined
  <applet> tag .
                                                         task.
• A Java application runs in stand-alone mode.         • Coding Java should follow the stepwise
  Applications must have a main() method.
                                                         refinement approach.
• Java programs are first compiled into bytecode and
  then interpreted by the Java Virtual Machine
                                                       • A stub method is a method with a complete
  (JVM) .                                                header and an incomplete body.




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




                                                   14

				
DOCUMENT INFO
Shared By:
Tags: Java, Extension
Stats:
views:31
posted:4/23/2011
language:English
pages:14
Description: Sun has introduced Javajava logo is a programming language. It is a way to run through the interpretation of the language, grammar rules and C similar. At the same time, Java is a cross-platform programming language. java programming applications can be everywhere, from embedded devices to the server has. Which people use in the browser "Applet" (small applications) is one of the programs written in Java, the compiler will compile it into class files, WWW pages it exists, and to make the HTML file Well the marks, as long as the client Java client software installed can be run directly on the Internet "Applet". java extension is to support the java application to expand, more and more for mobile phones. Java programs include: applications, games, books and more!