Java™ Programming Language
                SL-275-SE6


               Student Guide




                Sun Microsystems,...
May 14, 2007 12:22 pm
Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved.

Th...
Copyright 2007 Sun Microsystems Inc., 4150 Network Circle, Santa Clara, California 95054, Etats-Unis. Tous droits réservés...
Table of Contents
About This Course ..............................................................Preface-xv
    Course Go...
Creating Java Technology Applications........................................ 2-1
         Objectives .......................
Examining the Method Body ........................................................... 4-8
       Examining Expressions ......
Creating a Subclass Using Inheritance ......................................... 7-1
           Objectives ...................
Declaring and Using Specialized Class Types ..............................9-1
    Objectives ................................
The Properties Class .................................................................... 11-5
           I/O Stream Funda...
Files and File I/O ............................................................................. 12-8
             Creatin...
The Producer Thread ......................................................... 14-26
                     The Consumer Thre...
Complex Example................................................................... 16-9
           Multiple Listeners .......
Preface




About This Course


Course Goals
          Upon completion of this course, you should be able to:
          ● ...
Course Goals

               The main goal of the Java™ Programming Language course is to provide
               you with ...
Course Overview

Course Overview
         This course first describes the Java runtime environment and the syntax of
      ...
Course Map


Course Map
                The following course map enables you to see what you have
                accompli...
Module-by-Module Overview

Module-by-Module Overview
         ●      Module 1 – “Executing Your First Java Application”
  ...
Module-by-Module Overview

              ●      Module 9 – “Declaring and Using Specialized Class Types”
                 ...
Topics Not Covered

Topics Not Covered
         This course does not cover the following topics. Many of these topics are
...
How Prepared Are You?


How Prepared Are You?
               To be sure you are prepared to take this course, can you answ...
Introductions

Introductions
          Now that you have been introduced to the course, introduce yourself to
          th...
How to Use Course Materials


How to Use Course Materials
               To enable you to succeed in this course, these co...
Conventions

Conventions
             The following conventions are used in this course to represent various
             ...
Conventions

           Typographical Conventions
               Courier is used for the names of commands, files, director...
Conventions

Additional Conventions
    Java programming language examples use the following additional
    conventions:
 ...
Module 1




Executing Your First Java Application


Objectives
             Upon completion of this module, you should be...
Additional Resources


Additional Resources

                Additional resources – The following reference provides addit...
Examining the JDK Software

Examining the JDK Software
         The JDK software contains the components you need to perfo...
Examining the JDK Software

          Examining the JDK Software Support for Developing
          Java Applications
      ...
Examining the JDK Software

23       }
24
25       public String toString() {
26           return "Stock: " + symbol + "  ...
Examining the JDK Software

                  The JDK tools provide support for the development and deployment of
        ...
Examining the JDK Software

Table 1-2 Advanced Tool Categories

 Tool Category                          Comment
 Java Plug...
Examining the JDK Software

               JDK Libraries

               The JDK libraries consist of predefined data types...
Examining the JDK Software

                ●      Other base libraries
                       This is a general grouping ...
Examining the JDK Software

               Documentation for the JDK library classes (also known as Java technology
      ...
Examining the JDK Software

The main sections of a class document include the following:
●      The class hierarchy
●     ...
Examining the JDK Software

         JDK Deployment Technologies
               Figure 1-5 highlights the deployment techn...
Examining the JDK Software

The Java Virtual Machine (JVM)
    This section provides an introduction to the JVM implementa...
Examining the JDK Software

               ●      What is a Java HotSpot™ virtual machine?
                      The first ...
Examining the JDK Software

The Java™ Runtime Environment (JRE™)
   The JRE™ software is a subset of the JDK software and ...
Examining Java Application Loading and Execution


Examining Java Application Loading and Execution
                Figure...
Examining Java Application Loading and Execution

The Class Loader
    The class loader loads all classes needed for the e...
Creating a Simple Java Application


Creating a Simple Java Application
                Like any other programming languag...
Creating a Simple Java Application

The TestGreeting Application
    This section describes the TestGreeting application.
...
Creating a Simple Java Application

                ●      public – The method main() can be accessed by anything,
       ...
Creating a Simple Java Application

The Greeting Class
    This section describes the Greeting class.

    Code 1-10 Line ...
Creating a Simple Java Application

          Compiling and Running the TestGreeting Program
                After you hav...
Creating a Simple Java Application

Troubleshooting the Compilation
    The following sections describe errors that you mi...
Creating a Simple Java Application

                Runtime Errors

                Some of the errors generated when typi...
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275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g
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Sl275 Sg
Upcoming SlideShare
Loading in …5
×

Sl275 Sg

5,823 views

Published on

Published in: Technology, Business
0 Comments
6 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
5,823
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
330
Comments
0
Likes
6
Embeds 0
No embeds

No notes for slide

Sl275 Sg

  1. 1. Java™ Programming Language SL-275-SE6 Student Guide Sun Microsystems, Inc. UBRM03-195 500 Eldorado Blvd. Broomfield, CO 80021 U.S.A. Revision G
  2. 2. May 14, 2007 12:22 pm
  3. 3. Copyright 2007 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved. This product or document is protected by copyright and distributed under licenses restricting its use, copying, distribution, and decompilation. No part of this product or document may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any. Netscape Navigator is a trademark or registered trademark of Netscape Communications Corporation in the United States and other countries. Third-party software, including font technology, is copyrighted and licensed from Sun suppliers. Sun, Sun Microsystems, the Sun logo, EJB, Enterprise JavaBeans, Java, JDK, J2EE, Java, J2SE, Java SE, JavaBeans, JDBC, JavaServer Pages, JSP, JVM, Java Naming and Directory Interface, JMX, Java HotSpot, JRE, Sun Java and Solaris are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries. Federal Acquisitions: Commercial Software – Government Users Subject to Standard License Terms and Conditions Export Laws. Products, Services, and technical data delivered by Sun may be subject to U.S. export controls or the trade laws of other countries. You will comply with all such laws and obtain all licenses to export, re-export, or import as may be required after delivery to You. You will not export or re-export to entities on the most current U.S. export exclusions lists or to any country subject to U.S. embargo or terrorist controls as specified in the U.S. export laws. You will not use or provide Products, Services, or technical data for nuclear, missile, or chemical biological weaponry end uses. DOCUMENTATION IS PROVIDED “AS IS” AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS, AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID. THIS MANUAL IS DESIGNED TO SUPPORT AN INSTRUCTOR-LED TRAINING (ILT) COURSE AND IS INTENDED TO BE USED FOR REFERENCE PURPOSES IN CONJUNCTION WITH THE ILT COURSE. THE MANUAL IS NOT A STANDALONE TRAINING TOOL. USE OF THE MANUAL FOR SELF-STUDY WITHOUT CLASS ATTENDANCE IS NOT RECOMMENDED. Export Control Classification Number (ECCN) assigned: 5 March 2003 Please Recycle
  4. 4. Copyright 2007 Sun Microsystems Inc., 4150 Network Circle, Santa Clara, California 95054, Etats-Unis. Tous droits réservés. Ce produit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l’utilisation, la copie, la distribution, et la décompilation. Aucune partie de ce produit ou document ne peut être reproduite sous aucune forme, par quelque moyen que ce soit, sans l’autorisation préalable et écrite de Sun et de ses bailleurs de licence, s’il y en a. Le logiciel détenu par des tiers, et qui comprend la technologie relative aux polices de caractères, est protégé par un copyright et licencié par des fournisseurs de Sun. Sun, Sun Microsystems, le logo Sun, EJB, Enterprise JavaBeans, Java, JDK, J2EE, J2SE, Java SE, JavaBeans, JDBC, JavaServer Pages, JSP, JVM, Java Naming and Directory Interface, JMX, Java HotSpot, JRE, Sun Java et Solaris sont des marques de fabrique ou des marques déposées de Sun Microsystems, Inc. aux Etats-Unis et dans d’autres pays. Netscape Navigator est une marque de Netscape Communications Corporation aux Etats-Unis et dans d’autres pays. Législation en matière dexportations. Les Produits, Services et données techniques livrés par Sun peuvent être soumis aux contrôles américains sur les exportations, ou à la législation commerciale dautres pays. Nous nous conformerons à lensemble de ces textes et nous obtiendrons toutes licences dexportation, de ré-exportation ou dimportation susceptibles dêtre requises après livraison à Vous. Vous nexporterez, ni ne ré-exporterez en aucun cas à des entités figurant sur les listes américaines dinterdiction dexportation les plus courantes, ni vers un quelconque pays soumis à embargo par les Etats-Unis, ou à des contrôles anti-terroristes, comme prévu par la législation américaine en matière dexportations. Vous nutiliserez, ni ne fournirez les Produits, Services ou données techniques pour aucune utilisation finale liée aux armes nucléaires, chimiques ou biologiques ou aux missiles. LA DOCUMENTATION EST FOURNIE “EN L’ETAT” ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET GARANTIES EXPRESSES OU TACITES SONT FORMELLEMENT EXCLUES, DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITE MARCHANDE, A L’APTITUDE A UNE UTILISATION PARTICULIERE OU A L’ABSENCE DE CONTREFAÇON. CE MANUEL DE RÉFÉRENCE DOIT ÊTRE UTILISÉ DANS LE CADRE D’UN COURS DE FORMATION DIRIGÉ PAR UN INSTRUCTEUR (ILT). IL NE S’AGIT PAS D’UN OUTIL DE FORMATION INDÉPENDANT. NOUS VOUS DÉCONSEILLONS DE L’UTILISER DANS LE CADRE D’UNE AUTO-FORMATION. Please Recycle
  5. 5. Table of Contents About This Course ..............................................................Preface-xv Course Goals......................................................................... Preface-xv Course Overview ................................................................Preface-xvii Course Map........................................................................ Preface-xviii Module-by-Module Overview ........................................... Preface-xix Topics Not Covered............................................................. Preface-xxi How Prepared Are You?....................................................Preface-xxii Introductions ......................................................................Preface-xxiii How to Use Course Materials ..........................................Preface-xxiv Conventions .........................................................................Preface-xxv Icons .............................................................................Preface-xxv Typographical Conventions ....................................Preface-xxvi Additional Conventions..........................................Preface-xxvii Executing Your First Java Application...........................................1-1 Objectives ........................................................................................... 1-1 Additional Resources ........................................................................ 1-2 Examining the JDK Software............................................................ 1-3 Examining the JDK Software Support for Developing Java Applications........................................................................... 1-4 JDK Deployment Technologies............................................ 1-12 The Java Virtual Machine (JVM)........................................... 1-13 The Java™ Runtime Environment (JRE™)......................... 1-15 Examining Java Application Loading and Execution................. 1-16 The Class Loader..................................................................... 1-17 The Byte-Code Verifier........................................................... 1-17 Creating a Simple Java Application .............................................. 1-18 The TestGreeting Application .......................................... 1-19 The Greeting Class............................................................... 1-21 Compiling and Running the TestGreeting Program..... 1-22 Troubleshooting the Compilation ....................................... 1-23 v Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  6. 6. Creating Java Technology Applications........................................ 2-1 Objectives ........................................................................................... 2-1 Additional Resources ........................................................................ 2-2 The Composition of a Java Application.......................................... 2-3 Examining Custom Class Creation: Concept to Implementation2-6 Examining Class Creation........................................................ 2-6 Examining Application Main Classes .................................. 2-11 Comparing Static and Dynamic Views of a Java Application... 2-12 A Static View ........................................................................... 2-12 A Dynamic View ..................................................................... 2-13 Creating, Using, and Disposing of Objects .................................. 2-19 Creating a Class: Fields and Constructors Syntax ...................... 3-1 Objectives ........................................................................................... 3-1 Additional Resources ........................................................................ 3-2 Introducing the class Declaration ................................................. 3-3 Associating a New Class With a Package.............................. 3-3 Declaring the Foreign Classes Used by the New Class ....... 3-4 Declaring the Fields of the Class............................................. 3-5 Declaring the Constructors of the Class ................................ 3-6 Declaring the Methods of the Class........................................ 3-7 Declaring Fields: Selecting Primitive Data Types ......................... 3-9 Declaring Fields: Selecting Class Types........................................ 3-11 The Java SE Class Libraries.................................................... 3-11 Declaring Fields: Formatting Identifiers....................................... 3-15 Declaring Fields: Initializing Fields............................................... 3-16 Field Initialization Using Default Values ............................ 3-17 Field Initialization Using Explicit Values............................ 3-18 Field Initialization Using Constructors............................... 3-19 Examining Comments, White Space, and Keywords ................. 3-24 Comments ................................................................................ 3-24 White Space.............................................................................. 3-25 Java Programming Language Keywords ............................ 3-25 Directory Layout and Packages ..................................................... 3-27 Development ........................................................................... 3-27 Compiling Using the -d Option ........................................... 3-28 Deployment ............................................................................. 3-29 Declaring a Class: Methods Syntax ............................................... 4-1 Objectives ........................................................................................... 4-1 Additional Resources ........................................................................ 4-2 Examining Methods........................................................................... 4-3 Examining the Class-to-Method Relationship...................... 4-4 Examining the Method Interface-to-Method Body Relationship ............................................................................ 4-5 Examining the Fields, Parameters, and Local Variables-to-Method Body Relationship ............................ 4-7 vi Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  7. 7. Examining the Method Body ........................................................... 4-8 Examining Expressions ..................................................................... 4-9 Examining Simple Expressions............................................. 4-10 Expressions: Advanced Issues ....................................................... 4-15 Numeric Promotions in Simple Expressions ...................... 4-15 Casting ...................................................................................... 4-16 Autoboxing of Primitive Types............................................. 4-17 Evaluating Compound Expressions..................................... 4-18 Introducing Statements ................................................................... 4-19 Block Statements .............................................................................. 4-21 Branching Statements ...................................................................... 4-22 Simple if Statements ............................................................. 4-22 Simple if, else Statements................................................... 4-22 Complex if, else Statements............................................... 4-23 The switch Statement........................................................... 4-24 Looping Statements ......................................................................... 4-27 The for Loops ......................................................................... 4-27 The while Loop...................................................................... 4-28 The do/while Loop ................................................................ 4-28 Special Loop Flow Control .................................................... 4-29 Advanced Method Design Issues: Overloading Methods ......... 4-31 Methods Using Variable Arguments ................................... 4-32 Advanced Method Design Issues: Pass-by-Value....................... 4-33 Advanced Method Design Issues: The this Reference ............. 4-35 Creating a Class: Using Encapsulation..........................................5-1 Objectives ........................................................................................... 5-1 Additional Resources ........................................................................ 5-2 Examining the Concept of Encapsulation ...................................... 5-3 Implementing Encapsulation in Java Technology ........................ 5-6 Using the static Keyword.............................................................. 5-9 Class Attributes ......................................................................... 5-9 Class Methods ......................................................................... 5-10 Static Initializers ...................................................................... 5-12 Static Imports.................................................................................... 5-13 Creating Arrays.................................................................................6-1 Objectives ........................................................................................... 6-1 Additional Resources ........................................................................ 6-2 Declaring Arrays ................................................................................ 6-3 Creating Arrays .................................................................................. 6-4 Creating Reference Arrays................................................................ 6-5 Initializing Arrays .............................................................................. 6-6 Multi-Dimensional Arrays................................................................ 6-7 Array Bounds ..................................................................................... 6-8 Using the Enhanced for Loop ................................................ 6-8 Array Size Immutability ................................................................... 6-9 vii Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  8. 8. Creating a Subclass Using Inheritance ......................................... 7-1 Objectives ........................................................................................... 7-1 Additional Resources ........................................................................ 7-2 Examining the Concept of Inheritance ........................................... 7-3 Examining the Benefits of Inheritance ................................... 7-5 Implementing Inheritance in Java Technology ............................. 7-6 Step 1: Selecting the Parent Class ........................................... 7-7 Step 2: Determining What Is Inherited From the Parent Class ......................................................................................... 7-8 Step 3: Declaring the Subclass ................................................. 7-9 Step 4: Adding the Attributes and Methods Specific to the Subclass ................................................................................... 7-9 Step 5: If Required, Overriding Parent Class Methods ..... 7-10 Step 6: Adding Constructors as Needed.............................. 7-13 Polymorphism .................................................................................. 7-20 Virtual Method Invocation .................................................... 7-20 Heterogeneous Collections.................................................... 7-22 Polymorphic Arguments ....................................................... 7-22 The instanceof Operator.............................................................. 7-24 Casting Object References..................................................... 7-25 The Object Class ............................................................................. 7-26 The equals Method................................................................ 7-26 The toString Method ........................................................... 7-29 The final Keyword ........................................................................ 7-30 Final Classes............................................................................. 7-30 Final Methods .......................................................................... 7-30 Final Variables ......................................................................... 7-30 Error Handling Using Exception Classes and Assertions ........... 8-1 Objectives ........................................................................................... 8-1 Additional Resources ........................................................................ 8-2 Exceptions and Assertions................................................................ 8-3 Exceptions .................................................................................. 8-3 Exception Example ................................................................... 8-4 The try-catch Statement ................................................................ 8-6 Call Stack Mechanism .............................................................. 8-8 The finally Clause ................................................................. 8-9 Exception Categories ....................................................................... 8-10 Common Exceptions........................................................................ 8-12 The Handle or Declare Rule ........................................................... 8-13 Method Overriding and Exceptions.............................................. 8-15 Creating Your Own Exceptions ..................................................... 8-16 Throwing a User-Defined Exception .................................. 8-17 Handling a User-Defined Exception ................................... 8-18 Assertions.......................................................................................... 8-19 Recommended Uses of Assertions ....................................... 8-19 Controlling Runtime Evaluation of Assertions .................. 8-22 viii Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  9. 9. Declaring and Using Specialized Class Types ..............................9-1 Objectives ........................................................................................... 9-1 Additional Resources ........................................................................ 9-2 Abstract Methods and Abstract Classes ......................................... 9-3 Abstract Class Example............................................................ 9-5 Interfaces ............................................................................................. 9-7 The Flyer Example .................................................................... 9-7 Multiple Interface Example ................................................... 9-12 Interface Declaration and Usage Rules ................................ 9-13 Nested Classes.................................................................................. 9-14 Examining the Nested Class Syntax..................................... 9-15 Inner Classes ............................................................................ 9-16 Static Nested Classes ............................................................. 9-19 Inner Interfaces, EnumeratedTypes, and Annotations...... 9-19 Enumerated Types ........................................................................... 9-20 Switch Statements ................................................................... 9-20 For Loops.................................................................................. 9-21 Enumerated Types With Fields, Methods, and Constructors.......................................................................... 9-22 Using Generics and the Collections Framework.........................10-1 Objectives ......................................................................................... 10-1 Additional Resources ...................................................................... 10-2 The Collections API ......................................................................... 10-3 Collection Implementations ........................................................... 10-5 A Set Example ........................................................................ 10-5 A List Example ...................................................................... 10-6 The Map Interface.............................................................................. 10-8 A Map example......................................................................... 10-9 Legacy Collection Classes............................................................. 10-10 Ordering Collections ..................................................................... 10-11 The Comparable Interface .................................................. 10-11 The Comparator Interface ................................................... 10-13 Generics ........................................................................................... 10-16 Generic Set Example............................................................ 10-17 Generic Map Example .......................................................... 10-18 Generics: Examining Type Parameters....................................... 10-19 Wild Card Type Parameters ............................................... 10-21 Generics: Refactoring Existing Non-Generic Code ................... 10-24 Iterators............................................................................................ 10-26 The Enhanced for Loop ............................................................... 10-28 I/O Fundamentals ...........................................................................11-1 Objectives ......................................................................................... 11-1 Additional Resources ...................................................................... 11-2 Command-Line Arguments ........................................................... 11-3 System Properties............................................................................. 11-4 ix Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  10. 10. The Properties Class .................................................................... 11-5 I/O Stream Fundamentals.............................................................. 11-6 Data Within Streams............................................................... 11-6 Byte Streams ..................................................................................... 11-7 The InputStream Methods ................................................... 11-7 The OutputStream Methods................................................. 11-8 Character Streams ............................................................................ 11-9 The Reader Methods .............................................................. 11-9 The Writer Methods ........................................................... 11-10 Node Streams.................................................................................. 11-11 A Simple Example................................................................. 11-11 Buffered Streams ............................................................................ 11-13 I/O Stream Chaining..................................................................... 11-14 Processing Streams ........................................................................ 11-15 Basic Byte Stream Classes ............................................................. 11-16 The FileInputStream and FileOutputStream Classes ................................................................................. 11-17 The BufferedInputStream and BufferedOutputStream Classes ................................................................................. 11-17 The PipedInputStream and PipedOutputStream Classes ................................................................................. 11-17 The DataInputStream and DataOutputStream Classes ................................................................................. 11-17 The ObjectInputStream and ObjectOutputStream Classes ................................................................................. 11-18 Serialization .................................................................................... 11-21 Serialization and Object Graphs ......................................... 11-21 Writing and Reading an Object Stream ............................. 11-22 Basic Character Stream Classes.................................................... 11-25 The InputStreamReader and OutputStreamWriter Methods.............................................................................. 11-26 Byte and Character Conversions ........................................ 11-26 Using Other Character Encoding ....................................... 11-26 The FileReader and FileWriter Classes ....................... 11-27 The BufferedReader and BufferedWriter Classes ..... 11-27 The StringReader and StringWriter Classes .............. 11-27 The PipedReader and PipedWriter Classes................... 11-27 Console I/ O and File I/O................................................................ 12-1 Objectives ......................................................................................... 12-1 Additional Resources ...................................................................... 12-2 Console I/O ...................................................................................... 12-3 Writing to Standard Output .................................................. 12-3 Reading From Standard Input .............................................. 12-4 Simple Formatted Output..................................................... 12-6 Simple Formatted Input ........................................................ 12-7 x Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  11. 11. Files and File I/O ............................................................................. 12-8 Creating a New File Object ................................................. 12-8 The File Tests and Utilities .................................................. 12-9 File Stream I/O...................................................................... 12-10 Implementing Multi-Tier Applications Using Networking...........13-1 Objectives ......................................................................................... 13-1 Additional Resources ...................................................................... 13-2 Networking ....................................................................................... 13-3 Sockets ...................................................................................... 13-3 Setting Up the Connection..................................................... 13-3 Addressing the Connection ................................................... 13-5 Port Numbers .......................................................................... 13-5 Java Networking Model......................................................... 13-6 Minimal TCP/IP Server .................................................................. 13-7 Minimal TCP/IP Client................................................................... 13-8 Accessing Information From a URL..................................... 13-9 Implementing Multithreaded Applications ...................................14-1 Objectives ......................................................................................... 14-1 Additional Resources ...................................................................... 14-2 Threads .............................................................................................. 14-3 Creating the Thread................................................................ 14-4 Starting the Thread ................................................................. 14-5 Thread Scheduling .................................................................. 14-6 Terminating theThread .......................................................... 14-7 Basic Control of Threads ................................................................. 14-9 Testing Threads ....................................................................... 14-9 Accessing Thread Priority ..................................................... 14-9 Putting Threads on Hold ....................................................... 14-9 Alternative Way to Create Threads............................................. 14-12 Selecting a Way to Create Threads .................................... 14-13 Using the synchronized Keyword ............................................ 14-14 The Problem........................................................................... 14-14 The Object Lock Flag ............................................................ 14-16 Releasing the Lock Flag........................................................ 14-18 Using the synchronized Mechanism............................... 14-19 Thread States ......................................................................... 14-20 Deadlock................................................................................. 14-20 Thread Interaction.......................................................................... 14-21 Scenario .................................................................................. 14-21 The Problem........................................................................... 14-21 The Solution ........................................................................... 14-21 The wait and notify Methods .......................................... 14-21 Thread States ......................................................................... 14-23 Monitor Model for Synchronization ................................. 14-24 Putting It Together......................................................................... 14-25 xi Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  12. 12. The Producer Thread ......................................................... 14-26 The Consumer Thread .......................................................... 14-26 The SyncStack Class........................................................... 14-28 The SyncTest Example........................................................ 14-31 Building Java GUIs Using the Swing API .................................... 15-1 Objectives ......................................................................................... 15-1 Additional Resources ...................................................................... 15-2 Pluggable Look-and-Feel ....................................................... 15-5 Swing Architecture ................................................................. 15-6 Swing Packages ................................................................................ 15-8 Examining the Composition of a Java Technology GUI .......... 15-10 Swing Containers ........................................................................... 15-12 Top-level Containers ............................................................ 15-12 General-purpose Containers ............................................... 15-14 Special-purpose Containers................................................. 15-15 Swing Components........................................................................ 15-18 The Swing Component Hierarchy...................................... 15-19 Buttons.................................................................................... 15-20 Text Components .................................................................. 15-21 Uneditable Information Display Components ................. 15-23 Menus ..................................................................................... 15-24 Formatted Display Components......................................... 15-25 Other Basic Controls............................................................. 15-26 Swing Components Properties .................................................... 15-28 Common Component Properties........................................ 15-28 Component-Specific Properties .......................................... 15-29 Layout Managers ........................................................................... 15-30 The BorderLayout Layout Manager ................................. 15-30 The FlowLayout Layout Manager ..................................... 15-31 The BoxLayout Layout Manager........................................ 15-32 The CardLayout Layout Manager ..................................... 15-33 The GridLayout Layout Manager ..................................... 15-34 The GridBagLayout Layout Manager............................... 15-34 The GroupLayout Layout Manager ................................... 15-35 GUI Construction........................................................................... 15-36 Programmatic Construction ................................................ 15-36 Handling GUI-Generated Events .................................................. 16-1 Objectives ......................................................................................... 16-1 Additional Resources ...................................................................... 16-2 What Is an Event? ............................................................................ 16-3 Java SE Event Model........................................................................ 16-4 Delegation Model.................................................................... 16-4 A Listener Example................................................................. 16-5 GUI Behavior .................................................................................... 16-7 Event Categories ..................................................................... 16-7 xii Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  13. 13. Complex Example................................................................... 16-9 Multiple Listeners ................................................................. 16-12 Developing Event Listeners.......................................................... 16-13 Event Adapters...................................................................... 16-13 Event Handling Using Inner Classes ................................. 16-14 Event Handling Using Anonymous Classes..................... 16-15 Concurrency in Swing ................................................................... 16-17 xiii Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  14. 14. Preface About This Course Course Goals Upon completion of this course, you should be able to: ● Create Java™ technology applications that leverage the object-oriented features of the Java language, such as encapsulation, inheritance, and polymorphism ● Execute a Java technology application from the command line ● Use Java technology data types and expressions ● Use Java technology flow control constructs ● Use arrays and other data collections ● Implement error-handling techniques using exception handling ● Create an event-driven graphical user interface (GUI) by using Java technology GUI components: panels, buttons, labels, text fields, and text areas ● Implement input/output (I/O) functionality to read from and write to data and text files ● Create multithreaded programs ● Create a simple Transmission Control Protocol/Internet Protocol (TCP/IP) client that communicates through sockets Preface-xv Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  15. 15. Course Goals The main goal of the Java™ Programming Language course is to provide you with the knowledge and skills necessary for object-oriented programming of advanced Java applications. In this course, you learn the Java programming language syntax and object-oriented concepts, as well as more sophisticated features of the Java runtime environment, such as support for GUIs, multithreading, and networking. This course covers prerequisite knowledge to help prepare you for the Sun Certified Programmer for the Java™ Platform (SCJP) examination. For information about the exam, review the web site: http://www.sun.com/training/certification/java/ However, SL-275 is not sufficient to immediately pass the exam. You should spend several months practicing these techniques by building real programs. You should also review the exam objectives and study areas that were not discussed in this course. The SCJP exam objectives can be found at the web site listed previously. Preface-xvi Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  16. 16. Course Overview Course Overview This course first describes the Java runtime environment and the syntax of the Java programming language. The course then covers object-oriented concepts as they apply to the Java programming language. As the course progresses, advanced features of the Java platform are discussed. The audience for this course includes people who are familiar with implementing elementary programming concepts using the Java programming language or other languages. This is the follow-up course to SL-110: Fundamentals of the Java™ Programming Language. While the Java programming language is independent of an operating system, the GUI that it produces can be dependent on the operating system on which the code is executed. In this course, code examples are run in the Solaris™ Operating System (Solaris OS) and in the Microsoft Windows operating environment; therefore, the graphics in this guide have both a Motif and a Windows GUI. The content of this course is applicable to all Java operating system ports. About This Course Preface-xvii Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  17. 17. Course Map Course Map The following course map enables you to see what you have accomplished and where you are going in reference to the course goal. The Java Programming Language Basics Executing Your Creating Java Creating a Class: Fields and First Java Technology Constructors Application Applications Syntax Declaring a Class: Creating a Class: Methods Syntax Using Encapsulation More Object-Oriented Programming Creating a Subclass Creating Arrays Using Inheritance Building Applications Error Handling Declaring and Using Using Exceptions Specialized Class and Assertions Types Developing Graphical User Interfaces Using Generics and Console I/O and the Collections I/O Fundamentals File I/O Framework Advanced Java Programming Implementing Multi-Tier Implementing Building Java GUIs Applications Multithreaded Using the Using Applications Swing API Networking Handling GUI-Generated Events Preface-xviii Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  18. 18. Module-by-Module Overview Module-by-Module Overview ● Module 1 – “Executing Your First Java Application” This module provides a general overview of the Java programming language and its main features and introduces a simple Java application. ● Module 2 – “Creating Java Technology Applications” This module examines the composition of a Java technology application. It examines the concepts of classes, instances, and references. ● Module 3 – “Creating a Class: Fields and Constructors Syntax” This module focuses on mapping object state using fields. It discusses the syntax of field declarations and initializations using default values, explicit values and using constructors. ● Module 4 – “Creating a Class: Methods Syntax” This module focuses on implementing behavior using methods. It looks at method signatures and method bodies and also at expressions, including operators, and the syntax of Java program control. ● Module 5 – “Creating a Class Using Encapsulation” This module discusses the concept of encapsulation and its implementation using the Java programming language. It examines the use of the package statement, access modifiers and the static keyword. ● Module 6 – “Creating Arrays” This module describes how Java arrays are declared, created, initialized, and copied. ● Module 7 – “Creating a Subclass Using Inheritance” This module examines the concept of creating specialized types using inheritance and the implementation of polymorphism. This module also contains a discussion of the use of the final keyword. ● Module 8 – “Error Handling Using Exceptions and Assertions” Exceptions provide you with a mechanism for trapping errors at runtime. This module explores both predefined and user-defined exceptions. It also contains a discussion on the use of assertions. About This Course Preface-xix Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  19. 19. Module-by-Module Overview ● Module 9 – “Declaring and Using Specialized Class Types” This module contains a discussion of the declaration and use of enumerated types, interfaces, and nested classes. ● Module 10 – “Using Generics and the Collections Framework” This module examines the collections framework and the use of generics in the Java programming language. ● Module 11 – “I/O Fundamentals” This module describes the classes available for reading and writing both data and text. It also contains a discussion on object serialization. ● Module 12 – “Console I/O and File I/O” This module introduces topics that are useful in implementing large, text-based applications, such as console and file I/O. ● Module 13 – “Implementing Multi-Tier Applications Using Networking” This module introduces the Java network programming package and demonstrates a TCP/IP client-server model. ● Module 14 – “Implementing Multithreaded Applications” Threads are a complex topic; this module explains threading as it relates to the Java programming language and introduces a straightforward example of thread communication and synchronization. ● Module 15 – “Building Java GUIs Using the Swing API” This module discusses a variety of Swing API GUI elements. ● Module 16 – “Handling GUI-Generated Events” Creating a layout of GUI components in a frame is not enough. You must write code to handle the events that occur, such as clicking a button or typing a character. This module demonstrates how to write GUI event handlers. Preface-xx Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  20. 20. Topics Not Covered Topics Not Covered This course does not cover the following topics. Many of these topics are covered in other courses offered by Sun Educational Services: ● Object-oriented analysis and design – Covered in OO-226: Object-Oriented Application Analysis and Design Using UML ● General programming concepts – Covered in SL-110: Fundamentals of the Java™ Programming Language Refer to the Sun Educational Services catalog for specific information and registration. About This Course Preface-xxi Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  21. 21. How Prepared Are You? How Prepared Are You? To be sure you are prepared to take this course, can you answer yes to the following questions? Before attending this course, you should have completed SL-110: Fundamentals of the Java™ Programming Language, or have: ● Created and compiled programs with C or C++ ● Created and edited text files using a text editor ● Used a World Wide Web (WWW) browser, such as Netscape Navigator™ Preface-xxii Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  22. 22. Introductions Introductions Now that you have been introduced to the course, introduce yourself to the other students and the instructor, addressing the following items: ● Name ● Company affiliation ● Title, function, and job responsibility ● Experience related to topics presented in this course ● Reasons for enrolling in this course ● Expectations for this course About This Course Preface-xxiii Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  23. 23. How to Use Course Materials How to Use Course Materials To enable you to succeed in this course, these course materials contain a learning module that is composed of the following components: ● Goals – You should be able to accomplish the goals after finishing this course and meeting all of its objectives. ● Objectives – You should be able to accomplish the objectives after completing a portion of instructional content. Objectives support goals and can support other higher-level objectives. ● Lecture – The instructor presents information specific to the objective of the module. This information helps you learn the knowledge and skills necessary to succeed with the activities. ● Activities – The activities take various forms, such as an exercise, self-check, discussion, and demonstration. Activities help you facilitate the mastery of an objective. ● Visual aids – The instructor might use several visual aids to convey a concept, such as a process, in a visual form. Visual aids commonly contain graphics, animation, and video. Preface-xxiv Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  24. 24. Conventions Conventions The following conventions are used in this course to represent various training elements and alternative learning resources. Icons Additional resources – Indicates other references that provide additional information on the topics described in the module. Discussion – Indicates a small-group or class discussion on the current topic is recommended at this time. ! ? Note – Indicates additional information that can help students but is not crucial to their understanding of the concept being described. Students should be able to understand the concept or complete the task without this information. Examples of notational information include keyword shortcuts and minor system adjustments. About This Course Preface-xxv Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  25. 25. Conventions Typographical Conventions Courier is used for the names of commands, files, directories, programming code, and on-screen computer output; for example: Use ls -al to list all files. system% You have mail. Courier is also used to indicate programming constructs, such as class names, methods, and keywords; for example: The getServletInfo method is used to get author information. The java.awt.Dialog class contains Dialog constructor. Courier bold is used for characters and numbers that you type; for example: To list the files in this directory, type: # ls Courier bold is also used for each line of programming code that is referenced in a textual description; for example: 1 import java.io.*; 2 import javax.servlet.*; 3 import javax.servlet.http.*; Notice the javax.servlet interface is imported to allow access to its life-cycle methods (Line 2). Courier italics is used for variables and command-line placeholders that are replaced with a real name or value; for example: To delete a file, use the rm filename command. Courier italic bold is used to represent variables whose values are to be entered by the student as part of an activity; for example: Type chmod a+rwx filename to grant read, write, and execute rights for filename to world, group, and users. Palatino italics is used for book titles, new words or terms, or words that you want to emphasize; for example: Read Chapter 6 in the User’s Guide. These are called class options. Preface-xxvi Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  26. 26. Conventions Additional Conventions Java programming language examples use the following additional conventions: ● Method names are not followed with parentheses unless a formal or actual parameter list is shown; for example: “The doIt method...” refers to any method called doIt. “The doIt() method...” refers to a method called doIt that takes no arguments. ● Line breaks occur only where there are separations (commas), conjunctions (operators), or white space in the code. Broken code is indented four spaces under the starting code. ● If a command used in the Solaris™ Operating System (Solaris OS) is different from a command used in the Microsoft Windows platform, both commands are shown; for example: In the Solaris OE: $CD SERVER_ROOT/BIN In Microsoft Windows: C:>CD SERVER_ROOTBIN About This Course Preface-xxvii Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  27. 27. Module 1 Executing Your First Java Application Objectives Upon completion of this module, you should be able to: ● Examine the Java Development Kit (JDK™) software ● Examine Java application loading and executing ● Create a simple Java application 1-1 Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  28. 28. Additional Resources Additional Resources Additional resources – The following reference provides additional information on the topics described in this module: ● Gosling, Joy, Bracha, and Steele. The Java Language Specification, Third Edition. Prentice-Hall. 2005. [Also online at: http://java.sun.com/docs/books/jls/]. accessed May 1, 2007. 1-2 Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  29. 29. Examining the JDK Software Examining the JDK Software The JDK software contains the components you need to perform the following tasks: ● Develop Java technology applications ● Deploy Java technology applications ● Execute Java technology applications: Figure 1-1 provides an overview of the JDK software. It shows the components of the JDK and the activities with which they are associated. Java Programming Language Application Tools and Tools API development Java SE Libraries JDK Application Deployment Technologies deployment Platform Specific JVMs Application execution Figure 1-1 The Java SE JDK Overview The JDK consists of the following components ● The Java programming language ● Tools and tools API ● Deployment technologies ● Java Platform, Standard Edition (Java SE) libraries ● Virtual Machine for the Java platform (Java Virtual Machine (JVM™)) Note – Strictly speaking, the Java programming language is not a component of the JDK software. However, it is included in the discussion of the JDK software on the basis that the JDK is primarily provided to support Java programming language-based application development. To use the JDK, you need to download and install both the JDK software and the associated JDK documentation on your development platform. The following URL contains the instructions to download and install both the JDK software and the associated JDK documentation. http://java.sun.com/javase/downloads/index.jsp Executing Your First Java Application 1-3 Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  30. 30. Examining the JDK Software Examining the JDK Software Support for Developing Java Applications The following JDK components are provided to support the development of Java technology applications: ● The Java programming language ● The JDK tools ● The JDK libraries The Java Programming Language The Java Programming Language is a general-purpose, concurrent, strongly typed, class-based object-oriented language. The Java programming language is defined by the Java language specification. The primary building block of a Java technology application is a class. The language specification specifies the language syntax for all Java language constructs including that of a class. Code 1-1 shows an example of a Java technology class. Code 1-1 Example of a Java Technology Class 1 package trader; 2 import java.io.Serializable; 3 public class Stock implements Serializable { 4 private String symbol; 5 private float price; 6 7 public Stock(String symbol, float price){ 8 this.symbol = symbol; 9 this.price = price; 10 } 11 12 // Methods to return the private values of this object 13 public String getSymbol() { 14 return symbol; 15 } 16 17 public float getPrice() { 18 return price; 19 } 20 21 public void setPrice(float newPrice) { 22 price = newPrice; 1-4 Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  31. 31. Examining the JDK Software 23 } 24 25 public String toString() { 26 return "Stock: " + symbol + " " + price; 27 } 28 } The JDK Tools and Tools API Figure 1-2 highlights the tools and tool categories available with the Java SE JDK. Figure 1-2 The Java SE JDK With the Java SE Tools Highlighted Executing Your First Java Application 1-5 Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  32. 32. Examining the JDK Software The JDK tools provide support for the development and deployment of Java technology applications. The JDK tools can be classified into two categories. ● Basic tools These tools are the tools you use to create, build, and execute Java technology applications. Table 1-1 lists the tools from this group that you are could encounter in the early stages of learning to program using Java technology. Table 1-1 Java SE Basic Tools: A Sample Selection Tool Name Function javac The compiler for the Java programming language java The launcher for Java technology applications jdb The Java debugger javadoc The API document generator jar Java Archive (JAR) file creator and management tool ● Advanced user tools The advanced user tools consist of several categories of tools. Each category helps you leverage a particular technology when creating a Java technology application. Table 1-2 lists the advanced tool categories. Table 1-2 Advanced Tool Categories Tool Category Comment Security tools Help you create applications that work with security policies. Internationalization tools Help create applications that can be localized. Remote method invocation Help create applications that work across a (RMI) tools network. Common object request Help create network applications that are based on broker architecture (CORBA) CORBA technology. tools Java deployment tools Provide compression and decompression functionality that assist with the deployment of Java technology applications. 1-6 Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  33. 33. Examining the JDK Software Table 1-2 Advanced Tool Categories Tool Category Comment Java Plug-in tools Utilities for use with the Java Plug-in. Java web start tools Utilities for use with Java web start technology. Java Monitoring and Used in conjunction with JMX technology. Management (JMX) console Java web services tools Support the development of Java web service applications. Experimental tools These tools are experimental and might not be available with future releases of the Java SE JDK. Note – The JDK tools API is a set of libraries and accompanying documentation that enables the creation of custom tools. A discussion of this API is beyond the scope of this module. For more information, refer to the Java Platform Debugger Architecture (JPDA) documentation section of the JDK documentation. Executing Your First Java Application 1-7 Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  34. 34. Examining the JDK Software JDK Libraries The JDK libraries consist of predefined data types known as classes. These classes are grouped on the basis of functionality into libraries. In Java technology, a library is called a package. Figure 1-3 highlights the libraries available with the Java SE JDK. Figure 1-3 The Java SE JDK With the Java SE Libraries Highlighted The major library groupings can be categorized as follows: ● User interface toolkits The user interface toolkits consist of a set of libraries that contain the classes necessary to create graphical user interfaces (GUI). These libraries range from libraries that provide GUI widgets (buttons, labels, tab panes, and so on) to libraries that support drag and drop, sound, accessibility, input, and printing. ● Integration libraries The integration libraries provide support for the use of various network technologies that enable the integration of distributed applications. These network technologies include RMI, CORBA, Java™ DataBase Connectivity (JDBC™), and Java Naming and Directory Interface™ (JNDI) API. 1-8 Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  35. 35. Examining the JDK Software ● Other base libraries This is a general grouping of base-level libraries. This grouping includes the security, internationalization, Java™ Management Extensions (JMX™) and other similar libraries. ● Language and utilities base libraries This grouping consists of the core libraries required to create an application. At the core are the lang and util libraries. Other libraries included in this group are for concurrency (enabling the creation of multithreaded applications), logging, and management. Table 1-3 lists a small selection of the standard libraries and a sample of classes from the selected libraries. Table 1-3 Sample Selection of Standard Libraries and Classes Library Name Sample Classes in Library Purpose java.lang Enum, Float, String, Fundamental classes of the Java Object programming language java.util ArrayList, Calendar, Date Utility classes java.io File, Reader, Writer Input and output support classes java.math BigDecimal, BigInteger Arbitrary precision maths support classes java.text DateFormat, Collator Text handling and formatting support classes javax.crypto Cipher, KeyGenerator Cryptography support classes java.net Socket, URL, InetAddress Networking support classes java.sql ResultSet, Date, Structured Query Language Timestamp (SQL) support classes. javax.swing JFrame, JPanel Graphical user interface (GUI) classes javax.xml.parsers DocumentBuilder, Extensible Markup Language SAXParser (XML) support classes Executing Your First Java Application 1-9 Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  36. 36. Examining the JDK Software Documentation for the JDK library classes (also known as Java technology API documentation) is supplied as a set of HTML files. The layout of this documentation is hierarchical, so that the home page lists all the packages as hyperlinks. When you select a particular package hotlink, the classes that are members of that package are listed. Selecting a class hotlink from a package page presents a page of information about that class. Figure 1-4 shows one such class. Figure 1-4 Java Technology API Documentation 1-10 Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  37. 37. Examining the JDK Software The main sections of a class document include the following: ● The class hierarchy ● A description of the class and its general purpose ● A list of attributes ● A list of constructors ● A list of methods ● A detailed list of attributes with descriptions ● A detailed list of constructors with descriptions and formal parameter lists ● A detailed list of methods with descriptions and formal parameter lists Executing Your First Java Application 1-11 Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  38. 38. Examining the JDK Software JDK Deployment Technologies Figure 1-5 highlights the deployment technologies available with the JDK software. Figure 1-5 The Java SE JDK With Deployment Technologies Highlighted The JDK software contains support for deployment of client-side Java applications on the desktop. This support is provided by the following two types of deployment technologies. ● Java Plug-in Java Plug-in is a tool used for deploying Java applets that run inside a web browser. Supported web browsers include Internet Explorer, Mozilla, and Netscape Navigator. Note – A Java applet is a restricted Java application that executes in a browser. ● Java Web Start Java Web Start is a tool used for deploying standalone Java applications on the desktop using the Java Network Launching Protocol (JNLP). 1-12 Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  39. 39. Examining the JDK Software The Java Virtual Machine (JVM) This section provides an introduction to the JVM implementation by using an Frequently Asked Questions (FAQ) format to highlight the information you need to know. ● What is a JVM implementation? A JVM implementation executes Java technology applications, which consist of compiled Java classes. Compiled Java classes consist of byte code, so to be precise, a JVM implementation loads the classes that compose a Java technology application and executes the byte code contained in the classes. Figure 1-6 illustrates the relationship between a Java technology application, the JVM implementation, the operating system (OS) and the hardware platform. Java Technology Application JVM OS Hardware Platform Figure 1-6 The JVM Implementation, the Application, and the OS ● Are JVM implementations platform dependent? JVM implementations are platform specific. For example, to execute a Java application on a Solaris OS, you need the JVM implementation that is specific to the Solaris OS. Similarly, to execute a Java technology application on a Windows OS, you need the JVM implementation that is specific to the Windows OS. ● Are Java technology applications platform dependent? An application written using the Java programming language is platform independent. Such an application can run on any platform that contains a supporting JVM implementation. Executing Your First Java Application 1-13 Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  40. 40. Examining the JDK Software ● What is a Java HotSpot™ virtual machine? The first generation of JVM implementations interpreted byte code. The latest generation of JVM implementations compile the byte code ahead of its execution. This delayed dynamic compiling enables a high level of optimization and performance improvements over statically compiled languages. The JVM compiler dynamically identifies repeatedly executed blocks of code known as hotspots and pays particular attention to the optimization of the byte codes in these hotspots. Hence the terminology hotspot JVM. ● What is a Java Hotspot™ Client VM? On platforms typically used for client applications, the JDK software comes with a virtual machine (VM) implementation called the Java Hotspot Client VM (client VM). The client VM is tuned for reducing start-up time and memory footprint. ● What is a Java Hotspot Server VM? On all platforms, the JDK software comes with an implementation of the Java virtual machine called the Java Hotspot Server VM (server VM). The server VM is designed for maximum program execution speed. Figure 1-3 highlights the JVM implementations and supported platforms available for the JDK software. Figure 1-7 The JDK Software Highlighting the JVM Implementations and Supported Platforms 1-14 Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  41. 41. Examining the JDK Software The Java™ Runtime Environment (JRE™) The JRE™ software is a subset of the JDK software and contains all the components of the JDK that are required to execute a Java technology application. It does not contain the components of the JDK required to develop a Java technology application. Figure 1-8 shows the components that are common to both the JDK and the JRE. Figure 1-8 Comparing the JDK With the JRE Executing Your First Java Application 1-15 Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  42. 42. Examining Java Application Loading and Execution Examining Java Application Loading and Execution Figure 1-9 illustrates the loading and execution of a Java application by the JVM implementation. Compile Runtime java Class loader TestGreeting.java Load from Bytecode javac hard disk, verifier network, or other source Hotspot Execution Engine Hardware TestGreeting.class Figure 1-9 Operation of the JRE Java software source files are compiled in the sense that they are converted into a set of byte codes from the text format in which you write them. The byte codes are stored in .class files. At runtime, the byte codes that make up a Java program are loaded, checked, and run by the Java HotSpot execution engine. In the case of applets, you can download the byte codes, and then they are executed by the JVM implementation built into the browser. The following section provides a more comprehensive discussion of the three main tasks performed by the JVM implementation: ● Loads code – Performed by the class loader ● Verifies code – Performed by the byte-code verifier ● Executes code – Performed by the execution engine 1-16 Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  43. 43. Examining Java Application Loading and Execution The Class Loader The class loader loads all classes needed for the execution of a program. The class loader adds security by separating the namespaces for the classes of the local file system from those imported from network sources. This limits any Trojan Horse applications, because local classes are always loaded first. After all of the classes have been loaded, the memory layout of the executable file is determined. At this point, specific memory addresses are assigned to symbolic references and the lookup table is created. Because memory layout occurs at runtime, the Java technology interpreter adds protection against unauthorized access into the restricted areas of code. The Byte-Code Verifier Java software code passes several tests before running on your machine. The JVM implementation puts the code through a byte-code verifier that tests the format of the code fragments and checks code fragments for illegal code, which is code that forges pointers, violates access rights on objects, or attempts to change object type. Note – All class files imported across the network pass through the byte- code verifier. Verification Process The byte-code verifier makes four passes on the code in a program. It ensures that the code adheres to the JVM specifications and does not violate system integrity. If the verifier completes all four passes without returning an error message, then the following is ensured: ● The classes adhere to the class file format of the JVM specification. ● There are no access restriction violations. ● The code causes no operand stack overflows or underflows. ● The types of parameters for all operational codes are correct. ● No illegal data conversions, such as converting integers to object references, have occurred. Executing Your First Java Application 1-17 Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  44. 44. Creating a Simple Java Application Creating a Simple Java Application Like any other programming language, you use the Java programming language to create applications. Code 1-2 and Code 1-3 show how to create a simple Java application that prints a greeting to the world. Code 1-2 The TestGreeting.java Application 1 // 2 // Sample "Hello World" application 3 // 4 public class TestGreeting { 5 public static void main (String[] args) { 6 Greeting hello = new Greeting(); 7 hello.greet(); 8 } 9 } Code 1-3 The Greeting.java Class 1 public class Greeting { 2 public void greet() { 3 System.out.println("hi"); 4 } 5 } 1-18 Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  45. 45. Creating a Simple Java Application The TestGreeting Application This section describes the TestGreeting application. Code 1-4 shows lines 1 to 3 of the sample application. Code 1-4 Lines 1 to 3 1 // 2 // Sample "Hello World" application 3 // Lines 1 to 3 in the program are comment lines, indicated by the //. Code 1-5 Line 4 4 public class TestGreeting { Line 4 declares the class name as TestGreeting. A class name specified in a source file creates a classname.class file when the source file is compiled. If you do not specify a target directory for the compiler to use, this class file is in the same directory as the source code. In this case, the compiler creates a file called TestGreeting.class. It contains the compiled code for the public class TestGreeting. Code 1-6 Line 5 5 public static void main (String args[]) { Line 5 is where the program starts to execute. The Java technology interpreter must find this defined exactly as given or it refuses to run the program. Other programming languages, notably C and C++, also use the main() declaration as the starting point for execution. The various parts of this declaration are briefly described here. The details are covered later in this course. If the program is given any arguments on its command line, these are passed into the main() method in an array of String called args. In this example, no arguments are used. The following describes each element of Line 5: Executing Your First Java Application 1-19 Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  46. 46. Creating a Simple Java Application ● public – The method main() can be accessed by anything, including the Java technology interpreter. ● static – This keyword tells the compiler that the main() method is usable in the context of the class TestGreeting. No instance of the class is needed to execute static methods. ● void – This keyword indicates that the method main() does not return any value. This is important because the Java programming language performs careful type-checking to confirm that the methods called return the types with which they were declared. ● String args[] – This method declares the single parameter to the main method, args, and has the type of a String array. When this method is called, the args parameter contains the arguments typed on the command line following the class name; for example: java TestGreeting args[0] args[1] . . . Code 1-7 Line 6 6 Greeting hello = new Greeting(); Line 6 illustrates how to create an object, referred to by the hello variable. The new Greeting syntax tells the Java technology interpreter to construct a new object of the class Greeting. Code 1-8 Line 7 7 hello.greet(); Lines 7 demonstrates an object method call. This call tells the hello object to greet the world. The implementation of this method is shown on Lines 3–5 of the Greeting.java file. Code 1-9 Lines 8 and 9 8 } 9 } Lines 8 and 9 of the program, the two braces, close the method main() and the class TestGreeting, respectively. 1-20 Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  47. 47. Creating a Simple Java Application The Greeting Class This section describes the Greeting class. Code 1-10 Line 1 1 public class Greeting { Line 1 declares the Greeting class. Code 1-11 Lines 2 to 4 2 public void greet() { 3 System.out.println(“hi”); 4 } Lines 2 to 4 demonstrate the declaration of a method. This method is declared public, making it accessible to the TestGreeting program. It does not return a value, so void is used as the return type. The greet method sends a string message to the standard output stream. The println() method is used to write this message to the standard output stream. Code 1-12 Line 5 5 } Line 5 closes the class declaration for the Greeting class. Executing Your First Java Application 1-21 Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  48. 48. Creating a Simple Java Application Compiling and Running the TestGreeting Program After you have created the TestGreeting.java source file, compile it by typing the following line: javac TestGreeting.java If the compiler does not return any messages, the new file TestGreeting.class is stored in the same directory as the source file, unless specified otherwise. The Greeting.java file has been compiled into Greeting.class. This is done automatically by the compiler because the TestGreeting class uses the Greeting class. To run your TestGreeting application, use the Java technology interpreter. The executables for the Java technology tools (javac, java, javadoc, and so on) are located in the bin directory. java TestGreeting Note – You must set the PATH environment variable to find java and javac; ensure that it includes java_root/bin (where java_root represents the directory root where the Java technology software is installed). 1-22 Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  49. 49. Creating a Simple Java Application Troubleshooting the Compilation The following sections describe errors that you might encounter when compiling code. Compile-Time Errors The following are common errors seen at compile time, with examples of compiler-generated messages. Your messages can vary depending on which version of the JDK you are using. ● javac: Command not found The PATH variable is not set properly to include the javac compiler. The javac compiler is located in the bin directory below the installed JDK software directory. ● Greeting.java:4:cannot resolve symbol symbol : method printl (java.lang.String) location: class java.io.PrintStream System.out.printl("hi"); ^ The method name println is typed incorrectly. ● Class and file naming If the .java file contains a public class, then it must have the same file name as that class. For example, the definition of the class in the previous example is: public class TestGreeting The name of the source file must be TestGreeting.java. If you named the file TestGreet.java, then you would get the error message: TestGreet.java:4: Public class TestGreeting must be defined in a file called "TestGreeting.java". ● Class count You should declare only one top-level, non-static class to be public in each source file, and it must have the same name as the source file. If you have more than one public class, then you will get the same message as in the previous bullet for every public class in the file that does not have the same name as the file. Executing Your First Java Application 1-23 Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G
  50. 50. Creating a Simple Java Application Runtime Errors Some of the errors generated when typing java TestGreeting are: ● Can't find class TestGreeting Generally, this means that the class name specified on the command line was spelled differently than the filename.class file. The Java programming language is case-sensitive. For example, public class TestGreet { creates a TestGreet.class, which is not the class name (TestGreeting.class) that the runtime expected. ● Exception in thread "main" java.lang.NoSuchMethodError: main This means that the class you told the interpreter to execute does not have a static main method. There might be a main method, but it might not be declared with the static keyword or it might have the wrong parameters declared, such as: public static void main(String args) { In this example, args is a single string, not an array of strings. public static void main() { In this example, the coder forgot to include any parameter list. 1-24 Java™ Programming Language Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision G

×