introduction to java programming - itcourseware€¦ · introduction to java programming chapter 8...

67
Introduction to Java Programming Student Workbook

Upload: others

Post on 24-Jun-2020

25 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to JavaProgramming

Student Workbook

Page 2: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Page ii Rev 5.2.1 © 2013 ITCourseware, LLC

Introduction to Java Programming

Introduction to Java Programming

Contributing Authors: John Crabtree, Danielle Hopkins, Julie Johnson, Channing Lovely, Mike Naseef,Jamie Romero, Rob Roselius, Rob Seitz, and Rick Sussenbach.

Published by ITCourseware, LLC., 7245 South Havana Street, Suite 100, Centennial, CO 80112

Editor: Jan Waleri

Editorial Staff: Danielle North

Special thanks to: Many instructors whose ideas and careful review have contributed to the quality of thisworkbook, including Jimmy Ball, Larry Burley, Roger Jones, Joe McGlynn, Jim McNally, Mike Naseef,Richard Raab, and Todd Wright, and the many students who have offered comments, suggestions,criticisms, and insights.

Copyright © 2013 by ITCourseware, LLC. All rights reserved. No part of this book may be reproduced orutilized in any form or by any means, electronic or mechanical, including photo-copying, recording, or by aninformation storage retrieval system, without permission in writing from the publisher. Inquiries should beaddressed to ITCourseware, LLC., 7245 South Havana Street, Suite 100, Centennial, Colorado, 80112.(303) 302-5280.

All brand names, product names, trademarks, and registered trademarks are the property of their respectiveowners.

Page 3: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

© 2013 ITCourseware, LLC Rev 5.2.1 Page iii

Introduction to Java Programming

Contents

Chapter 1 - Course Introduction ............................................................................................................. 9

Course Objectives .......................................................................................................................... 10Course Overview ........................................................................................................................... 12Using the Workbook ...................................................................................................................... 13Suggested References ..................................................................................................................... 14

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

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

Chapter 3 - Eclipse ............................................................................................................................... 31

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

Chapter 4 - Language Fundamentals ..................................................................................................... 51

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

Page 4: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Page iv Rev 5.2.1 © 2013 ITCourseware, LLC

Introduction to Java Programming

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

Chapter 5 - Objects and Classes .......................................................................................................... 77

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

Chapter 6 - Using Java Objects ............................................................................................................ 95

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

Chapter 7 - Inheritance in Java ............................................................................................................ 119

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

Page 5: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

© 2013 ITCourseware, LLC Rev 5.2.1 Page v

Introduction to Java Programming

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

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

Chapter 9 - Packages ......................................................................................................................... 153

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

Chapter 10 - Exception Handling ........................................................................................................ 169

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

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

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

Page 6: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Page vi Rev 5.2.1 © 2013 ITCourseware, LLC

Introduction to Java Programming

Labs ............................................................................................................................................. 204

Chapter 12 - Core Collection Classes ................................................................................................. 207

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

appendix A - Collection Sorting and Tuning ......................................................................................... 229

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

Appendix B - Java EE Overview ........................................................................................................ 245

Introduction to Java EE ................................................................................................................. 246Java SE Building Blocks ............................................................................................................... 248Web Applications ......................................................................................................................... 250Web Services ............................................................................................................................... 252Enterprise JavaBeans .................................................................................................................... 254Additional Java EE APIs ............................................................................................................... 256POJO, Dependency Injection, and Annotations ............................................................................. 258The Java EE Platform ................................................................................................................... 260

Appendix C - Eclipse Shortcuts .......................................................................................................... 263

Shortcut Key Sequences ............................................................................................................... 264More Shortcut Key Sequences ..................................................................................................... 266

Page 7: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

© 2013 ITCourseware, LLC Rev 5.2.1 Page vii

Introduction to Java Programming

Index .................................................................................................................................................. 269

Page 8: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Page viii Rev 5.2.1 © 2013 ITCourseware, LLC

Introduction to Java Programming

Page 9: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Course IntroductionChapter 1

© 2013 ITCourseware, LLC Rev 5.2.1 Page 9

Chapter 1 - Course Introduction

Page 10: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 10 Rev 5.2.1 ©2013 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.

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.

Course Objectives

Page 11: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Course IntroductionChapter 1

© 2013 ITCourseware, LLC Rev 5.2.1 Page 11

Page 12: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 12 Rev 5.2.1 ©2013 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 Overview

Page 13: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Course IntroductionChapter 1

© 2013 ITCourseware, LLC Rev 5.2.1 Page 13

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.

Page 14: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 14 Rev 5.2.1 ©2013 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 References

Page 15: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Course IntroductionChapter 1

© 2013 ITCourseware, LLC Rev 5.2.1 Page 15

Page 16: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 16 Rev 5.2.1 ©2013 ITCourseware, LLC

Page 17: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Getting Started with JavaChapter 2

© 2013 ITCourseware, LLC Rev 5.2.1 Page 17

Chapter 2 - Getting Started with Java

Objectives

Define Java terms such as JRE,JSDK, and JVM

Write, compile, and run a Javaprogram.

Page 18: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Intermediate Java Programming

Page 18 Rev 5.2.1 ©2013 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?

Page 19: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Getting Started with JavaChapter 2

© 2013 ITCourseware, LLC Rev 5.2.1 Page 19

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.

Page 20: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Intermediate Java Programming

Page 20 Rev 5.2.1 ©2013 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 Java

Page 21: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Getting Started with JavaChapter 2

© 2013 ITCourseware, LLC Rev 5.2.1 Page 21

Page 22: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Intermediate Java Programming

Page 22 Rev 5.2.1 ©2013 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 Program

Page 23: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Getting Started with JavaChapter 2

© 2013 ITCourseware, LLC Rev 5.2.1 Page 23

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.

Page 24: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Intermediate Java Programming

Page 24 Rev 5.2.1 ©2013 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 Applications

Page 25: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Getting Started with JavaChapter 2

© 2013 ITCourseware, LLC Rev 5.2.1 Page 25

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.

Page 26: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Intermediate Java Programming

Page 26 Rev 5.2.1 ©2013 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 Structure

Page 27: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Getting Started with JavaChapter 2

© 2013 ITCourseware, LLC Rev 5.2.1 Page 27

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

Page 28: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Intermediate Java Programming

Page 28 Rev 5.2.1 ©2013 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)

Labs

Page 29: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Language FundamentalsChapter 4

© 2013 ITCourseware, LLC Rev 5.2.1 Page 51

Chapter 4 - Language Fundamentals

Objectives

Read and understand Java programs.

Use Java's program-control statements.

Program proficiently with Java syntax.

Use Java's portable datatypes, andcorrectly evaluate expressions.

Work with arrays.

Work with Strings.

Page 30: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 52 Rev 5.2.1 ©2013 ITCourseware, LLC

A Java Program

All Java code is defined in the methods and fields of classes.

A Java program contains a public class with a public method, return type void,named main.

The Virtual Machine loads the compiled class (and any other classes thatthis class uses).

The Virtual Machine begins execution by invoking the main() method ofthe class.

The Virtual Machine copies runtime arguments from the program's commandline into an array of Strings, which is main's only parameter.

Most programmers name the array arg or args.

Page 31: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Language FundamentalsChapter 4

© 2013 ITCourseware, LLC Rev 5.2.1 Page 53

Rectangle.javapackage examples;

public class Rectangle { static int width = 10; static int height = 5;

public static void main(String[] args) { int area = width * height; System.out.println("The area is: " + area); }}

If main() is declared incorrectly, the Virtual Machine won't recognize it, and therefore won't be able to startyour application:

public So that the VM has access to the main() method.

static main() resides in its class, not in objects of its class. The VM doesn'tneed to create an object before invoking main().

void main() doesn't return a value.

main The name must be exact, not Main, start, or anything else.

String args[] main() must be declared with exactly one parameter, an array ofStrings. This parameter must exist, even if you don't use the argumentsin your code. It can be declared as String[] args.

Page 32: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 54 Rev 5.2.1 ©2013 ITCourseware, LLC

If Statements

Java's syntax for conditional (if) statements is identical to that of C, C++, andC#.

Each if statement may have multiple else if clauses, as well as an optional elseclause.

if ( expression )statement;

if ( expression )statement;

elsestatement;

if ( expression )statement;

else if ( expression )statement;

elsestatement;

Every simple statement must end in a semicolon, and you can group simplestatements together inside braces to form a block, which can appear anywhere asimple statement can.

Page 33: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Language FundamentalsChapter 4

© 2013 ITCourseware, LLC Rev 5.2.1 Page 55

IfTest.javapackage examples;

public class IfTest { static double totalSales = 33000.0;

public static void main(String[] args) { double bonus = 0.0;

if (totalSales < 30000) bonus = totalSales * 0.050;

// when will the following line print? System.out.println("Small bonus awarded: " + bonus);

if (totalSales >= 30000) { bonus = totalSales * 0.075; // when will the following line print? System.out.println("Large bonus awarded: " + bonus); } }}

In this example, both System.out.println lines will print every time because they are not part of the ifstatements, no matter how they are indented.

Page 34: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 56 Rev 5.2.1 ©2013 ITCourseware, LLC

Switch Statements

A switch statement compares an integer (byte, char, short, or int) expressionagainst a set of specific values:

switch ( expression ) {case value1:

statement;break;

case value2:statement;break;

default:statement;

}

As of Java 5.0, enum values can also be used in a switch statement.

Java 7 added String as another possible expression data type.

Page 35: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Language FundamentalsChapter 4

© 2013 ITCourseware, LLC Rev 5.2.1 Page 57

SwitchTest.javapackage examples;

public class SwitchTest { static char grade = 'A';

public static void main(String[] args) { switch (grade) { case 'A': System.out.println("Great Job"); break; case 'B': System.out.println("Good Job"); break; case 'C': System.out.println("Average Job"); break; case 'D': System.out.println("Poor Job"); break; case 'F': System.out.println("Bad Job"); break; default: System.out.println("Illegal grade"); break; } }}

Page 36: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 58 Rev 5.2.1 ©2013 ITCourseware, LLC

The while loop iterates while an expression is true.

while ( expression )statement;

expression must yield a boolean, not an int value; this is true forconditional (if) statements as well (get used to it, C programmers!).

The do loop is similar to the while loop, but is guaranteed to execute at leastonce.

dostatement;

while ( expression );

A for loop iterates a specified number of times:

for ( initial ; test_expression ; increment )statement;

initial or increment may be a single expression, or a comma-separated listof expressions.

Variables declared in the initializer are local to the loop.

for ( int i=0; i < 10 ; i++ ) {// i is local to this loop

}System.out.println(i); //compile error

break stops iteration of its enclosing loop.

continue jumps immediately to the next iteration.

Loop Statements

Page 37: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Language FundamentalsChapter 4

© 2013 ITCourseware, LLC Rev 5.2.1 Page 59

CountDown.java...public class CountDown {

public static void main(String[] args) {

int counter = 10; while (true) { if (counter == 0) { break; } System.out.println(counter--); } System.out.println("Blast off!"); }}

Temperature.java...public class Temperatures {

public static void main(String[] args) {

for (int c = 0; c <= 100; c++) { float f = c * (9F/5F) + 32; System.out.println(c + " Celsius is " + f + " Fahrenheit"); } }}

ForLoopTest.java...public class ForLoopTest {

public static void main(String[] args) {

for (int i = 0, j = 10; i < 10; i++, j--) { if (i <= j) { continue; } System.out.println("i is : " + i + ", j is : " + j); } }}

Page 38: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 60 Rev 5.2.1 ©2013 ITCourseware, LLC

Identifiers are used for names of classes, methods, and variables.

An identifier:

Is case-sensitive.

Must begin with a letter, or with _ or $.

After the first character, you can use letters, numbers, _, or $; nosymbols, such as #@!(), etc.

Can be of unlimited length.

Must not be a keyword.

There are three kinds of comments in Java:

C-style block comments — do not try to nest these!

/* This comment continueson the next line (that is, this line...) */

C++-style in-line comments:

// comment to end of line

Javadoc comments, for automatic documentation of classes and methodsby javadoc.

/** This is just a C-style block comment, but the javadoc program looks for the slash-star-star at the beginning. I should format this appropriately. */

Syntax Details

Page 39: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Language FundamentalsChapter 4

© 2013 ITCourseware, LLC Rev 5.2.1 Page 61

Keywords are tokens reserved by the language. You cannot use these Java keywords as identifiers:

abstract continue for new switch†assert default if package synchronizedboolean do *goto private thisbreak double implements protected throwbyte else import public throwscase ‡enum instanceof return transientcatch extends int short trychar final interface static voidclass finally long strictfp volatile*const float native super while

*Reserved, but not currently used†Added at 1.4‡Added at 1.5 (Java 5.0)

The words true and false are not formally keywords, but boolean literals; however, the distinction isslight and you should not try to use them as identifiers. The same is true of the null value literal, null.

Valid identifiers:total_amountgetRadiusMyClass$revenueThis_is_a_mighty_long_identifier_and_could_be_even_longer // Yuck!_$_$____$ // YUCK!!!

Invalid identifiers:#sterling // Invalid character, '#'get Radius // Two words (invalid character, ' ')class // This is a keyword

Note:By convention, most Java programmers capitalize class names and lowercase variable and method names.

Page 40: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 62 Rev 5.2.1 ©2013 ITCourseware, LLC

Java precludes hardware, operating-system, and network datatype dependenciesby defining portable primitive datatypes whose size and properties are identicalon every Java Virtual Machine.

int employeeId = 1234; // int literalfloat salary = 32500.00F; // float literaldouble income = 7250000.0; // double literalboolean oriented = false; // boolean literalchar status = 'A'; // char literal

Java defines exactly 8 primitive datatypes.

There are no unsigned numeric types.

Unlike in C, a char is 2 bytes, not one; all Java characters are 16-bit Unicodecharacters, not 8-bit ASCII characters.

Unicode is compatible with ASCII — the first 128 Unicode characterscomprise the ASCII character set.

Use char, not byte, for character data.

A Unicode character escape can appear anywhere in a Java program:

char status = '\u0041'; // Initialize w/Unicode char.

Primitive Datatypes

Page 41: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Language FundamentalsChapter 4

© 2013 ITCourseware, LLC Rev 5.2.1 Page 63

For more information on Unicode, go to http://www.unicode.org.

As of Java 7, you can use an underscore within your numeric literals to break up hard to read numbers.

int phone = 555_5280;

epyT muminiM mumixaM tluafeD eziS

etyb 821- 721 0 regetnidengistib-8

trohs 86723- 76723 0 regetnidengistib-61

tni 8463847412- 7463847412 0 regetnidengistib-23

gnol 8085774586302733229- 7085774586302733229 0 regetnidengistib-46

taolf 54-e64893204.1- 83+e74328204.3 F0.0+ taolfEEEItib-23

elbuod 423-e33564214854656049.4- 803+e07513268431396797.1 D0.0+ elbuodEEEItib-46

naeloob eslaf eurt eslaf A/N

rahc 0000u\ ffffu\ 0000u\ edocinUtib-61

Page 42: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 64 Rev 5.2.1 ©2013 ITCourseware, LLC

Variables

Variables are declared either in a class or inside methods of a class.

A variable declared in a class is called a field (or attribute) of that class.

A field is accessable to all methods in the class.

Fields are automatically initialized to their default value.

Numerics are initialized to 0.

Booleans are initialized to false.

References (covered later) are initialized to null.

A variable declared in a method is called a local variable.

A local variable's scope is limited to the method in which it was declared.

You must initialize a local variable before using it.

Variables declared with the modifier final must be assigned before use andcannot be changed once assigned.

final short cards = 52;cards = 53; //Illegal! Can't change a final.

Page 43: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Language FundamentalsChapter 4

© 2013 ITCourseware, LLC Rev 5.2.1 Page 65

InitTest.javapackage examples;

public class InitTest { int count; // Automatically initialized to 0 double budget; // Automatically initialized to +0.0D String name; // Automatically initialized to null final int max = 100; // Initialize final before use

void firstMethod() { int k = 42; System.out.println("The value of k is: " + k); // int j; // not initialized, so... // System.out.println("Testing: " + j); // Compiler Error! }

void secondMethod() { count = count + 1; // We can use the count field here. // k = 17; // Compiler Error! // max = 50; // Compiler Error! }}

Try It:Uncomment the four commented lines in InitTest.java and then compile the class. Pay close attention tothe messages that the compiler generates.

Page 44: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 66 Rev 5.2.1 ©2013 ITCourseware, LLC

Expressions in Java

Evaluation reduces an expression's variables, literals, operators, and methodcalls to a single value of some type.

circumf = c.getRadius() * 2 * java.lang.Math.PI;

Expressions used in conditional and loop test statements must evaluate toa boolean value.

int my_var = getSomeNumber();if ( my_var != 0 )

not:if ( my_var ) // Won't compile.

Java can implicitly convert between certain primitive types.

Any numeric value to any other numeric type that is the same size orlarger.

short s = 32767;int i = s;

Integer values to floating-point types.

double d = i;

Explicit conversion requires a cast, which may lose some bits.

Floating-point type to integer type.

s = (short)d;

Larger type to smaller type.

s = (short)i;s = (short)1000000;// Too big for a short.

boolean is not an integer; there is no way to cast between boolean and anotherdatatype.

Page 45: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Language FundamentalsChapter 4

© 2013 ITCourseware, LLC Rev 5.2.1 Page 67

rotarepO ssalC ecnedecerP ytivitaicossA

--++ )xiftsoproxiferp(

yranu 1 tfel-ot-thgir+~-!

( tsac )

%/* yranib 2 thgir-ot-tfel

-+ yranib 3 thgir-ot-tfel

>>>>><< yranib 4 thgir-ot-tfel

=>>=<<foecnatsni yranib 5 thgir-ot-tfel

=!== yranib 6 thgir-ot-tfel

& yranib 7 thgir-ot-tfel

^ yranib 8 thgir-ot-tfel

| yranib 9 thgir-ot-tfel

&& yranib 01 thgir-ot-tfel

|| yranib 11 thgir-ot-tfel

:? yranret 21 tfel-ot-thgir

=<<=-=+=%=/=*=yranib 31 tfel-ot-thgir

=>>>=^=|=&=>>

Java uses the same operators as C/C++ for assignment (=) and comparison (==). In C, mixing these up cancause very subtle and serious bugs:

int x = 0;if ( x = 1 ) { /* Assign 1 to x, yielding the integer value 1,

which is numerically true. What was meant was:if ( x == 1 ), numerical comparison */

In Java, however, all conditional expressions must yield a boolean value, so this class of bug won'tpass the compiler:

int x = 0;if ( x = 1 ) { // Assign 1 to x, yielding numeric value 1,

// which is not a boolean; this won't compile.

The order of evaluation of operands is strictly defined.

Page 46: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 68 Rev 5.2.1 ©2013 ITCourseware, LLC

Java's String class handles most string processing.

"Gosling" is a String literal (an object).

+ is a special operator for String used for concatenation.

equals() is used to test if two Strings are equivalent.

Arrays of char are not strings in Java.

A String can be converted to an array of chars by the String instancemethod toCharArray().

String objects are immutable: they can't be changed.

String s = "Hello";s = s + ", World";

The second statement creates a new String, whose value is theconcatenation of the original String referenced by s ("Hello"), and thetemporary String object ", World".

The variable s is then set to refer to the new String; the original Stringreferenced by s, containing "Hello", is discarded.

No operation can modify an existing String.

Strings

Page 47: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Language FundamentalsChapter 4

© 2013 ITCourseware, LLC Rev 5.2.1 Page 69

Compare.javapackage examples;

public class Compare {

public static void main(String[] args) { if (args.length == 2) { // check == if (args[0] == args[1]) System.out.println("Both Strings are =="); else System.out.println("Both Strings are NOT ==");

// check equals() if (args[0].equals(args[1])) System.out.println("Both Strings are 'equal'"); else System.out.println("Both Strings are NOT 'equal'"); } else { System.out.println("Usage: java Compare arg1 arg2"); } }}

Try It:Run Compare.java. Try passing in your first name for args[0] and args[1].

Page 48: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 70 Rev 5.2.1 ©2013 ITCourseware, LLC

A variable declared with brackets, [], is an array reference.

Put the [] next to the datatype or the name; your choice.

float price[];String[] title, author; // Both are array refs

You must use new to actually create the array.

price = new float[44]; // Create array of 44 floatsString[] names = new String[10]; //Declare & create

Once created, an array cannot be resized.

Primitive-type array elements are initialized to default values.

If the array is an array of object references, then each object must also becreated with new.

names[1] = new String("Bob Dobbs");

Elements are indexed using [], and numbered from 0.

price[0] = 99.95F;

An array's length field gives the number of elements in the array.

Indexing past the end of an array throws an exception.

Multi-dimensional arrays are implemented as arrays of arrays.

Arrays

Page 49: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Language FundamentalsChapter 4

© 2013 ITCourseware, LLC Rev 5.2.1 Page 71

Consider the args array, which is the array of Strings containing the command-line arguments passedto the Java program.

Echo.javapackage examples;

public class Echo { public static void main(String args[]) { System.out.println(args[0]); }}

java Echo Howdy, Folks!Howdy,

To print the last command-line argument:LastOne.javapackage examples;

public class LastOne { public static void main(String args[]) { System.out.println(args[args.length - 1]); }}

java LastOne one two threethree

ArrayTest.javapackage examples;

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

int odds[] = { 1, 3, 5, 7, 9 };

for (int i = 0; i < odds.length; i++) { System.out.println(odds[i]); } ... }}

Instead of using new, youcan initialize an array with alist of values inside braces.

Page 50: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 72 Rev 5.2.1 ©2013 ITCourseware, LLC

Enhanced for Loop

To loop through an array, you can use the array's built-in length field todetermine the size of the array.

int odds[] = {1,3,5,7,9};for(int n = 0; n < odds.length; n++){

System.out.println(odds[n]);}

Java 5.0 added the enhanced for loop to make it easier to step through acollection, such as an array.

for (declaration : expression)statement;

The variable defined in the declaration should be the same type as yourarray's elements.

The expression is simply the name of the array itself.

for (int n : odds){System.out.println(n);

}

The : is read as the word 'in'; "for each int n in odds".

The enhanced for loop is sometimes called the for each loop.

Page 51: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Language FundamentalsChapter 4

© 2013 ITCourseware, LLC Rev 5.2.1 Page 73

ArrayTest.javapackage examples;

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

int odds[] = { 1, 3, 5, 7, 9 };

for (int i = 0; i < odds.length; i++) { System.out.println(odds[i]); }

for (int num : odds) { System.out.println(num); } }}

ArrayTest2.javapackage examples;

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

String bookInfo[][] = { { "Java In a Nutshell", "Flanagan" }, { "Core Java", "Horstmann" }, { "Thinking in Java", "Eckel" } };

for (int i = 0; i < bookInfo.length; i++) { for (int j = 0; j < bookInfo[i].length; j++) { System.out.print(bookInfo[i][j] + " "); } System.out.println(); }

for (String[] book : bookInfo) { for (String s : book) { System.out.print(s + " "); } System.out.println(); } }}

Page 52: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 74 Rev 5.2.1 ©2013 ITCourseware, LLC

Write an application that loops through any number of command-line arguments, printing out oneper line.(Solution: Echo1.java)

Modify your previous program so that, if the user enters no arguments, it will print a messageexplaining that you must pass at least one command-line argument to the program.(Solution: Echo2.java)

Modify your solution again so that, in addition to each argument, it prints that argument's number.Also, before printing the last argument, print "Last one...".(Solution: Echo3.java)

Write an application that creates an array of 12 Strings. Populate each member of the array withthe name of a month. Use the enhanced for loop to print out each month, one per line.(Solution: Months.java)

Modify your Months program so that only the first three characters of each month prints. (Hint: UseString's substring (begin Index, endIndex) method.)(Solution: ThreeCharMonths.java)

(Optional) Modify your solution again so that the three-character months are printed in all capitalletters. (Hint: Use String's toUpperCase() method.)(Solution: CapThreeCharMonths.java)

Labs

Page 53: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Language FundamentalsChapter 4

© 2013 ITCourseware, LLC Rev 5.2.1 Page 75

To send output to your terminal screen or console, use System.out:

System.out.println("Hola, Mundo!");

You'll find out all about Java input and output streams later. For now, it's enough to know that there's anobject called System.out that has methods to print information to your screen. The print() method prints itsargument and nothing else. println() prints its argument, followed by a newline character. Both methods cantake either String or numeric arguments:

double p = 3.1415926535897932384626433;System.out.print("The number is: ");System.out.println(p);

These methods convert numeric arguments into Strings before printing. Another way to accomplish this is tocombine a number with a String using the concatenation operator, +, which also converts the number to aString.

System.out.println("The number is: " + p);

The System class has another object, err, which is commonly associated with the "standard error"destination (the terminal again, by default):

System.err.println("Warning: this number was rounded.");

To read from the keyboard, you can use System.in. Let's save that until we get to I/O streams a little later.

Page 54: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

PackagesChapter 9

© 2013 ITCourseware, LLC Rev 5.2.1 Page 153

Chapter 9 - Packages

Objectives

Write programs that use classes fromother packages.

Write programs that import packages.

Create and use your own packages.

Page 55: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 154 Rev 5.2.1 © 2013 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.

Packages

Page 56: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

PackagesChapter 9

© 2013 ITCourseware, LLC Rev 5.2.1 Page 155

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.

Page 57: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 156 Rev 5.2.1 © 2013 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 Statement

Page 58: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

PackagesChapter 9

© 2013 ITCourseware, LLC Rev 5.2.1 Page 157

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

Page 59: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 158 Rev 5.2.1 © 2013 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);

Page 60: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

PackagesChapter 9

© 2013 ITCourseware, LLC Rev 5.2.1 Page 159

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); }}

Page 61: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 160 Rev 5.2.1 © 2013 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 Import

Page 62: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

PackagesChapter 9

© 2013 ITCourseware, LLC Rev 5.2.1 Page 161

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.

Page 63: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 162 Rev 5.2.1 © 2013 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 Packages

Page 64: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

PackagesChapter 9

© 2013 ITCourseware, LLC Rev 5.2.1 Page 163

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.

Page 65: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 164 Rev 5.2.1 © 2013 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 Scope

Page 66: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

PackagesChapter 9

© 2013 ITCourseware, LLC Rev 5.2.1 Page 165

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.

Page 67: Introduction to Java Programming - ITCourseware€¦ · Introduction to Java Programming Chapter 8 ... Java SE Building Blocks ... platform with any Java Virtual Machine (interpreter)

Introduction to Java Programming

Page 166 Rev 5.2.1 © 2013 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)

Labs