Top Banner
© 2013 ITCourseware, LLC Rev 5.3.1 Page iii Java Programming Contents Chapter 1 - Course Introduction ........................................................................................................... 11 Course Objectives .......................................................................................................................... 12 Course Overview ........................................................................................................................... 14 Using the Workbook ...................................................................................................................... 15 Suggested References ..................................................................................................................... 16 Chapter 2 - Getting Started with Java .................................................................................................... 19 What is Java? ................................................................................................................................. 20 How to Get Java ............................................................................................................................ 22 A First Java Program ...................................................................................................................... 24 Compiling and Interpreting Applications ........................................................................................... 26 The JSDK Directory Structure ........................................................................................................ 28 Labs ............................................................................................................................................... 30 Chapter 3 - Eclipse ............................................................................................................................... 33 Introduction to Eclipse .................................................................................................................... 34 Installing Eclipse ............................................................................................................................ 36 Running Eclipse for the First Time .................................................................................................... 38 Editors, Views, and Perspectives ..................................................................................................... 40 Setting up a Project ........................................................................................................................ 42 Creating a New Java Application .................................................................................................... 44 Running a Java Application .............................................................................................................. 46 Debugging a Java Application .......................................................................................................... 48 Importing Existing Java Code into Eclipse ........................................................................................ 50 Chapter 4 - Language Fundamentals ..................................................................................................... 53 A Java Program .............................................................................................................................. 54 If Statements .................................................................................................................................. 56 Switch Statements .......................................................................................................................... 58 Loop Statements ............................................................................................................................ 60 Syntax Details ................................................................................................................................. 62 Primitive Datatypes ......................................................................................................................... 64 Variables ........................................................................................................................................ 66 Expressions in Java ......................................................................................................................... 68 EVALUATION COPY Unauthorized reproduction or distribution is prohibited.
42

Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Apr 10, 2018

Download

Documents

ledien
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

© 2013 ITCourseware, LLC Rev 5.3.1 Page iii

Java Programming

Contents

Chapter 1 - Course Introduction ........................................................................................................... 11

Course Objectives .......................................................................................................................... 12Course Overview ........................................................................................................................... 14Using the Workbook ...................................................................................................................... 15Suggested References ..................................................................................................................... 16

Chapter 2 - Getting Started with Java .................................................................................................... 19

What is Java? ................................................................................................................................. 20How to Get Java ............................................................................................................................ 22A First Java Program ...................................................................................................................... 24Compiling and Interpreting Applications ........................................................................................... 26The JSDK Directory Structure ........................................................................................................ 28Labs ............................................................................................................................................... 30

Chapter 3 - Eclipse ............................................................................................................................... 33

Introduction to Eclipse .................................................................................................................... 34 Installing Eclipse ............................................................................................................................ 36Running Eclipse for the First Time .................................................................................................... 38Editors, Views, and Perspectives ..................................................................................................... 40Setting up a Project ........................................................................................................................ 42Creating a New Java Application .................................................................................................... 44Running a Java Application .............................................................................................................. 46Debugging a Java Application .......................................................................................................... 48Importing Existing Java Code into Eclipse ........................................................................................ 50

Chapter 4 - Language Fundamentals ..................................................................................................... 53

A Java Program .............................................................................................................................. 54If Statements .................................................................................................................................. 56Switch Statements .......................................................................................................................... 58Loop Statements ............................................................................................................................ 60Syntax Details ................................................................................................................................. 62Primitive Datatypes ......................................................................................................................... 64Variables ........................................................................................................................................ 66Expressions in Java ......................................................................................................................... 68

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 2: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Page iv Rev 5.3.1 © 2015 ITCourseware, LLC

Java Programming

Strings ............................................................................................................................................ 70Arrays ............................................................................................................................................ 72Enhanced for Loop ......................................................................................................................... 74Labs ............................................................................................................................................... 76

Chapter 5 - Objects and Classes .......................................................................................................... 79

Defining a Class .............................................................................................................................. 80Creating an Object ......................................................................................................................... 82Instance Data and Class Data ......................................................................................................... 84Methods ......................................................................................................................................... 86Constructors ................................................................................................................................... 88Access Modifiers ............................................................................................................................ 90Encapsulation ................................................................................................................................. 92Labs ............................................................................................................................................... 94

Chapter 6 - Using Java Objects ............................................................................................................ 97

Printing to the Console .................................................................................................................... 98printf Format Strings ..................................................................................................................... 100StringBuilder and StringBuffer ....................................................................................................... 102Methods and Messages ................................................................................................................ 104toString ........................................................................................................................................ 106Comparing and Identifying Objects ............................................................................................... 108Parameter Passing ........................................................................................................................ 110Destroying Objects ....................................................................................................................... 112The Primitive-Type Wrapper Classes ............................................................................................ 114Enumerated Types ........................................................................................................................ 116Labs ............................................................................................................................................. 118

Chapter 7 - Inheritance in Java ............................................................................................................ 121

Inheritance .................................................................................................................................... 122Inheritance in Java ........................................................................................................................ 124Casting ......................................................................................................................................... 126Method Overriding ....................................................................................................................... 128Polymorphism ............................................................................................................................... 130super ............................................................................................................................................ 132The Object Class .......................................................................................................................... 134Labs ............................................................................................................................................. 136

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 3: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

© 2013 ITCourseware, LLC Rev 5.3.1 Page v

Java Programming

Chapter 8 - Advanced Inheritance and Generics .................................................................................. 139

Abstract Classes ........................................................................................................................... 140Interfaces ..................................................................................................................................... 142Using Interfaces ............................................................................................................................ 144Collections ................................................................................................................................... 146Generics ....................................................................................................................................... 148Comparable ................................................................................................................................. 150Labs ............................................................................................................................................. 152

Chapter 9 - Packages ......................................................................................................................... 155

Packages ...................................................................................................................................... 156The import Statement .................................................................................................................... 158Static Imports ............................................................................................................................... 160CLASSPATH and Import ............................................................................................................. 162Defining Packages ........................................................................................................................ 164Package Scope ............................................................................................................................ 166Labs ............................................................................................................................................. 168

Chapter 10 - Exception Handling ........................................................................................................ 171

Exceptions Overview .................................................................................................................... 172Catching Exceptions ..................................................................................................................... 174The finally Block ........................................................................................................................... 176Exception Methods ....................................................................................................................... 178Declaring Exceptions .................................................................................................................... 180Defining and Throwing Exceptions ................................................................................................. 182Errors and RuntimeExceptions ...................................................................................................... 184Labs ............................................................................................................................................. 186

Chapter 11 - Input/Output Streams ..................................................................................................... 189

Overview of Streams .................................................................................................................... 190Bytes vs. Characters ..................................................................................................................... 192Converting Byte Streams to Character Streams ............................................................................. 194File Object ................................................................................................................................... 196Binary Input and Output ................................................................................................................ 198PrintWriter Class .......................................................................................................................... 200Reading and Writing Objects ......................................................................................................... 202Closing Streams ............................................................................................................................ 204

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 4: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Page vi Rev 5.3.1 © 2015 ITCourseware, LLC

Java Programming

Labs ............................................................................................................................................. 206

Chapter 12 - Core Collection Classes ................................................................................................. 209

The Collections Framework .......................................................................................................... 210The Set Interface .......................................................................................................................... 212Set Implementation Classes ........................................................................................................... 214The List Interface .......................................................................................................................... 216List Implementation Classes .......................................................................................................... 218The Queue Interface ..................................................................................................................... 220Queue Implementation Classes ...................................................................................................... 222The Map Interface ........................................................................................................................ 224Map Implementation Classes ........................................................................................................ 226Labs ............................................................................................................................................. 228

Chapter 13 - Collection Sorting and Tuning ......................................................................................... 231

Sorting with Comparable .............................................................................................................. 232Sorting with Comparator ............................................................................................................... 234Sorting Lists and Arrays ................................................................................................................ 236Collections Utility Methods ........................................................................................................... 238Tuning ArrayList ........................................................................................................................... 240Tuning HashMap and HashSet ...................................................................................................... 242Labs ............................................................................................................................................. 244

Chapter 14 - Inner Classes ................................................................................................................. 247

Inner Classes ................................................................................................................................ 248Member Classes ........................................................................................................................... 250Local Classes ............................................................................................................................... 252Anonymous Classes ...................................................................................................................... 254Instance Initializers ........................................................................................................................ 256Static Nested Classes ................................................................................................................... 258Labs ............................................................................................................................................. 260

Chapter 15 - Introduction to Swing ..................................................................................................... 263

AWT and Swing ........................................................................................................................... 264Displaying a Window .................................................................................................................... 266GUI Programming in Java ............................................................................................................. 268

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 5: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

© 2013 ITCourseware, LLC Rev 5.3.1 Page vii

Java Programming

Handling Events ............................................................................................................................ 270Arranging Components ................................................................................................................. 272A Scrollable Component ............................................................................................................... 274Configuring Components .............................................................................................................. 276Menus .......................................................................................................................................... 278Using the JFileChooser ................................................................................................................. 280Labs ............................................................................................................................................. 282

Chapter 16 - Swing Events and Layout Managers ............................................................................... 285

The Java Event Delegation Model ................................................................................................. 286Action Events ............................................................................................................................... 288List Selection Events ..................................................................................................................... 290Mouse Events ............................................................................................................................... 292Layout Managers .......................................................................................................................... 294BorderLayout ............................................................................................................................... 296FlowLayout .................................................................................................................................. 298GridLayout ................................................................................................................................... 300BoxLayout ................................................................................................................................... 302Box .............................................................................................................................................. 304JTabbedPane ................................................................................................................................ 306Labs ............................................................................................................................................. 308

Chapter 17 - Introduction to JDBC ..................................................................................................... 311

The JDBC Connectivity Model ..................................................................................................... 312Database Programming ................................................................................................................. 314Connecting to the Database .......................................................................................................... 316Creating a SQL Query .................................................................................................................. 318Getting the Results ........................................................................................................................ 320Updating Database Data ............................................................................................................... 322Finishing Up ................................................................................................................................. 324Labs ............................................................................................................................................. 326

Chapter 18 - JDBC SQL Programming ............................................................................................... 329

Error Checking and the SQLException Class ................................................................................ 330The SQLWarning Class ................................................................................................................ 332JDBC Types ................................................................................................................................. 334Executing SQL Queries ................................................................................................................. 336

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 6: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Page viii Rev 5.3.1 © 2015 ITCourseware, LLC

Java Programming

ResultSetMetaData ....................................................................................................................... 338Executing SQL Updates ................................................................................................................ 340Using a PreparedStatement ........................................................................................................... 342Parameterized Statements ............................................................................................................. 344Stored Procedures ........................................................................................................................ 346Transaction Management .............................................................................................................. 348Labs ............................................................................................................................................. 350

Appendix A - Introduction to Threads ................................................................................................. 353

Non-Threaded Applications .......................................................................................................... 354Threaded Applications .................................................................................................................. 356Creating Threads .......................................................................................................................... 358Thread States ............................................................................................................................... 360Runnable Threads ......................................................................................................................... 362Coordinating Threads ................................................................................................................... 364Interrupting Threads ...................................................................................................................... 366Runnable Interface ........................................................................................................................ 368ThreadGroups .............................................................................................................................. 370Labs ............................................................................................................................................. 372

Appendix B - Thread Synchronization and Concurrency ...................................................................... 375

Race Conditions ........................................................................................................................... 376Synchronized Methods ................................................................................................................. 378Deadlocks .................................................................................................................................... 380Synchronized Blocks .................................................................................................................... 382Synchronized Collections .............................................................................................................. 384Thread-Aware Collections ............................................................................................................ 386Thread Communication — wait() .................................................................................................. 388Thread Communication — notify() ................................................................................................ 390Executor ....................................................................................................................................... 392Callable ........................................................................................................................................ 394Labs ............................................................................................................................................. 396

Appendix C - Advanced JDBC .......................................................................................................... 399

JDBC SQL Escape Syntax ........................................................................................................... 400The execute() Method .................................................................................................................. 402Batch Updates .............................................................................................................................. 404Updatable Result Sets ................................................................................................................... 406Large Objects .............................................................................................................................. 408

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 7: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

© 2013 ITCourseware, LLC Rev 5.3.1 Page ix

Java Programming

Working with Savepoints .............................................................................................................. 410RowSets ...................................................................................................................................... 412CachedRowSet ............................................................................................................................ 414DataSources ................................................................................................................................. 416Labs ............................................................................................................................................. 418

Appendix D - Eclipse Shortcuts .......................................................................................................... 421

Shortcut Key Sequences ............................................................................................................... 422More Shortcut Key Sequences ..................................................................................................... 424

Index .................................................................................................................................................. 427

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 8: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Page x Rev 5.3.1 © 2015 ITCourseware, LLC

Java Programming

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 9: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Course IntroductionChapter 1

© 2015 ITCourseware, LLC Rev 5.3.1 Page 11

Chapter 1 - Course IntroductionEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 10: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 12 Rev 5.3.1 ©2015 ITCourseware, LLC

Write stand-alone applications using the Java language.

Accurately implement Object-Oriented concepts using Java features, such asclasses, interfaces, and references.

Create well-scoped classes using packages and inner classes.

Write programs which both handle and create exceptions.

Read and write data, using input and output streams.

Use the Java Collections Framework to work with groups of objects.

Use the java.awt and javax.swing packages to create GUI applications.

Write Java programs that interface with databases via JDBC.

Course ObjectivesEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 11: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Course IntroductionChapter 1

© 2015 ITCourseware, LLC Rev 5.3.1 Page 13

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 12: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC

Audience: This is a programming course designed for software developmentprofessionals who wish to write Java applications. You will write many programsin this class.

Prerequisites: Programming experience in C, C#, or C++ is required.Knowledge of Object-Oriented concepts is required.

Classroom Environment:

One Java development environment per student.

DBMS Server.

Course OverviewEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 13: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Course IntroductionChapter 1

© 2015 ITCourseware, LLC Rev 5.3.1 Page 15

Using the Workbook

Chapter 2 Servlet Basics

© 2002 ITCourseware, LLC Rev 2.0.0 Page 17

Add an init() method to your Today servlet that initializes a bornOn date, then print the bornOn date

along with the current date:

Today.java

...

public class Today extends GenericServlet {

private Date bornOn;

public void service(ServletRequest request,

ServletResponse response) throws ServletException, IOException

{

...

// Write the document

out.println("This servlet was born on " + bornOn.toString());

out.println("It is now " + today.toString());

}

public void init() {

bornOn = new Date();

}

}

Hands On:

The init() method is

called when the servlet is

loaded into the container.

This workbook design is based on a page-pair, consisting of a Topic page and a Support page. When youlay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topicpage contains the points to be discussed in class. The Support page has code examples, diagrams, screenshots and additional information. Hands On sections provide opportunities for practical application of keyconcepts. Try It and Investigate sections help direct individual discovery.

In addition, there is an index for quick look-up. Printed lab solutions are in the back of the book as well ason-line if you need a little help.

Java Servlets

Page 16 Rev 2.0.0 © 2002 ITCourseware, LLC

� The servlet container controls the life cycle of the servlet.

� When the first request is received, the container loads the servlet class

and calls the init() method.

� For every request, the container uses a separate thread to call

the service() method.

� When the servlet is unloaded, the container calls the destroy()

method.

� As with Java’s finalize() method, don’t count on this being

called.

� Override one of the init() methods for one-time initializations, instead of

using a constructor.

� The simplest form takes no parameters.

public void init() {...}

� If you need to know container-specific configuration information, use

the other version.

public void init(ServletConfig config) {...

� Whenever you use the ServletConfig approach, always call the

superclass method, which performs additional initializations.

super.init(config);

The Servlet Life Cycle

The Topic page providesthe main topics for

classroom discussion.

The Support page hasadditional information,

examples and suggestions.

Code examples are in afixed font and shaded. Theon-line file name is listedabove the shaded area.

Screen shots showexamples of what youshould see in class.

Topics are organized intofirst ( ), second ( ) and

third ( ) level points.

Pages are numberedsequentially throughout

the book, making lookupeasy.

Callout boxes point outimportant parts of the

example code.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 14: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 16 Rev 5.3.1 ©2015 ITCourseware, LLC

Arnold, Ken, James Gosling, and David Holmes. 2013. The Java Programming Language (5thEdition). Addison-Wesley, Reading, MA. ISBN 978-0132761680.

Bloch, Joshua. 2008. Effective Java (2nd Edition). Addison-Wesley, Reading, MA. ISBN 978-0321356680.

Cadenhead, Rogers. 2012. Sams Teach Yourself Java in 21 Days (6th Edition). Sams, Indianapolis,IN. ISBN 978-0672335747.

Eckel, Bruce. 2006. Thinking in Java (4th Edition). Prentice Hall PTR, Upper Saddle River, NJ. ISBN 978-0131872486.

Horstmann, Cay and Gary Cornell. 2012. Core Java 2, Volume I: Fundamentals (9th Edition).Prentice Hall PTR, Upper Saddle River, NJ. ISBN 978-0137081899.

Horstmann, Cay and Gary Cornell. 2013. Core Java 2, Volume II: Advanced Features (9th Edition).Prentice Hall PTR, Upper Saddle River, NJ. ISBN 978-0137081608.

Schildt, Herbert. 2011. Java, A Beginner's Guide (5th Edition). McGraw Hill, New York, NY.ISBN 978-0071606325.

Schildt, Herbert. 2011. Java The Complete Reference (8th Edition). McGraw Hill, New York, NY.ISBN 978-0070435926.

Sierra, Kathy and Bert Bates. 2005. Head First Java (2nd Edition). O'Reilly & Associates,Sebastopol, CA. ISBN 978-0596009205.

http://stackoverflow.com/questions/tagged/javahttp://www.javaworld.comhttp://www.javaranch.comhttp://www.oracle.com/technetwork/java

Suggested ReferencesEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 15: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Course IntroductionChapter 1

© 2015 ITCourseware, LLC Rev 5.3.1 Page 17

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 16: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 18 Rev 5.3.1 ©2015 ITCourseware, LLC

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 17: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Getting Started with JavaChapter 2

© 2015 ITCourseware, LLC Rev 5.3.1 Page 19

Chapter 2 - Getting Started with Java

Objectives

Define Java terms such as JRE,JSDK, and JVM

Write, compile, and run a Javaprogram.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 18: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 20 Rev 5.3.1 ©2015 ITCourseware, LLC

Java is an Object-Oriented Programming language with extensive class libraries.

You need a Java Runtime Environment (JRE), consisting of a Java VirtualMachine (VM) and a copy of the Java API libraries, to run a Javaprogram.

You need the Java Software Development Kit (JSDK), including a JavaVM, a copy of the Java API libraries, and a Java compiler, to create a Javaprogram.

Write Once, Run Anywhere.

Code written on any platform, with any Java compiler, can be run on anyplatform with any Java Virtual Machine (interpreter).

Java borrowed the best of several programming languages, including C++, C#,Objective C, Cedar/Mesa, Smalltalk, Eiffel, and Perl.

What is Java?EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 19: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Getting Started with JavaChapter 2

© 2015 ITCourseware, LLC Rev 5.3.1 Page 21

The Java white paper lists several design goals:

Simple — The language syntax is familiar, very much like C and C++, but many of the really nasty thingshave been removed.

Secure — Compile time and runtime support for security.

Distributed — The Java API library includes the java.net package.

Object-Oriented — Designed from the beginning to be strictly object-oriented. The Java API librariesinclude a large number of classes arranged in packages (like class libraries). There are no functions or globaldata outside of classes, e.g., main() or C++ friend functions.

Robust — Strongly typed — stronger type checking than C++. Compile-time checking for typemismatches. Simplified memory management. No pointers. Exception handling.

Portable — Java code is compiled into architecture-neutral bytecode. No implementation-dependentaspects in the language (e.g., the int type is 32 bits regardless of the platform word size).

Interpreted — The bytecode is interpreted on any platform that implements the Java Virtual Machine.

Multithreaded — Language and library support for multiple threads of control.

Dynamic — Classes are loaded as needed, locally or across the net. Runtime type information is built in.

High performance — Interpreted, so not as fast as C in execution speed. Just In Time (JIT) compilersmake Java programs almost as fast as C. Automatic Garbage Collection helps ensure needed memory isavailable.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 20: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 22 Rev 5.3.1 ©2015 ITCourseware, LLC

You can download the Java Software Development Kit for free from Oracle.

Oracle has ports for Solaris, Windows, OS X, and Linux platforms, andpublishes links to other ports.

The Oracle Java web site has many other resources, including the JSDKdocumentation, many demo programs, the FAQ, Java language spec, thewhite paper, etc.

Open source development environments like NetBeans and Eclipse are freelyavailable for download.

How to Get JavaEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 21: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Getting Started with JavaChapter 2

© 2015 ITCourseware, LLC Rev 5.3.1 Page 23

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 22: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 24 Rev 5.3.1 ©2015 ITCourseware, LLC

Hands On:

Type the following program into a text editor:

package examples;

public class Hello { public static void main(String[] args) { System.out.print("Hello, "); if (args.length == 0) System.out.println("World!"); else System.out.println(args[0] + "!"); }}

We are defining a top-level class named Hello.

The name of the file must be ClassName.java; e.g., Hello.java.

Case is important.

The file should reside in a directory that corresponds to the package name.

A First Java ProgramEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 23: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Getting Started with JavaChapter 2

© 2015 ITCourseware, LLC Rev 5.3.1 Page 25

The classic first program in Java is just "Hello, World!":

examples/HelloWorld.javapackage examples;

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); }}

Ours is very similar, but a little more interesting.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 24: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 26 Rev 5.3.1 ©2015 ITCourseware, LLC

The steps to compile and interpret a Java application:

1. Create the source file with a text editor.

2. Compile the source into bytecode:

javac examples\Hello.java

3. Interpret the bytecode:

java examples/Hello

or

java examples/Hello Bob

Compiling and Interpreting ApplicationsEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 25: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Getting Started with JavaChapter 2

© 2015 ITCourseware, LLC Rev 5.3.1 Page 27

public class Hello public static void System.out.print(" if (args.length == System.out.prin else

examples\Hello.java

feca beba 0300 2d000007 071a 1b00 0007 0a0005 0a0a 0300 0b00 001700 000c 001f 010d 034c28 616a 6176 6c2f 6e676e 293b 0156 1600 5b

examples\Hello.class

1. Load bytecode from the file Hello.class

Class Hello public void main()

2. Interpret and run bytecode:

Hello.main("Bob")

Java VM

javac examples\Hello.java

java examples/Hello Bob

Environment Variables

The easiest way to run java and javac is to have their location in your PATH environment variable.

On Linux:PATH=$PATH:/JAVA_HOME/bin

On Windows:PATH=%PATH%;c:\JAVA_HOME\bin

Where JAVA_HOME is your Java installation directory.

Stand-alone Applications

Java programs can run as stand-alone applications. They can be started from a DOS or Linux prompt. On aWindows platform, or a graphical Linux platform, you can run a Java program that has a graphical userinterface from an icon on your desktop.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 26: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 28 Rev 5.3.1 ©2015 ITCourseware, LLC

Java should be installed in some globally-accessible directory, such as/usr/local/java or C:\Program Files\Java.

src.zip is an archive which contains all of the source code for the standardJava library classes; this can be expanded to view the source code.

bin/ contains the javac compiler and the java interpreter, among other tools;this directory needs to be in your PATH environment variable.

lib/ contains Java Archive (JAR) files used by the Java tools.

jre/ contains subdirectories with files for the Java Runtime Environment.

jre/bin/ contains copies of the tools used at runtime and libraries that theyuse.

jre/lib/ contains resource files for fonts, etc., and the standard Java libraryclassfiles (in rt.jar).

include/ contains C header files for use with the Java Native Interface.

The JSDK Directory StructureEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 27: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Getting Started with JavaChapter 2

© 2015 ITCourseware, LLC Rev 5.3.1 Page 29

Oracle provides several Java tools with the JSDK. Here a few of the ones used most:

javac — the source code compiler.

javac produces architecture-neutral “bytecode.” The compiler produces a bytecode fileClassname.class; e.g., javac HelloWorld.java produces HelloWorld.class.

java — the bytecode interpreter.

The “virtual machine” (java) interprets bytecode for specific architectures. This is how stand-alone(non-applet) Java programs are executed.

java Classname

e.g.,

java HelloWorld

Do not include the .class extension.

appletviewer — a mini-browser for testing applets.

appletviewer reads an HTML file containing an <applet ...> tag, and loads and runs that appletclass file.

javap — a “disassembler” for bytecode.

jdb — the bytecode debugger.

javadoc — a utility to generate .html files which document the methods and hierarchy of your classes. Forjavadoc to work, you must:

1. Add javadoc comments to your .java file:

/** This is a Javadoc comment */

2. Run javadoc on your .java file:

javadoc HelloWorld.java

jar — a utility to create JAR files (similar to ZIP files).

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 28: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 30 Rev 5.3.1 ©2015 ITCourseware, LLC

Write a Java application called MyName that prints out your name, and compile it usingjavac. List your directory. What was created? Run your program.(Solutions: MyName.java)

What happens if the name of the .java file is different from the class name contained in it?Copy MyName.java to Name.java. What messages do you get from the compiler?(Solution: Name.txt)

Try disassembling one of your .class files with javap -c (leave off the .class extension). Tryjavap -help.(Solution: MyName_javap_output)

LabsEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 29: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

PackagesChapter 9

© 2015 ITCourseware, LLC Rev 5.3.1 Page 155

Chapter 9 - Packages

Objectives

Write programs that use classes fromother packages.

Write programs that import packages.

Create and use your own packages.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 30: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 156 Rev 5.3.1 © 2015 ITCourseware, LLC

A package is a convenient way of grouping classes that have relatedfunctionality, but may not be in the same file.

Each .java file may specify that it is part of a package.

package examples;

Package names will correspond to directory names.

The Java API groups classes into packages with related functionality:

java.lang — basic language classes.

java.sql — database access classes.

java.util— general utility classes.

java.util.regex— regular expression utility classes.

. . . and many others.

Since classes may be loaded across the Internet, packages reduce possibilitiesof namespace collisions.

Two packages can both contain a List class.

PackagesEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 31: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

PackagesChapter 9

© 2015 ITCourseware, LLC Rev 5.3.1 Page 157

When you use a class that belongs to another package, precede the class name with the package name:

java.awt.Frame

java.awt is a package name.

Frame is a class name.

To make the code easier to read, Java developers have used the convention of capitalizing the first letter inclass names. So the 'F' in Frame tells us that Frame is the name of a class. Any name before a class name isa package or subpackage name.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 32: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 158 Rev 5.3.1 © 2015 ITCourseware, LLC

To use a class from another package, just qualify the class name with thepackage name:

java.util.ArrayList a = new java.util.ArrayList();

The import statement allows you to use a package's classes without fullyspecifying the package name each time.

import packagename.*;

The package's classes become part of the current program's namespace.

You may import a single class or an entire package.

import java.util.ArrayList;

Use the wild card character * to import an entire package.

import java.util.*;

There is no memory or code size penalty for using the wild card.

References to classes from an imported package do not need to be preceded bythe package name.

For example, java.util.ArrayList can be specified as simply ArrayList.

If two imported packages define a class with the same name, you must fullyspecify the name of the class that you are trying to use.

The import StatementEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 33: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

PackagesChapter 9

© 2015 ITCourseware, LLC Rev 5.3.1 Page 159

Months1.javapackage examples;

public class Months1 {public static void main(String[] args) {

java.util.ArrayList<String> months = new java.util.ArrayList<>();months.add("January");months.add("February");months.add("March");...for (String month : months) {

System.out.println(month);}

}}

The same code using import:

Months2.javapackage examples;

import java.util.ArrayList;

public class Months2 {public static void main(String[] args) {

ArrayList<String> months = new ArrayList<>();months.add("January");months.add("February");months.add("March");...for (String month : months) {

System.out.println(month);}

}}

We can now use the ArrayList class without specifying the package.

One particular package that contains classes used in almost every program is java.lang. java.lang isautomatically imported. Explicitly importing it won’t hurt (or help).

The System class that we use for printing belongs to this package. We did not have to say:java.lang.System.out.println("Hello, World");.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 34: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 160 Rev 5.3.1 © 2015 ITCourseware, LLC

Static Imports

For convenience, you can use static imports to save you typing.

Any reference to a static field or method can be left unqualified.

import static java.lang.System.out;...

out.println("Hello World");

You can also use the wildcard with static imports.

import static java.lang.Math.*;...

double area = PI * pow(radius, 2);

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 35: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

PackagesChapter 9

© 2015 ITCourseware, LLC Rev 5.3.1 Page 161

StaticImports.javapackage examples;

import static java.lang.System.out;import static java.lang.Math.*;

public class StaticImports { public static void main(String[] args) { int radius = 5; double area = PI * pow(radius, 2);

out.printf( "The area of a circle with radius %1$d is %2$.2f %n", radius, area); }}

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 36: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 162 Rev 5.3.1 © 2015 ITCourseware, LLC

At runtime, the Application Class Loader searches for .class bytecode files inthe application classpath.

By default, the application classpath is the current directory.

You can override the default by setting the environment variable CLASSPATH.

Any of the directories in the CLASSPATH may have subdirectories;these are the package directories.

java (as well as other JDK utilities) has a flag, -classpath, that overridesthe CLASSPATH variable.

CLASSPATH, or -classpath, if set, must include the directories containing anyclasses you create.

The current directory, represented by "." on most systems, is usuallyplaced first.

Any project directories that contain package subdirectories must bespecified.

For Java to load classes from these packages/directories, the file permissionsmust grant access.

CLASSPATH and ImportEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 37: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

PackagesChapter 9

© 2015 ITCourseware, LLC Rev 5.3.1 Page 163

Any time you use classes from your own packages, set your CLASSPATH properly.

Suppose that you have created a university package and are working on it under the directory /home/projects/:

/home/projects/university/Student.class/home/projects/university/Professor.class/home/projects/university/...

When compiling or running applications that use classes from your university package, make sure yourCLASSPATH includes the directory that contains your package directory:

CLASSPATH=.:/home/projects

Do not include the university directory itself in your CLASSPATH!

The java interpreter actually searches for classes (bytecode files) in three directory paths:

The bootstrap classpath contains the directory for the standard Java bootstrap classes. This is typically/java-dir/lib. These are the classes contained in rt.jar. This path can be changed by using the -Xbootstrap option with the various tools, but this is not recommended.

The extension directories contain packages that can be used in conjunction with the standard Javabootstrap classes, as though they were built-in. This is primarily used for third-party packages, or appletsusing additional packages. The extension directory is /java-dir/lib/ext.

The application classpath contains directories for additional packages that you have created. By default,the current directory (".") is searched. This path can be changed by setting the CLASSPATH environmentvariable, or by using the -classpath option with the various tools. When you provide an applicationclasspath, either with the environment variable or the command line option, "." is not automatically added.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 38: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 164 Rev 5.3.1 © 2015 ITCourseware, LLC

The package keyword allows you to define a package.

The package statement must be the first non-comment line.

The package can be a single name:

package university;

The package can be a specialized dot-separated name:

package project.src;

Package names correspond to directories.

If your package name is project.src, then its class files must be in adirectory named project/src/.

It's a good idea to pick package names that won't conflict with other groups inyour company; this will allow you to share classes with one another.

network.services

You can further divide the package name:

network.services.accounting

If you use your Internet domain name as part of your package name, you'repretty much guaranteed a unique namespace:

package com.example.guistuff;

In fact, Oracle recommends, and uses, this practice:

package com.oracle.jdbc.driver;

Defining PackagesEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 39: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

PackagesChapter 9

© 2015 ITCourseware, LLC Rev 5.3.1 Page 165

The compiled class for Car.javashould be located under theexamples/rentalcar directory.

Car.javapackage examples.rentalcar;

public class Car { private String vIN; private String tag;

public String getVIN() { return vIN; }

public void setVIN(String vin) { vIN = vin; }

public String getLicenseTag() { return tag; }

public void setLicenseTag(String t) { tag = t; }}

By convention, Java programmers use lowercase letters for their package names.

If you omit the package declaration, then your code is said to be a member of the default package. Its useis discouraged since you open yourself up to namespace collisions when you don't use packages.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 40: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 166 Rev 5.3.1 © 2015 ITCourseware, LLC

When you define member data or methods within a class, you may choose toleave off the access specifiers private, protected, and public.

The field or method is then said to have default access.

Default access is also known as package access.

Default access control means that any other class within the same package willhave full access to that field or method.

Package ScopeEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 41: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

PackagesChapter 9

© 2015 ITCourseware, LLC Rev 5.3.1 Page 167

The public modifier on a class makes it accessible outside its package.

Classes with default, or package, access are helper classes that can only be used from classes within thesame package.EVALUATION COPY

Unauthorized reproduction or distribution is prohibited.

Page 42: Java Programming - ITCourseware · Java Programming Page 14 Rev 5.3.1 ©2015 ITCourseware, LLC Audience: This is a programming course designed for software development professionals

Java Programming

Page 168 Rev 5.3.1 © 2015 ITCourseware, LLC

Create a package called animal with two public classes, Dog and Cat. Create a Java application,within another package, that creates both a Dog and a Cat object. Test without using import, thenagain with the import statement.(Solutions: animal/Dog.java, animal/Cat.java, AnimalTest.java)

Add a non-public class called Jackal to your animal package. Try creating a Jackal object inyour application.(Solutions: animal/Jackal.java, AnimalTest2.java)

Create a second package named zoo that contains a Cat class (big zoo-type cats!). How can youuse objects of both Cat classes in your application?(Solutions: zoo/Cat.java, ZooTest.java)

LabsEVALUATION COPY

Unauthorized reproduction or distribution is prohibited.