training materials for it professionals · 2019. 4. 11. · roger has over 35 years of experience...

31
TRAINING MATERIALS FOR IT PROFESSIONALS EVALUATION COPY Unauthorized Reproduction or Distribution Prohibited

Upload: others

Post on 21-Aug-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

TRAINING MATERIALS FOR IT PROFESSIONALS EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Introduction to Java for New Programmers

(JVA102 version 2.0.2)

Copyright Information

© Copyright 2019 Webucator. All rights reserved.

The Authors

Steven Claflin

Steve has been providing training in C, C++, Java, database, and web-relatedprogramming for over fifteen years. His programming background includes webapplications using GWT, Java, JavaScript, and jQuery, as well as embeddedprogramming for programmable logic controllers. In the last few years, Steve hasbeen working extensively with Ajax, jQuery, and GWT. Steve receivedundergraduate degrees from MIT and an MBA from the Harvard Business School.Steve has been working with Webucator since 2005. He provides both onsite andonline training. He has provided training for employees of many organizations suchas Johnson & Johnson, ESPN, Cisco Systems, Verizon, Robert Half International,and more. Students enjoy Steve’s thorough explanations, real-world examples,and hands-on approach.Roger Sakowski (Editor)

Roger has over 35 years of experience in technical training, programming, datamanagement, network administration, and technical writing for companies such asNASA, Sun Microsystems, Bell Labs, GTE, GE, and Lucent among other Fortune100 companies.

Brian Hoke (Editor)

Brian Hoke is Principal of Bentley Hoke, a web consultancy in Syracuse, New York.The firm serves the professional services, education, government, nonprofit, andretail sectors with a variety of development, design, and marketing services. Coretechnologies for the firm include PHP and Wordpress, JavaScript and jQuery, Rubyon Rails, and HTML5/CSS3. Previously, Brian served as Director of Technology,

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Chair of the Computer and Information Science Department, and Dean of Studentsat Manlius Pebble Hill School, an independent day school in DeWitt, NY. Beforethat, Brian taught at Insitut auf dem Rosenberg, an international boarding schoolin St. Gallen, Switzerland. Brian holds degrees from Hamilton and Dartmouthcolleges.

Accompanying Class Files

This manual comes with accompanying class files, which your instructor or salesrepresentative will point out to you. Most code samples and exercise and solutionfiles found in the manual can also be found in the class files at the locations indicatedat the top of the code listings.

Due to space limitations, the code listings sometimes have line wrapping, whereno line wrapping occurs in the actual code sample. This is indicated in the manualusing three greater than signs: >>> at the beginning of each wrapped line.

In other cases, the space limitations are such that we have inserted a forced linebreak in the middle of a word. When this occurs, we append the following symbolat the end of the line before the actual break: »»

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Table of Contents1. Java Introduction...................................................................................1

Conventions in These Notes.............................................................................1The Java Environment - Overview....................................................................2Writing a Java Program....................................................................................3Obtaining The Java Environment......................................................................4Setting up Your Java Environment....................................................................7Creating a Class that Can Run as a Program.................................................13

The main() Method..................................................................................13Useful Stuff Necessary to Go Further.............................................................14

System.out.println() ................................................................................14Using an Integrated Development Environment.............................................14Exercise 1: Running a Simple Java Program..................................................17Using the Java Documentation.......................................................................19

2. Java Basics..........................................................................................21

Basic Java Syntax...........................................................................................21General Syntax Rules.............................................................................21Java Statements.....................................................................................22Blocks of Code........................................................................................22Comments...............................................................................................23

Variables.........................................................................................................25Declaring Variables.................................................................................26Advanced Declarations...........................................................................27

Data................................................................................................................30Primitive Data Types................................................................................30Object Data Types...................................................................................31Literal Values...........................................................................................31

Constants and the final Keyword....................................................................34Mathematics in Java.......................................................................................35

Basic Rules.............................................................................................35Expressions............................................................................................36Operator Precedence..............................................................................38Multiple Assignments..............................................................................38Order of Evaluation.................................................................................39Bitwise Operators....................................................................................40Compound Operators.............................................................................42Expressions that Mix Data Types: Typecasting.......................................44

Creating and Using Methods..........................................................................46Creating Methods....................................................................................48

Variable Scope................................................................................................51Exercise 2: Method Exercise...........................................................................53

iVersion: 2.0.2. Printed: 2019-01-17.

Table of Contents

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

3. Java Objects........................................................................................57

Objects............................................................................................................57Object-oriented Languages............................................................................58Object-oriented Programs...............................................................................59Encapsulation.................................................................................................60

OOP as a Messaging System.................................................................62Exercise 3: Object Definition...........................................................................63

Creating and Using an Instance of an Object.........................................65References......................................................................................................65

Reference Example.................................................................................67Reference Expressions...........................................................................68

Defining a Class..............................................................................................69Access to Data........................................................................................70

More on Access Terms...................................................................................71Adding Data Members to a Class...................................................................72

Adding Method Members (Functions) to a Class....................................73Standard Practices for Fields and Methods....................................................74

Order of Elements within a Class............................................................74Java Beans.....................................................................................................75Bean Properties..............................................................................................76Exercise 4: Payroll01: Creating an Employee Class ......................................79Constructors...................................................................................................82Instantiating Objects Revisited........................................................................84Important Note on Constructors.....................................................................85Exercise 5: Payroll02: Adding an Employee Constructor................................86Method Overloading.......................................................................................90Exercise 6: Payroll03: Overloading Employee Constructors...........................93The this Keyword............................................................................................97Using this to Call Another Constructor............................................................97Exercise 7: Payroll04: Using the this Reference...........................................101static Elements.............................................................................................104The main Method..........................................................................................104Exercise 8: Payroll05: A static field in Employee...........................................106Garbage Collection.......................................................................................111Java Packages..............................................................................................111Compiling and Executing with Packages......................................................112Working with Packages.................................................................................113Exercise 9: Payroll06: Creating an employees Package...............................118Variable Argument Lists (varargs).................................................................121

Keyboard I/O Using the Console Class.................................................123Keyboard Input Without the Console.....................................................128

Exercise 10: Payroll07: Using KeyboardReader in Payroll............................132String, StringBuffer, and StringBuilder..........................................................135Creating Documentation Comments and Using javadoc..............................135

Javadoc Comments..............................................................................135Exercise 11: Payroll08: Creating and Using javadoc Comments..................140Primitives and Wrapper Classes ..................................................................148

Autoboxing and Unboxing.....................................................................149

© Copyright 2019 Webucator. All rights reserved.ii

Table of Contents

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

4. Comparisons and Flow Control Structures....................................151

Boolean-valued Expressions........................................................................151Comparison Operators.................................................................................152Comparing Objects.......................................................................................152Conditional Expression Examples................................................................152Complex boolean Expressions.....................................................................153Simple Branching..........................................................................................155The if Statement...........................................................................................155if Statement Examples..................................................................................156

Absolute Value......................................................................................156Random Selection.................................................................................157

Exercise 12: Game01: A Guessing Game....................................................158Exercise 13: Payroll-Control01: Modified Payroll...........................................162Two Mutually Exclusive Branches.................................................................169

The if ... else Statement........................................................................169Nested if ... else Statements - Comparing a Number of Mutually ExclusiveOptions..................................................................................................170

Exercise 14: Game02: A Revised Guessing Game......................................172Comparing a Number of Mutually Exclusive options - The switch Statement.175

The switch Statement............................................................................175switch Statement Examples..................................................................176

Exercise 15: Game03: Multiple Levels..........................................................180Comparing Two Objects................................................................................184

Testing Strings for Equivalence.............................................................186Conditional Expression.................................................................................187

while and do . . . while Loops.................................................................188for Loops...............................................................................................190For-Each Loops ....................................................................................192

Exercise 16: Payroll-Control02: Payroll With a Loop.....................................194Exercise 17: Game04: Guessing Game with a Loop....................................198Additional Loop Control: break and continue................................................202

Breaking Out of a Loop.........................................................................202Continuing a Loop.........................................................................................203Classpath, Code Libraries, and Jar Files......................................................205

Using CLASSPATH...............................................................................205Creating a jar File (a Library)................................................................206

Exercise 18: Creating and Using an External Library...................................208Compiling to a Different Directory.................................................................209

iiiVersion: 2.0.2. Printed: 2019-01-17.

Table of Contents

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

5. Arrays.................................................................................................211

Defining and Declaring Arrays......................................................................211Instantiating Arrays.......................................................................................212Initializing Arrays...........................................................................................213Working With Arrays.....................................................................................214Enhanced for Loops - the For-Each Loop ....................................................216Array Variables..............................................................................................217Copying Arrays.............................................................................................219Exercise 19: Using the args Array.................................................................221Exercise 20: Game-Arrays01: A Guessing Game with Random Messages..224Arrays of Objects..........................................................................................228Exercise 21: Payroll-Arrays01: An Array of employees.................................229Multi-Dimensional Arrays..............................................................................232Multidimensional Arrays in Memory..............................................................232Example - Printing a Picture.........................................................................234Typecasting with Arrays of Primitives ...........................................................236

© Copyright 2019 Webucator. All rights reserved.iv

Table of Contents

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

6. Inheritance.........................................................................................239

Inheritance....................................................................................................239Inheritance Examples...................................................................................240Payroll with Inheritance.................................................................................241Derived Class Objects..................................................................................243Polymorphism...............................................................................................244

Inheritance and References..................................................................244Dynamic Method Invocation..................................................................245

Creating a Derived Class..............................................................................245Inheritance Example - A Derived Class .......................................................246Inheritance and Access................................................................................248Inheritance and Constructors - the super Keyword.......................................248Derived Class Methods that Override Base Class Methods.........................250Inheritance and Default Base Class Constructors........................................252The Instantiation Process at Runtime...........................................................255

Inheritance and static Elements............................................................255Example - Factoring Person Out of Employee..............................................256Exercise 22: Payroll-Inheritance01: Adding Types of Employees .................262Typecasting with Object References.............................................................271

More on Object Typecasts.....................................................................271Typecasting, Polymorphism, and Dynamic Method Invocation.............272

More on Overriding.......................................................................................274Changing Access Levels on Overridden Methods................................274Redefining Fields..................................................................................274

Object Typecasting Example.........................................................................275Checking an Object's Type: Using instanceof ..............................................277Typecasting with Arrays of Objects...............................................................278Exercise 23: Payroll-Inheritance02: Using the Employee Subclasses..........280Other Inheritance-related Keywords.............................................................285

abstract ................................................................................................285final.......................................................................................................285

Exercise 24: Payroll-Inheritance03: Making our base classes abstract........287Methods Inherited from Object.....................................................................290

vVersion: 2.0.2. Printed: 2019-01-17.

Table of Contents

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

7. Interfaces...........................................................................................295

Interfaces......................................................................................................295Creating an Interface Definition....................................................................296Implementing Interfaces................................................................................297

Implementing Interfaces - Example.......................................................298Reference Variables and Interfaces..............................................................299

Calling an Interface Method..................................................................300Interfaces and Inheritance............................................................................302Exercise 25: Exercise: Payroll-Interfaces01..................................................304Some Uses for Interfaces.............................................................................312

Interfaces and Event-Handling..............................................................312Interfaces and "Pluggable Components"..............................................314Marker Interfaces..................................................................................320

Annotations...................................................................................................321Annotation Details ........................................................................................321Using Annotations.........................................................................................322

8. Exceptions.........................................................................................325

Exceptions....................................................................................................325Handling Exceptions.....................................................................................326Exception Objects.........................................................................................327Attempting Risky Code - try and catch ........................................................329

try ... catch Blocks and Variable Scope/Initialization.............................330Example - An Exception You Must Handle............................................331Using Multiple catch Blocks..................................................................333

Guaranteeing Execution of Code - The finally Block.....................................334Letting an Exception be Thrown to the Method Caller..................................337Throwing an Exception.................................................................................338Exercise 26: Payroll-Exceptions01: Handling NumberFormatException inPayroll...........................................................................................................339Exercise 27: Payroll-Exceptions01, continued..............................................341Exceptions and Inheritance..........................................................................351

Exception Class Constructors and Methods.........................................351Creating and Using Your Own Exception Classes........................................353Exercise 28: Payroll-Exceptions02................................................................357Rethrowing Exceptions.................................................................................365Initializer Blocks............................................................................................365

Static Initializer Blocks..........................................................................366Logging.........................................................................................................367

Creating a Logger ................................................................................367Logger Hierarchy and Naming..............................................................368Log Handlers.........................................................................................368Log Formatters......................................................................................369

Log Properties..............................................................................................372Assertions.....................................................................................................374

© Copyright 2019 Webucator. All rights reserved.vi

Table of Contents

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

9. Collections.........................................................................................377

Collections....................................................................................................377Using the Collection Classes........................................................................380Using the Iterator Interface...........................................................................382Creating Collectible Classes.........................................................................386

hashCode and equals...........................................................................386Comparable and Comparator................................................................386

Generics.......................................................................................................390Bounded Types.............................................................................................393Extending Generic Classes and Implementing Generic Interfaces .............394Generic Methods..........................................................................................394Variations on Generics - Wildcards ..............................................................395Exercise 29: Payroll Using Generics.............................................................397

10. Inner Classes...................................................................................403

Inner Classes, aka Nested Classes..............................................................403Inner Class Syntax........................................................................................405Instantiating an Inner Class Instance from within the Enclosing Class.........407Inner Classes Referenced from Outside the Enclosing Class......................408Referencing the Outer Class Instance from the Inner Class Code ..............409

static Inner Classes ..............................................................................409Better Practices for Working with Inner Classes...........................................411Enums...........................................................................................................423

Why Another Syntax Element for a Set of Constants? ........................423Defining an enum Class........................................................................424More Complex Enums...........................................................................427

viiVersion: 2.0.2. Printed: 2019-01-17.

Table of Contents

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Java Introduction1.In this lesson, you will learn...1. About the Java Runtime Environment and how a Java program is created,

compiled, and run.2. How to download, install, and set up the Java Development Kit Standard

Edition.3. How to create a simple Java program.

Conventions in These Notes1.1

Code is listed in a monospace font, both for code examples and for Java keywordsmentioned in the text.

The standard Java convention for names is used:

• Class names are listed with an initial uppercase letter.• Variable and function names are listed with an initial lowercase letter.• The first letters of inner words are capitalized (e.g., maxValue).

For syntax definitions:

• Terms you must use as is are listed in normal monospace type.

Page 1 of 428Version: 2.0.2. Printed: 2019-01-17.

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

• Terms that you must substitute for, either one of a set of allowable values, ora name of your own, or code, listed in italics.

• The following generic terms are used - you must substitute an appropriate term.

Substitution OptionsGeneric TermsAn access word from: public, protected, private, orit can be omitted

access

one or more terms that modify a declaration; these include theaccess terms as well as terms like: static, transient, orvolatile

modifiers

A data type word; this can be a primitive, such as int, or thename of a class, such as Object; variants of this include:returnType and paramType

dataType

The name of a variable; variants on this include paramNameand functionName

variableName

The name of a class; there will be variants of this used fordifferent types of examples, such as: BaseClassName,DerivedClassName, InterfaceName, andExceptionClassName

ClassName

Executable code goes herecode

In an example, omitted code not related to the topic. . .

Don't worry if some (or all) of the terms in the table above don't make sense rightnow - we'll cover all of this material in detail as we move through the course.

The Java Environment - Overview1.2

A Java program is run differently than a traditional executable program.

Traditional programs are invoked through the operating system (OS).

© Copyright 2019 Webucator. All rights reserved.Page 2 of 428

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

• They occupy their own memory space.• They are tracked as an individual process by the OS.

Traditional programs are compiled from source code into a machine and OS-specificbinary executable file.

• To run the program in different environments, the source code would becompiled for that specific target environment.

When you run a Java program, the OS is actually running the Java Runtime Engine,or JRE, as an executable program; it processes your compiled code through the JavaVirtual Machine (usually referred to as the JVM).

A Java source code file is compiled into a bytecode file.

• You can consider bytecode as a sort of generic machine language.• The compiled bytecode is read by the JVM as a data file.• The JVM interprets the bytecode at runtime, performing a final mapping of

bytecode to machine language for whatever platform it is running on.• Thus, Java programs are portable - they can be written in any environment,

compiled in any environment, and run in any environment (as long as a JVMis available for that environment).

• The JVM manages its own memory area and allocates it to your program asnecessary.

• Although this involves more steps at runtime, Java is still very efficient, muchmore so than completely interpreted languages like JavaScript, since thetime-consuming parsing of the source code is done in advance.

Writing a Java Program1.3

Java source code is written in plain text, using a text editor.

• This could range from a plain text editor like Notepad, to a programmer's editorsuch as TextPad, EditPlus, or Crimson Editor, to a complex integrateddevelopment environment (IDE) like NetBeans, Eclipse, or JDeveloper.

• The source code file should have a .java extension.

The javac compiler is then used to compile the source code into bytecode. Thefollowing command, run from the command line (the "Command Prompt", alsoknown as "cmd", on a Windows computer; "Terminal" on a Mac), would compilethe source-code file MyClass.java into the bytecode file MyClass.class:

javac MyClass.java

Page 3 of 428Version: 2.0.2. Printed: 2019-01-17.

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

• The bytecode is stored in a file with an extension .class• Bytecode is universal - one bytecode file will run on any supported platform.

You then run the java runtime engine, which will then interpret the bytecode toexecute the program. This command runs the compiled bytecode:

java MyClass

• The executable program you are running is: java.• The class name tells the JVM what class to load and run the mainmethod for.• You must have a JVM made specifically for your hardware/OS platform.

Obtaining The Java Environment1.4

You can download the SDK (software development kit), including the compiler andruntime engine, for free from oracle.com at: http://www.oracle.com/technetwork/ja

© Copyright 2019 Webucator. All rights reserved.Page 4 of 428

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

va/javase/downloads/index.html. Look for the download of the latest release of JavaSE. You want the Java Development Kit (JDK) download:

From the next page, accept the license agreement and choose the JDK appropriatefor your operating system. Windows users would select the last item:

Page 5 of 428Version: 2.0.2. Printed: 2019-01-17.

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Run the installer, accepting the default directory locations and options.

You can also download the API documentation and even the source code. Note that:

• The documentation lists all the standard classes in the API, with their data fieldsand methods, as well as other information necessary to use the class. You willfind this documentation helpful as you work through some of the exercises.

• You can view the docs online, but it is worth downloading it (https://docs.oracle.com/javase/10/docs/api/overview-summary.html) so that you don't have tobe connected to the internet to use it.

© Copyright 2019 Webucator. All rights reserved.Page 6 of 428

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Setting up Your Java Environment1.5

Java programs are compiled and run from an operating system prompt, unless youhave installed an IDE that will do this for you directly.

After you have installed the JDK, you will need to set at least one environmentvariable in order to be able to compile and run Java programs.

For more complex projects that pull together elements from different sources, youmust set an additional environment variable or two. Note that:

• a PATH environment variable enables the operating system to find the JDKexecutables when your working directory is not the JDK's binary directory.

• CLASSPATH is Java's analog to PATH, the compiler and JVM use it to locateJava classes.• Often you will not need to set this, since the default setting is to use the

JDK's library jar file and the current working directory.• But, if you have additional Java classes located in another directory (a

third-party library, perhaps), you will need to create a classpath thatincludes not only that library, but the current working directory as well(the current directory is represented as a dot).

• Many IDE's and servers expect to find a JAVA_HOME environment variable.• This would be the JDK directory (the one that contains bin and lib).• The PATH is then set from JAVA_HOME plus \bin.• This makes it easy to upgrade your JDK, since there is only one entry you

will need to change.

Best Practice: Setting PATH from JAVA_HOME

The instructions below will help you to create a JAVA_HOME environment variableand add a PATH entry from JAVA_HOME.

1. First, find the full path of the directory in which the JDK was installed:

Page 7 of 428Version: 2.0.2. Printed: 2019-01-17.

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

• The screenshot above shows the path after we accepted the default locationwhen installing the JDK; in this example, the path is C:\ProgramFiles\Java\jdk-10.0.2

© Copyright 2019 Webucator. All rights reserved.Page 8 of 428

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

2. Search for Environment Variables (on an older PC, right-click on MyComputer, choose Properties, select the Advanced tab):•

3. Check both the User and System variable lists to see if JAVA_HOME or PATHalready exist.

Page 9 of 428Version: 2.0.2. Printed: 2019-01-17.

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

4. If JAVA_HOME exists, check to see that it matches the JDK path from theinstallation - in our example above, that would be the path C:\ProgramFiles\Java\jdk-10.0.2A. If JAVA_HOME exists under System variables, click Edit, if not, click

AddB. For Variable name, enter JAVA_HOMEC. For Variable value, enter the JDK directory, such as

C:\Program Files\Java\jdk-10.0.2:D.

© Copyright 2019 Webucator. All rights reserved.Page 10 of 428

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

5. Next, add an entry to the PATH to reference the JAVA_HOME system variableyou just created:A. In the unlikely case that a PATH System variable does not already exist,

create a new System variable; most likely you will be editing an existingPATH System variable

B. If there isn't already a JDK bin directory mentioned in the PATH, it willwork as a User variable.

C. If there is already a JDK mentioned, you would want to ensure that thisnew entry preceded the existing entry, so you would edit that variable.

D. Note that if the existing entry was created using JAVA_HOME, then weare already set correctly.

E. If no entry exists already, add %JAVA_HOME%\bin as the new PATHentry.

Page 11 of 428Version: 2.0.2. Printed: 2019-01-17.

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

F. In the screenshot below, we edited the existing PATH System variable,adding a new entry that references the JAVA_HOME System variable weset previously:

6. Once you have completed these steps, open a command line window and typejavac -version and press enter; you should see a response like in thefollowing screenshot:

© Copyright 2019 Webucator. All rights reserved.Page 12 of 428

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

If you don't see the version returned or if you see an error, then ask yourinstructor for assistance.

Creating a Class that Can Run as a Program1.6

The main()MethodIn order to run as a program, a class must contain a method named main, with aparticular argument list. This is similar to the C and C++ languages.

The method declaration goes inside your class definition, and looks like:

public static void main(String[] args) {(code goes here)}

• It must be public, because it will be called from outside your class (by theJVM).

• The static keyword defines an element (could be data or functional) thatwill exist regardless of whether an object of a class has been instantiated. Inother words, declaring main as static allows the JVM to call the methodand therefore execute the program. That doesn't mean that an object of thatclass cannot be instantiated, it is just not required.

• The String[] args parameter states that there will be an array of Stringobjects given to the method - these are the command line arguments.

• To run the program, you would first compile a file named ClassName.java withthe following from the command line:

javac ClassName.java

Page 13 of 428Version: 2.0.2. Printed: 2019-01-17.

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

and then use the following from the command line to run the program:

java ClassName

For example, if we had an executable class called Hello, in a file calledHello.java that compiled to Hello.class, you could run it with:

java Hello

As above, if terms like "static" and "instantiated" don't make too much sense rightnow, don't worry - we will cover these concepts in detail soon.

Useful Stuff Necessary to Go Further1.7

System.out.println()In order to see something happen, we need to be able to print to the screen.

There is a System class that is automatically available when your program runs(everything in it is static).

• It contains, among other things, input and output streams that match stdin,stdout, and stderr (standard output, standard input, and standard error).

System.out is a static reference to the standard output stream.

As an object, System.out contains a println(String)method that acceptsa String object, and prints that text to the screen, ending with a newline (linefeed).

• There is also a print(String)method that does not place a newline at theend.

You can print a String directly, or you can build one from pieces.

• It is worth noting that a String will automatically be created from aquote-delimited series of characters.

• Values can be appended to a String by using the + sign; if one item is aString or quote-delimited series of characters, then the rest can be any othertype of data.

Using an Integrated Development Environment1.8

Integrated Development Environments, or IDEs, can greatly facilitate the task ofcreating applications. Mid-level code editors, such as Crimson Editor, TextPad, or

© Copyright 2019 Webucator. All rights reserved.Page 14 of 428

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Edit-Plus, provide syntax highlighting, automatic indenting, parentheses andcurly-brace matching, and may have tools to compile and execute programs.

High-end environments, such as Eclipse, NetBeans, or JDeveloper, offer manyadditional features, such as project management, automatic deployment for webapplications, code refactoring, code assist, etc. But, these additional capabilitiescomewith the price of additional complexity in the environment, particularly becausethey force you to create projects for even the simplest applications.

To use the class files in these environments, we must first have a workspace, whichis a collection of projects. Workspaces have various configuration settings that willcut across all projects within all projects they contain, such as which version of Javais in use, any added libraries, etc. (a project is usually one application).

Both Eclipse and NetBeans use the workspace concept, but you can start with anyempty directory - the IDE will add its own special files as you create projects.

In theWindows Explorer, navigate to your ClassFiles directory. If it does not containa Workspace subdirectory, create it.

To use Eclipse with the class files, you can direct it to the workspace(ClassFiles/Workspace) when it opens (if it asks), or use File, SwitchWorkspace if Eclipse is already running. Each chapter's demo folder should betreated as a project, as should each Solution folder.

One limitation of these environments is that no project can contain the same Javaclass twice, so our progressive versions of the Payroll application solution requiretheir own individual project. Also, due to the way Java's package structures work,each Demo folder must be a separate project, as with each subdirectory underSolutions.

To use the Exercises folder as an Eclipse project:

1. Select File, New ... Java Project from the menu (if JavaProject is not immediately available, choose Project ... first - themenu items are usage-sensitive).

2. Name the project Exercises.3. check Create project from existing source.

Page 15 of 428Version: 2.0.2. Printed: 2019-01-17.

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

4. Browse to the Exercises directory, and OK it.5. You can then Finish the dialog box.

As we encounter each chapter, we can create a project using the Demos directoryfor that chapter the same way we just created the Exercises project..

To create a Java class within a project, use File, New, and then Class if thatis available, or Other... and then Class. Provide a name and then OK.

In general, with the several applications that we will build upon progressively (Gameand Payroll), you can continue to work with the same files, and add to them as wecover additional topics. If you want to check the solutions, you can either open thosefiles in a separate editor, like Notepad, or create a project for that Solutionssubdirectory. If you wish to save a particular stage of the application for futurereference, you can just make a copy of the Exercises directory.

The examples and instructions going forward in this course assume the use of a basictext editor and the command line. You are free to choose which tool to use. If Eclipsebecomes a problem, move to a simple editor. The focus of this course is on the JavaProgramming Language and not a particular tool.

© Copyright 2019 Webucator. All rights reserved.Page 16 of 428

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Running a Simple Java ProgramExercise 15 to 15 minutes

1. Use a text editor or IDE to open Java-Introduction/Exercises/Hello.java.2. Note that the file is intentionally blank.3. Enter the following code:

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

4. Save the file.5. In a command prompt window, change to the directory where Hello.java is

stored and type the following

javac Hello.java

and press Enter. A prompt on the next line without any error messages indicatessuccess.

6. Next, type

java Hello

7. Press Enter. You should see the message Hello World print in the window.

Code Explanation

public class Hello

• All Java code must be within a class definition.• A class defines a type of object.• A public class can be accessed by any other class.• A public class must be in its own file, whose name is the name of the class,

plus a dot and an file extension of java (e.g., Hello.java).

{. . .}

• Curly braces denote a block of code (the code inside the braces).• Code within braces usually belongs to whatever immediately precedes them.

public static void main(String[] args) {

• Words followed by parentheses denote a function.

Page 17 of 428Version: 2.0.2. Printed: 2019-01-17.

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

• To be executable by itself, a class must have a function defined in this fashion;the name main means that execution will start with the first step of thisfunction, and will end when the last step is done.

• It is public because it needs to be executed by other Java objects (the JVMitself is a running Java program, and it launches your program and calls itsmain function).

• It is static because it needs to exist even before one of these objects hasbeen created.

• It does not return an answer when it is done; the absence of data is called void.• The String[] args represents the additional data that might have been

entered on the command line.

System.out.println("Hello World!");

• System is an class within the JVM that represents system resources.• It contains an object called out, which represents output to the screen (what

many environments call standard out).• Note that an object's ownership of an element is denoted by using the name of

the object, a dot, and then the name of the element.• out in turn contains a function, println, that prints a line onto the screen

(and appends a newline at the end).• A function call is denoted by the function name followed by parentheses; any

information inside the parentheses is used as input to the function (calledarguments or parameters to the function).

• The argument passed toprintln() is the string of text"Hello World!".• Note that the statement ends in a semicolon (as all do Java statements).

© Copyright 2019 Webucator. All rights reserved.Page 18 of 428

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Using the Java Documentation1.9

Oracle provides extensive Java documentation. The homepage for Java documentationin English is at https://docs.oracle.com/en/java/. Documentation for the platform(JDK Standard Edition, or "SE") that you will use in this course is athttps://docs.oracle.com/javase/10/ for the current version - version 10 as of thiswriting.

This page offer a wealth of resources - videos, downloadable books, etc. - to helpyou learn Java. Perhaps the most useful is the API reference - a detailed list of allof the built-in features of Java available to you when programming in the language:

https://docs.oracle.com/javase/10/docs/api/overview-summary.html

If you view that page, you will see a list of classes on the left as hyperlinks. Clickinga class name will bring up the documentation for that class on the right.

For example, click on java.base, then java.lang, then out under "FieldSummary" to get to this page:

https://docs.oracle.com/javase/10/docs/api/java/lang/System.html#out

From this page you can find the println methods we looked at above in a tablewith short descriptions. Select one to see the detailed description. The multipleversions are an example ofmethod overloading, which we will cover in an upcominglesson. Another lesson will cover documenting your own classes with the same toolthat created this documentation.

In this lesson, you have learned:

Conclusion1.10In this lesson you have learned:

1. About the Java Runtime Environment.2. How to download, install, and set up the Java Development Kit Standard

Edition.3. How to create a simple Java program.

Page 19 of 428Version: 2.0.2. Printed: 2019-01-17.

Java Introduction

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

7400 E. Orchard Road, Suite 1450 NGreenwood Village, Colorado 80111

Ph: 303-302-5280www.ITCourseware.com

9-38-00237-000-02-25-19

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited