Java SE 8 - Guía de Estudio Vol.1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 304

Matis Consulting SฺCฺ

Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
e rná to us
e r o H ense
err leSE
Java
u lic 8 Fundamentals
é G rab
J s
o nsfe
r
ga n-tra
d
E no Student Guide - Volume I
D83527GC10
Edition 1.0 | December 2016 | D87049

Learn more from Oracle University at education.oracle.com


Matis Consulting SฺCฺ

Authors Copyright © 2014, 2015, 2016 Oracle and/or its affiliates. All rights reserved.

Kenneth Somerville Disclaimer

Jill Moritz This document contains proprietary information and is protected by copyright and
Cindy Church other intellectual property laws. You may copy and print this document solely for your
own use in an Oracle training course. The document may not be modified or altered
Nick Ristuccia in any way. Except where your use constitutes "fair use" under copyright law, you
may not use, share, download, upload, copy, print, display, perform, reproduce,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

publish, license, post, transmit, or distribute this document in whole or in part without
Technical Contributors the express authorization of Oracle.
and Reviewers
The information contained in this document is subject to change without notice. If you
Kenneth Somerville find any problems in the document, please report them in writing to: Oracle University,
500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
Peter Fernandez warranted to be error-free.
Jill Moritz
Restricted Rights Notice
Cindy Church
Nick Ristuccia If this documentation is delivered to the United States Government or anyone using
the documentation on behalf of the United States Government, the following notice is
Tom McGinn applicable:
Mike Williams
U.S. GOVERNMENT RIGHTS
a
has
Matt Heimer The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or
disclose these training materials are restricted by the terms of the applicable Oracle
)
om ฺ
license agreement and/or the applicable U.S. Government contract.
Editors c
Anwesha Ray
Trademark Notice l ฺ
ai ide
Raj Kumar
m
g t Gu
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names
4 @
h d u d en
may be trademarks of their respective owners.
2
Graphic Designers
( e d S t
Divya Thallap ez e th i s
n d
Rajiv Chandrabhanu
Daniel Milne e rná to us
e r o H ense
Publishers
u err le lic
é
Michael Sebastian G rab
J s
o nsfe
Veena Narasimhan
r
gaBrozowski tra
dNita
E Sumesh n -
noKoshy
Matis Consulting SฺCฺ

Contents
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1 Introduction
About This Course 1-2
Audience 1-3
Course Objectives 1-4
Schedule 1-6
Course Environment 1-9
Test Your Lab Machines 1-11
How Do You Learn More After the Course? 1-12
a
has
Quiz 1-13
)
om ฺ
Summary 1-14
l ฺ c
m ai ide
2 What Is a Java Program?
@ g t Gu
Objectives 2-2
d 2 4 en
Topics 2-3
d h t u d
( e i s S
Purpose of a Computer Program 2-4
n d ez e th
rná 2-6to us
Translating High-Level Code to Machine Code 2-5
e
Linked to Platform-Specific Libraries
r o H e2-7nse
Platform-Dependent Programs
e
Topics 2-8
u err le lic
é
Key FeaturesGof therJava
a b Language 2-9
s sf e
JoIs Platform-Independent
Java 2-10
a r a n
-tr Run In a Java Virtual Machine 2-11
g JavanPrograms
Ed Procedural
o
n Programming Languages 2-12
Java Is an Object-Oriented Language 2-13
Topics 2-14
Verifying the Java Development Environment 2-15
Examining the Installed JDK (Linux Example): The Tools 2-16
Examining the Installed JDK (Windows Example): The Libraries 2-17
Topics 2-18
Compiling and Running a Java Program 2-19
Compiling a Program 2-20
Executing (Testing) a Program 2-21
Output for a Java Program 2-22
Exercise 2-1 2-23

iii
Matis Consulting SฺCฺ

Quiz 2-24
Summary 2-25

3 Creating a Java Main Class


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Objectives 3-2
Topics 3-3
Java Classes 3-4
Program Structure 3-5
Java Packages 3-6
Using the Java Code Console 3-7
Using the Java Code Console: Creating a New Java Class 3-8
Using the Java Code Console: Creating a New Java Class for an Exercise 3-9
Exercise 3-1: Creating a Class 3-10
a
has
Topics 3-11
The main Method 3-12 )
A main Class Example 3-13
l ฺ c om ฺ
Output to the Console 3-14
m ai ide
Fixing Syntax Errors 3-15 @ g t Gu
d 2 4 en
Exercise 3-2: Creating a main Method 3-16
d h t u d
Quiz 3-17 ( e i s S
Summary 3-18
n d ez e th
e rná to us
4 Data in a Cart
r o H se
Objectives 4-2 rr e l i c en
Topics 4-3Gu
e le
é r a b
s
Jo Types
Variables 4-4 e
sf4-5
a r a n
g n-tar Variable 4-6
Variable
Ed Naming
n o
Uses of Variables 4-7
Topics 4-8
Variable Declaration and Initialization 4-9
String Concatenation 4-10
String Concatenation Output 4-11
Exercise 4-1: Using String Variables 4-12
Quiz 4-13
Topics 4-14
int and double Values 4-15
Initializing and Assigning Numeric Values 4-16
Topics 4-17
Standard Mathematical Operators 4-18
Increment and Decrement Operators (++ and --) 4-19

iv
Matis Consulting SฺCฺ

Operator Precedence 4-20


Using Parentheses 4-22
Exercise 4-2: Using and Manipulating Numbers 4-23
Quiz 4-24
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Summary 4-26

5 Managing Multiple Items


Objectives 5-2
Topics 5-3
Making Decisions 5-4
The if/else Statement 5-5
Boolean Expressions 5-6
Relational Operators 5-7
a
has
Examples 5-8
Exercise 5-1: Using if Statements 5-9 )
Quiz 5-10
l ฺ c om ฺ
Topics 5-11
m ai ide
@ g t Gu
What If There Are Multiple Items in the Shopping Cart? 5-12
d 2 4 en
Introduction to Arrays 5-13
d h t u d
Array Examples 5-14 ( e i s S
d
Array Indices and Length 5-15
n ez e th
rná to us
Declaring and Initializing an Array 5-16
e
e r o H ense
Accessing Array Elements 5-18

err le lic
Exercise 5-2: Using an Array 5-19
u
G rab
Quiz 5-20
é
s
o nsfe
Topics 5-22
J
r
ga n-tra
Loops 5-23
d
E no Processing a String Array 5-24
Using break with Loops 5-25
Exercise 5-3: Using a Loop to Process an Array 5-26
Quiz 5-27
Summary 5-28
Play Time! 5-29
About Java Puzzle Ball 5-30
Tips 5-31

6 Describing Objects and Classes


Interactive Quizzes 6-2
Objectives 6-3
Topics 6-4
Java Puzzle Ball 6-5

v
Matis Consulting SฺCฺ

Java Puzzle Ball Debrief 6-6


Object-Oriented Programming 6-7
Duke’s Choice Order Process 6-8
Characteristics of Objects 6-9
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Classes and Instances 6-10


Quiz 6-11
Topics 6-12
The Customer Properties and Behaviors 6-13
The Components of a Class 6-14
Modeling Properties and Behaviors 6-15
Exercise 6-1: Creating the Item Class 6-16
Topics 6-17
Customer Instances 6-18
a
has
Object Instances and Instantiation Syntax 6-19
The Dot (.) Operator 6-20 )
Objects with Another Object as a Property 6-21
l ฺ c om ฺ
Quiz 6-22
m ai ide
Topics 6-23 @ g t Gu
d 2 4 en
d h
Accessing Objects by Using a Reference 6-24
t u d
( e
Working with Object References 6-25
i s S
d ez e th
References to Different Objects 6-28
n
rná to us
References and Objects in Memory 6-30
e
e r o H ense
Assigning a Reference to Another Reference 6-31

err le lic
Two References, One Object 6-32
u
G rab
Exercise 6-2: Modify the ShoppingCart to Use Item Fields 6-33
é
s
o nsfe
Topics 6-34
J
r
ga n-tra
Arrays Are Objects 6-35
d
E no Declaring, Instantiating, and Initializing Arrays 6-36
Storing Arrays in Memory 6-37
Storing Arrays of Object References in Memory 6-38
Quiz 6-39
Topics 6-41
Java IDEs 6-42
The NetBeans IDE 6-43
Creating a Java Project 6-44
Creating a Java Class 6-45
Avoiding Syntax Problems 6-46
Compile Error: Variable Not Initialized 6-47
Runtime Error: NullPointerException 6-48
Compiling and Running a Program by Using NetBeans 6-49
Topics 6-50

vi
Matis Consulting SฺCฺ

Soccer Application 6-51


Creating the Soccer Application 6-52
Soccer Web Application 6-53
Summary 6-54
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Challenge Questions: Java Puzzle Ball 6-55


Practice 6-1 Overview: Creating Classes for the Soccer League 6-56
Practice 6-2 Overview: Creating a Soccer Game 6-57

7 Manipulating and Formatting the Data in Your Program


Objectives 7-2
Topics 7-3
String Class 7-4
Concatenating Strings 7-5
a
has
String Method Calls with Primitive Return Values 7-8
String Method Calls with Object Return Values 7-9 )
Topics 7-10
l ฺ c om ฺ
Java API Documentation 7-11
m ai ide
Java Platform SE 8 Documentation 7-12 @ g t Gu
d 2 4 en
d h
Java Platform SE 8: Method Summary 7-13
t u d
( e
Java Platform SE 8: Method Detail 7-14
i s S
indexOf Method Example 7-15
n d ez e th
Topics 7-16
e rná to us
e r o H ense
StringBuilder Class 7-17

err le lic
StringBuilder Advantages over String for Concatenation (or Appending) 7-18
u
G rab
StringBuilder: Declare and Instantiate 7-19
é
s
o nsfe
StringBuilder Append 7-20
J
r
ga n-tra
Quiz 7-21
d
E no Exercise 7-1: Use indexOf and substring Methods 7-22
Exercise 7-2: Instantiate the StringBuilder object 7-23
Topics 7-24
Primitive Data Types 7-25
Some New Integral Primitive Types 7-26
Floating Point Primitive Types 7-28
Textual Primitive Type 7-29
Java Language Trivia: Unicode 7-30
Constants 7-31
Quiz 7-32
Topics 7-33
Modulus Operator 7-34
Combining Operators to Make Assignments 7-35
More on Increment and Decrement Operators 7-36

vii
Matis Consulting SฺCฺ

Increment and Decrement Operators (++ and ––) 7-37


Topics 7-38
Promotion 7-39
Caution with Promotion 7-40
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Type Casting 7-42


Caution with Type Casting 7-43
Using Promotion and Casting 7-45
Compiler Assumptions for Integral and Floating Point Data Types 7-46
Automatic Promotion 7-47
Using a long 7-48
Using Floating Points 7-49
Floating Point Data Types and Assignment 7-50
Quiz 7-51
a
has
Exercise 7-3: Declare a Long, Float, and Char 7-52
Summary 7-53 )
Play Time! 7-54
l ฺ c om ฺ
Practice 7-1 Overview: Manipulating Text 7-55
m ai ide
@ g t Gu
d 2 4 en
8 Creating and Using Methods
d h t u d
Objectives 8-2 ( e i s S
Topics 8-3
n d ez e th
Basic Form of a Method 8-4 rná
e t o us
o H Class
Calling a Method from a Different
r se 8-5
r e
Caller and Worker rMethods c e n
u e e l i8-6
A ConstructorG rab
Method l
8-7
s é
o Calling
Writing and fe a Constructor 8-8
r J n s
a in the Same Class 8-9
d gaCalling
n -atrMethod
E Topics
n o 8-10
Method Arguments and Parameters 8-11
Method Parameter Examples 8-12
Method Return Types 8-13
Method Return Types Examples 8-14
Method Return Animation 8-15
Passing Arguments and Returning Values 8-16
More Examples 8-17
Code Without Methods 8-18
Better Code with Methods 8-19
Even Better Code with Methods 8-20
Variable Scope 8-21
Advantages of Using Methods 8-22
Exercise 8-1: Declare a setColor Method 8-23

viii
Matis Consulting SฺCฺ

Topics 8-24
Java Puzzle Ball 8-25
Java Puzzle Ball Debrief 8-26
Static Methods and Variables 8-27
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Example: Setting the Size for a New Item 8-28


Creating and Accessing Static Members 8-29
When to Use Static Methods or Fields 8-30
Some Rules About Static Fields and Methods 8-31
Static Fields and Methods vs. Instance Fields and Methods 8-32
Static Methods and Variables in the Java API 8-33
Examining Static Variables in the JDK Libraries 8-34
Using Static Variables and Methods: System.out.println 8-35
More Static Fields and Methods in the Java API 8-36
a
has
Converting Data Values 8-37
Topics 8-38 )
Passing an Object Reference 8-39
l ฺ c om ฺ
What If There Is a New Object? 8-40
m ai ide
A Shopping Cart Code Example 8-41 @ g t Gu
d 2 4 en
Passing by Value 8-42
d h t u d
Reassigning the Reference 8-43 ( e i s S
Passing by Value 8-44
n d ez e th
Topics 8-45
e rná to us
e r o H ense
Method Overloading 8-46

err le lic
Using Method Overloading 8-47
u
G rab
Method Overloading and the Java API 8-49
é
s
o nsfe
Exercise 8-2: Overload a setItemFields Method 8-50
J
r
ga n-tra
Quiz 8-51
d
E no Summary 8-52
Challenge Questions: Java Puzzle Ball 8-53
Practice 8-1 Overview: Using Methods 8-54
Practice 8-2 Overview: Creating Game Data Randomly 8-55
Practice 8-3 Overview: Creating Overloaded Methods 8-56

9 Using Encapsulation
Interactive Quizzes 9-2
Objectives 9-3
Topics 9-4
What Is Access Control? 9-5
Access Modifiers 9-6
Access from Another Class 9-7
Another Example 9-8

ix
Matis Consulting SฺCฺ

Using Access Control on Methods 9-9


Topics 9-10
Encapsulation 9-11
Get and Set Methods 9-12
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Why Use Setter and Getter Methods? 9-13


Setter Method with Checking 9-14
Using Setter and Getter Methods 9-15
Exercise 9-1: Encapsulate a Class 9-16
Topics 9-17
Initializing a Shirt Object 9-18
Constructors 9-19
Shirt Constructor with Arguments 9-20
Default Constructor and Constructor with Args 9-21
a
has
Overloading Constructors 9-22
Quiz 9-23 )
Exercise 9-2: Create an Overloaded Constructor 9-24
l ฺ c om ฺ
Summary 9-25
m ai ide
Play Time! 9-26 @ g t Gu
d 2 4 en
Practice 9-1 Overview: Encapsulating Fields 9-27
d h t u d
( e s S
Practice 9-2 Overview: Creating Overloaded Constructors 9-28
i
n d ez e th
10 More on Conditionals
e rná to us
Objectives 10-2
r o H se
Topics 10-3 r r e l i c en
G ue Operators
Review: Relational b le 10-4
é fBetween
sEquality a
er String variables 10-5
J o
Testing
s
g aCommon
- an
r trConditional Operators 10-9
d
E Ternary n
o Conditional Operator 10-10
n
Using the Ternary Operator 10-11
Exercise 10-1: Using the Ternary Operator 10-12
Topics 10-13
Java Puzzle Ball 10-14
Java Puzzle Ball Debrief 10-15
Handling Complex Conditions with a Chained if Construct 10-16
Determining the Number of Days in a Month 10-17
Chaining if/else Constructs 10-18
Exercise 10-2: Chaining if Statements 10-19
Topics 10-20
Handling Complex Conditions with a switch Statement 10-21
Coding Complex Conditions: switch 10-22
switch Statement Syntax 10-23

x
Matis Consulting SฺCฺ

When to Use switch Constructs 10-24


Exercise 10-3: Using switch Construct 10-25
Quiz 10-26
Topics 10-27
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Working with an IDE Debugger 10-28


Debugger Basics 10-29
Setting Breakpoints 10-30
The Debug Toolbar 10-31
Viewing Variables 10-32
Summary 10-33
Challenge Question: Java Puzzle Ball 10-34
Practice 10-1 Overview: Using Conditional Statements 10-35
Practice 10-2 Overview: Debugging 10-36
a
11 Working with Arrays, Loops, and Dates ) has
Interactive Quizzes 11-2
l ฺ c om ฺ
Objectives 11-3
m ai ide
Topics 11-4 @ g t Gu
d 2 4 en
Displaying a Date 11-5
h t u d
Class Names and the Import Statement 11-6 (ed S
ez e th i s
Working with Dates 11-7
n d
e
á
Working with Different Calendarsrn11-9
t o us
Some Methods of LocalDateH 11-10se
r
Formatting Dates r11-11 ero licen
e ale
uDeclare
é G
Exercise 11-1:
r a b LocalDateTime Object 11-12
r J os11-13
Topics
n s fe
d gaUsing n - traargs Array in the main Method 11-14
the
E Converting
n o String Arguments to Other Types 11-15
Exercise 11-2: Parsing the args Array 11-16
Topics 11-17
Describing Two-Dimensional Arrays 11-18
Declaring a Two-Dimensional Array 11-19
Instantiating a Two-Dimensional Array 11-20
Initializing a Two-Dimensional Array 11-21
Quiz 11-22
Topics 11-23
Some New Types of Loops 11-24
Repeating Behavior 11-25
A while Loop Example 11-26
Coding a while Loop 11-27
while Loop with Counter 11-28

xi
Matis Consulting SฺCฺ

Coding a Standard for Loop 11-29


Standard for Loop Compared to a while loop 11-30
Standard for Loop Compared to an Enhanced for Loop 11-31
do/while Loop to Find the Factorial Value of a Number 11-32
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Coding a do/while Loop 11-33


Comparing Loop Constructs 11-34
The continue Keyword 11-35
Exercise 11-3: Processing an Array of Items 11-36
Topics 11-37
Nesting Loops 11-38
Nested for Loop 11-39
Nested while Loop 11-40
Processing a Two-Dimensional Array 11-41
a
has
Output from Previous Example 11-42
Quiz 11-43 )
Topics 11-45
l ฺ c om ฺ
ArrayList Class 11-46
m ai ide
Benefits of the ArrayList Class 11-47 @ g t Gu
d 2 4 en
Importing and Declaring an ArrayList 11-48
d h t u d
Working with an ArrayList 11-49 ( e i s S
d ez e th
Exercise 11-4: Working with an ArrayList 11-50
n
Summary 11-51
e rná to us
Play Time! 11-52
e r o H ense
err le lic
Practice 11-1 Overview: Iterating Through Data 11-53
u
G rab
Practice 11-2 Overview: Working with LocalDateTime 11-54
é
J s
o nsfe
r
g12aUsing tra
Inheritance
d n
E Objectives
o -
n
Topics 12-3
12-2

Java Puzzle Ball 12-4


Java Puzzle Ball Debrief 12-5
Inheritance in Java Puzzle Ball 12-6
Implementing Inheritance 12-8
More Inheritance Facts 12-9
Topics 12-10
Duke’s Choice Classes: Common Behaviors 12-11
Code Duplication 12-12
Inheritance 12-13
Clothing Class: Part 1 12-14
Shirt Class: Part 1 12-15
Constructor Calls with Inheritance 12-16

xii
Matis Consulting SฺCฺ

Inheritance and Overloaded Constructors 12-17


Exercise 12-1: Creating a Subclass 12-18
Topics 12-19
More on Access Control 12-20
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Overriding Methods 12-21


Review: Duke’s Choice Class Hierarchy 12-22
Clothing Class: Part 2 12-23
Shirt Class: Part 2 12-24
Overriding a Method: What Happens at Run Time? 12-25
Exercise 12-2: Overriding a Method in the Superclass 12-26
Topics 12-27
Polymorphism 12-28
Superclass and Subclass Relationships 12-29
a
has
Using the Superclass as a Reference 12-30
Polymorphism Applied 12-31 )
Accessing Methods Using a Superclass Reference 12-32
l ฺ c om ฺ
Casting the Reference Type 12-33
m ai ide
instanceof Operator 12-34 @ g t Gu
d 2 4 en
d h
Exercise 12-3: Using the instanceof Operator 12-35
t u d
Topics 12-36 ( e i s S
Abstract Classes 12-37
n d ez e th
rná to us
Extending Abstract Classes 12-39
e
Summary 12-40
e r o H ense
err le lic
Challenge Questions: Java Puzzle Ball 12-41
u
G rab
Practice 12-1 Overview: Creating a Class Hierarchy 12-43
é
s
o nsfe
Practice 12-2 Overview: Creating a GameEvent Hierarchy 12-44
J
r tra
g13aUsingn-Interfaces
d
E no
Interactive Quizzes 13-2
Objectives 13-3
Topics 13-4
The Object Class 13-5
Calling the toString Method 13-6
Overriding toString in Your Classes 13-7
Topics 13-8
The Multiple Inheritance Dilemma 13-9
The Java Interface 13-10
Multiple Hierarchies with Overlapping Requirements 13-11
Using Interfaces in Your Application 13-12
Implementing the Returnable Interface 13-13
Access to Object Methods from Interface 13-14

xiii
Matis Consulting SฺCฺ

Casting an Interface Reference 13-15


Quiz 13-16
Topics 13-18
The Collections Framework 13-19
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

ArrayList Example 13-20


List Interface 13-21
Example: Arrays.asList 13-22
Exercise 13-1: Converting an Array to an ArrayList 13-24
Topics 13-25
Example: Modifying a List of Names 13-26
Using a Lambda Expression with replaceAll 13-27
Lambda Expressions 13-28
The Enhanced APIs That Use Lambda 13-29
a
has
Lambda Types 13-30
The UnaryOperator Lambda Type 13-31 )
The Predicate Lambda Type 13-32
l ฺ c om ฺ
Exercise 13-2: Using a Predicate Lambda Expression 13-33
m ai ide
Summary 13-34 @ g t Gu
d 2 4 en
d h
Practice 13-1 Overview: Overriding the toString Method 13-35
t u d
( e s S
Practice 13-2 Overview: Implementing an Interface 13-36
i
d ez e th
Practice 13-3 (Optional) Overview: Using a Lambda Expression for Sorting 13-37
n
e rná to us
14 Handling Exceptions
r o H se
Objectives 14-2 rr e l i c en
Topics 14-3 G ue ble
s
WhatoAre f e ra 14-4
éExceptions?
r s
J aofnExceptions
d aExamplest r
g CodenExample
- 14-5
E no 14-6
Another Example 14-7
Types of Throwable classes 14-8
Error Example: OutOfMemoryError 14-9
Quiz 14-10
Topics 14-11
Normal Program Execution: The Call Stack 14-12
How Exceptions Are Thrown 14-13
Topics 14-14
Working with Exceptions in NetBeans 14-15
The try/catch Block 14-16
Program Flow When an Exception Is Caught 14-17
When an Exception Is Thrown 14-18
Throwing Throwable Objects 14-19

xiv
Matis Consulting SฺCฺ

Uncaught Exception 14-20


Exception Printed to Console 14-21
Summary of Exception Types 14-22
Exercise 14-1: Catching an Exception 14-23
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Quiz 14-24
Exceptions in the Java API Documentation 14-25
Calling a Method That Throws an Exception 14-26
Working with a Checked Exception 14-27
Best Practices 14-28
Bad Practices 14-29
Somewhat Better Practice 14-30
Topics 14-31
Multiple Exceptions 14-32
a
has
Catching IOException 14-33
Catching IllegalArgumentException 14-34 )
Catching Remaining Exceptions 14-35
l ฺ c om ฺ
Summary 14-36
m ai ide
Interactive Quizzes 14-37 @ g t Gu
d 2 4 en
d h
Practice 14-1 Overview: Adding Exception Handling 14-38
t u d
( e i s S
15 Deploying and Maintaining the Soccer
n d ez e th
Application
Objectives 15-2
e rná to us
Topics 15-3
r o H se
Packages 15-4 rr e l i c en
G ue Structure
Packages Directory b le 15-5
séin NetBeans
f a
er 15-6
J o
Packages
s
r trainnSource Code 15-7
g aPackages
on- 15-8
Ed Topics
n
SoccerEnhanced.jar 15-9
Set Main Class of Project 15-10
Creating the JAR File with NetBeans 15-11
Topics 15-13
Client/Server Two-Tier Architecture 15-14
Client/Server Three-Tier Architecture 15-15
Topics 15-16
Client/Server Three-Tier Architecture 15-17
Different Outputs 15-19
The Soccer Application 15-20
IDisplayDataItem Interface 15-21
Running the JAR File from the Command Line 15-22
Text Presentation of the League 15-23

xv
Matis Consulting SฺCฺ

Web Presentation of the League 15-24


Topics 15-25
Enhancing the Application 15-26
Adding a New GameEvent Kickoff 15-27
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Game Record Including Kickoff 15-28


Summary 15-29
Course Summary 15-30

16 Oracle Cloud
Agenda 16-2
What is Cloud? 16-3
What is Cloud Computing? 16-4
History – Cloud Evolution 16-5
a
has
Components of Cloud Computing 16-6
Characteristics of Cloud 16-7 )
Cloud Deployment Models 16-8
l ฺ c om ฺ
Cloud Service Models 16-9
m ai ide
Industry Shifting from On-Premises to the Cloud 16-13 @ g t Gu
d 2 4 en
Oracle IaaS Overview 16-15
d h t u d
Oracle PaaS Overview 16-16 ( e i s S
Oracle SaaS Overview 16-17
n d ez e th
Summary 16-18
e rná to us
r o H se
17 Oracle Application r r e l
Containeri c en Service Overview
Cloud
Objectives G ue ble
17-2
o
OraclesApplication ra
é feContainer Cloud Service 17-3
r J n s
d gaOracle
n - tra
Application Container Cloud 17-4
E Polyglot
n o Platform 17-5
Open Platform 17-6
Container-based Application Platform as a Service 17-7
Elastic Scaling 17-8
Profiling 17-9
Manageable 17-10
Deploy—Application Archive (Zip) 17-12
Application Deployment 17-13
Application Container Cloud Architecture 17-14
Load Balancer 17-15
Oracle Developer Cloud Service 17-16
Developer Cloud Service – Easy Adoption/Integration 17-17
Application Container Cloud Service Advantages 17-19
Summary 17-20

xvi
Matis Consulting SฺCฺ

A Java Puzzle Ball Challenge Questions Answered


Topics A-2
Question 1 A-3
Question 2 A-4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Question 3 A-5
Question 4 A-6
Topics A-7
Question 1 A-8
Topics A-9
Question 1 A-10
Topics A-12
Question 1 A-13
Topics A-14
a
has
Question 1 A-15
Question 2 A-16 )
l ฺ c om ฺ
B Introducing the Java Technology
m ai ide
Java’s Place in the World B-2 @ g t Gu
d 2 4 en
Java Desktops B-3
d h t u d
Java Mobile Phones B-4 ( e i s S
Java TV and Card B-5
n d ez e th
The Story of Java B-6
e rná to us
Identifying Java TechnologyH e
ProductsGroups
e r o e n B-7
Java SE B-8
u e rr e lic
Java EE B-9
é G rabl
Javao
J s B-10sfe
ME

g a r
Java Card
- t r anB-11
Ed Product
non Life Cycle (PLC) Stages B-12

xvii
Matis Consulting SฺCฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
e rná to us
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no
Matis Consulting SฺCฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Introduction

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no
Matis Consulting SฺCฺ

About This Course


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

12 Shirt myShirt = new Shirt();


13 Shirt yourShirt = new Shirt();
14
a
has
15 myShirt = yourShirt;
16
m )
17 myShirt.colorCode = 'R';
l ฺ c o
18 yourShirt.colorCode = 'G';
m ai ideฺ
19
@ g t Gu
20 System.out.println("Shirt color: “ + myShirt.colorCode);
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
During this course,Gyou will: bl
• WriteJJavao é f eraa code console and integrated development environment
s codesusing
a
• gComplete - r an quizzes
r tinteractive
E• d Playnoa ngame

Java SE 8 Fundamentals 1 - 2
Matis Consulting SฺCฺ

Audience

• Beginners to programming who have basic mathematical,


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

logical, and analytical problem-solving skills and who want


to begin learning the Java programming language
• Novice programmers and those programmers who prefer
to start learning the Java programming language at an
introductory level
• Students who want to begin their study of the Oracle
Certified Java Associate exam
s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é G course
The audience for this
r a bisla beginner to programming who has basic mathematical and
r J os skills.
problem-solving
n s fe course is targeted at technical writers, web developers, technical
The
managers,
g a project
- t r amanagers, program managers, and individuals with a technical,
Ed non background such as system administrators.
nonprogramming

Java SE 8 Fundamentals 1 - 3
Matis Consulting SฺCฺ

Course Objectives

After completing this course, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Demonstrate knowledge of basic programming language


concepts
• Demonstrate knowledge of the Java programming
language
• Implement intermediate Java programming and object-
oriented (OO) concepts
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Demonstrate knowledge
é G ofrabasicbl programming language concepts. For example, be able to
describe theo
J s sfe
following:
Source
g a r t r
code versus
- an machine code
E• d Platform
non dependence and platform independence
• The use of APIs and libraries
Demonstrate knowledge of the Java programming language
• Compile and run a Java program from both the command line and from NetBeans.
• Create a Java class with fields and methods.
• Declare and use arrays.
• Use methods of the StringBuilder, String, and ArrayList classes.
• Display and manipulate dates using one or two classes from the new java.time
package.
• Write conditional statements.
• Write loop statements (enhanced for, for, while, do/while).
• Write nested loops.
• Implement a try block to handle exceptions.

Java SE 8 Fundamentals 1 - 4
Matis Consulting SฺCฺ

Implement intermediate Java programming and object-oriented (OO) concepts


• Instantiate an object and invoke its methods.
• Explain how objects vs. primitive types or references are stored in memory.
• Create a hierarchy of Java classes.
• Implement inheritance by creating a subclass.
• Overload a method and a constructor.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Encapsulate the fields of a class.


• Use modifiers to control access to a field or a method.
• Implement a Java Interface.
• Create superclasses, abstract classes, and Interfaces and use them as reference types.
• Use a Predicate lambda expression as the argument to a method.

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
e rná to us
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 1 - 5
Matis Consulting SฺCฺ

Schedule

Day One
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Getting Started
– Lesson 1: Introduction
– Lesson 2: What Is a Java Program?
• The Basic Shopping Cart
– Lesson 3: Creating a Java Main Class
– Lesson 4: Data in a Cart
– Lesson 5: Managing Multiple Items a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 1 - 6
Matis Consulting SฺCฺ

Schedule

Day Two
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Filling the Cart


– Lesson 6: Describing Objects and Classes
– Lesson 7: Manipulating and Formatting the Data in Your
Program
• Improving Cart Efficiency
– Lesson 8: Creating and Using Methods
Day Three a
– Lesson 9: Using Encapsulation ) has
• Expanding the Business l ฺ c om ฺ
m ai ide
– Lesson 10: More on Conditionals @ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 1 - 7
Matis Consulting SฺCฺ

Schedule

Day Four
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– Lesson 11: Working with Arrays, Loops, and Dates


• Bringing It Home
– Lesson 12: Using Inheritance
Day Five
– Lesson 13: Using Interfaces
– Lesson 14: Handling Exceptions
– Lesson 15: Deploying and Maintaining the Soccer a
Application ) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 1 - 8
Matis Consulting SฺCฺ

Course Environment

Classroom Computer
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Java Code Student


Exercises
Console Guide
Java SE 8
NetBeans Practices Activity
Guide

Java Puzzle Ball

Java SE 8
Quizzes Fundamentals Practices
s a
Quiz.html

)ha
labs folder Exercises m
co eฺ
i l ฺ
Lesson folders
g ma Guid
4
Solutions
2 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G raproducts
In this course, the following
é bl are preinstalled for the lesson practices:
• JDK J s JavasfSE
8:oThe e Development Kit includes the command-line Java compiler
r
a -and
(javac) n
trathe Java Runtime Environment (JRE), which supplies the java command
d gneeded n
E no to execute Java applications.
• Firefox: A web browser is used to view the HTML documentation (Javadoc) for the Java
SE Platform libraries.
• NetBeans 8: The NetBeans IDE is a free and open-source software development tool
for professionals who create enterprise, web, desktop, and mobile applications.
• Student Guide: The guide contains the instructional material for all the topics discussed
in class and includes appendices with additional information. It also includes some
introductory instructions for completing the exercises and practices.
• Activity Guide: These are resources to use during the practice portions of the course.
The Activity Guide has instructions for completing the practices.
• Lab Folder: The lab folder includes interactive quizzes, practices, exercises, and
solution files.

Java SE 8 Fundamentals 1 - 9
Matis Consulting SฺCฺ

• Java API Documentation: The API documentation is the application programming


interface specification.
• Java Code Console: This is an IDE developed by Oracle Java Curriculum Developers
that you use to perform short coding exercises.
• Interactive Quizzes: The quizzes are self-paced and help you remember the key points
learned in each lesson.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Java Puzzle Ball: This game is available for you to play on your machines. It will be used
to introduce and reinforce concepts taught in the course.

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
e rná to us
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 1 - 10
Matis Consulting SฺCฺ

Test Your Lab Machines

1. Go to your lab machine.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2. Open the Firefox browser.


3. Enter http://localhost:8080/JavaCC.
4. Click the Cloud IDE link.

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
To ensure that yourG
é r a bl is working, access your lab machine and start the Java
lab environment

r J os nsfe
Code Console.

d ga n-tra
E no

Java SE 8 Fundamentals 1 - 11
Matis Consulting SฺCฺ

How Do You Learn More After the Course?

To find more resources, bookmark the URL:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Oracle.com/oll/java
Look for the Java SE 8 Fundamentals Collection.

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é G Library,
In the Oracle Learning
r a blthere is a list of resources that you can use to learn more
r J os nsfe Look for the collection on the oracle.com/oll/java page.
about Java programming.

d ga n-tra
E no

Java SE 8 Fundamentals 1 - 12
Matis Consulting SฺCฺ

Quiz

a. What is your name?


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

b. What do you do for a living, and where do you work?


c. What is the most interesting place you have visited?
d. Why are you interested in Java?

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 1 - 13
Matis Consulting SฺCฺ

Summary

In this lesson, you reviewed the course objectives and the


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

tentative class schedule. You met your fellow students, and you
saw an overview of the computer environment that you will use
during the course.
Enjoy the next five days of Java SE 8 Fundamentals.

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 1 - 14
Matis Consulting SฺCฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

What Is a Java Program?

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no
Matis Consulting SฺCฺ

Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Contrast the terms “platform-dependent” and “platform-


independent”
• Describe the purpose of the JVM
• Explain the difference between a procedural program and
an object-oriented program
• Describe the purpose of javac and java executables
• Verify the Java version on your system a
) has
• Run a Java program from the command line m
i l ฺ co eฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 2 - 2
Matis Consulting SฺCฺ

Topics

• Introduction to computer programs


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Introduction to the Java language


• Verifying the Java development environments
• Running and testing a Java program

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 2 - 3
Matis Consulting SฺCฺ

Purpose of a Computer Program

A computer program is a set of instructions that run on a


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

computer or other digital device.


• At the machine level, the program consists of binary
instructions (1s and 0s).
– Machine code
• Most programs are written in high-level code (readable).
– Must be translated to machine code
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 2 - 4
Matis Consulting SฺCฺ

Translating High-Level Code to Machine Code


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Solaris OS
C Compiler
Solaris OS
Binary

Linux
C Compiler
C
Linux
Binary s a
Code
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
de Windows
Microsoft Windows
C Compiler
d h d tu Microsoft

z (e is S Binary

de se t h
á n u
Copyright © 2014, e
rn o
Oracle and/or tits
o H ense
affiliates. All rights reserved.

e r
u e rr e lic
Programs written inG
é r a bl usually require numerous modifications to run on more
most languages
than one type
r J osof computing
n s fe platform, (a combination of a CPU and operating system). This
platform-dependence
g a - t r a because most languages require you to write code specific to the
is
d oplatform.
underlying
E n Popular programming languages, such as C and C++, require
n
programmers to compile and link their programs, resulting in an executable program unique to
a platform. A compiler is an application that converts a program that you write into a CPU-
specific code called machine code. These platform-specific files (binary files) are often
combined with other files, such as libraries of prewritten code, using a linker to create a
platform-dependent program, called an executable, which can be executed by an end user.
Unlike C and C++, the Java programming language is platform-independent.
The image illustrates how a compiler creates a binary file.

Java SE 8 Fundamentals 2 - 5
Matis Consulting SฺCฺ

Linked to Platform-Specific Libraries


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Project
Libraries
Solaris OS
C Compiler
Solaris OS Solaris OS
Binary Executable

Project
Libraries

Linux
C Compiler
Linux Linux
a
has
Binary Executable
)
Project
l ฺ c om ฺ
Libraries
m ai ide
@ g t Gu
Microsoft Windows
d 4
2 Microsoft en Windows
Microsoft Windows C Compiler
d h u d
t Executable
Binary
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The image illustrates
é bl file is linked with libraries to create a platform-dependent
Ghow raabinary
executable. os fe
r J n s
d ga n-tra
E no

Java SE 8 Fundamentals 2 - 6
Matis Consulting SฺCฺ

Platform-Dependent Programs
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Solaris OS Workstation

Solaris OS
Executable

Linux Linux Workstation


s a
Executable
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
Microsoft Windows
z (e is S
Executable
e e th
Microsoft Windows Workstation
n d
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é a bl
Ghow rplatform-dependent
The image illustrates executables can execute only on one platform.

r J os nsfe
d ga n-tra
E no

Java SE 8 Fundamentals 2 - 7
Matis Consulting SฺCฺ

Topics

• Introduction to computer programs


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Introduction to the Java language


• Verifying the Java development environment
• Running and testing a Java program

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 2 - 8
Matis Consulting SฺCฺ

Key Features of the Java Language

Some of the features that set Java apart from most other
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

languages are that:


• It is platform-independent
• It is object-oriented

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
There are several other
é bl of the Java language, but in this course, only the two
G keyrafeatures
r J os willnsbefediscussed.
mentioned above

d ga n-tra
E no

Java SE 8 Fundamentals 2 - 9
Matis Consulting SฺCฺ

Java Is Platform-Independent
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Project
Libraries

Java Compiler

Java Code Java Bytecode

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
A Java program can
é bl different CPUs and operating system combinations, such
Grun onraseveral
as the Solaris sOS on sa fSPARC
Jousually e chip, Mac OS X on an Intel chip, and Microsoft Windows on
r
an Intelachip,
t r a nwith few or no modifications.
g -
Edillustrated
As n onabove, Java programs are compiled using a Java compiler. The resulting format
of a compiled Java program is platform-independent Java bytecode instead of CPU-specific
machine code.
After the bytecode is created, it is interpreted by a bytecode interpreter called the Java Virtual
Machine or JVM. A virtual machine is a platform-specific program that understands platform-
independent bytecode and can execute it on a particular platform. For this reason, the Java
programming language is often referred to as an interpreted language, and Java technology
programs are said to be portable or executable on any platform. Other interpreted languages
include Perl.

Java SE 8 Fundamentals 2 - 10
Matis Consulting SฺCฺ

Java Programs Run In a Java Virtual Machine


JRE
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Solaris OS
Java Workstation
Bytecode
JRE
(.class file)

Linux
Workstation
a
) has
omVirtual
JRE
Java
l ฺ c eฺ
m ai Machine
i d
@ g t Gu(JVM)
d 2 4 en
d h t u d
( e
Microsoft Windows
i s S
n d ez e th
Workstation

Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The image illustrates
é Ga Java r a bl
bytecode file executing on several platforms where a Java

r J os nexists.
runtime environment
s fe
d ga machine
A virtual
n - tragets its name because it is a piece of software that runs code, a task
E accomplished
usually n o by the CPU or hardware machine. For Java programs to be platform-
independent, a virtual machine called the JVM is required on every platform where your
program will run. The JVM is responsible for interpreting Java code, loading Java classes,
and executing Java programs.
However, a Java program needs more than just a JVM to execute. A Java program also
needs a set of standard Java class libraries for the platform. Java class libraries are libraries
of prewritten code that can be combined with the code that you write to create robust
applications.
Combined, the JVM software and Java class libraries are referred to as the Java Runtime
Environment (JRE). Java Runtime Environments are available from Oracle for many common
platforms.

Java SE 8 Fundamentals 2 - 11
Matis Consulting SฺCฺ

Procedural Programming Languages

• Many early programming languages


1
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Step 1
followed a paradigm called Procedural
Programming.
• These languages use a sequential 2 Step 2

pattern of program execution.


3 Step 3
• Drawbacks to procedural programming:
– Difficult to translate real-world use cases a
to a sequential pattern 4 a s
)h
Step 4

– Difficult to maintain programs m


co eฺ
i l ฺ
– Difficult to enhance as needed g m5a Step
G u5id
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Earlier programming
é Glanguages
r a bl were based on a programming paradigm called “procedural”.
os nsuse
Procedural languages
r J fe a sequential pattern of program execution such as you see in the
diagram
g a above.
- t r a
Some examples of procedural programming languages are COBOL, Fortran,
Edand Pascal.
C,
n on
This style of programming has become less popular due to the difficulty of designing real-
world applications using sequential pattern. It has also proven difficult to maintain and
enhance programs structured in this way.

Java SE 8 Fundamentals 2 - 12
Matis Consulting SฺCฺ

Java Is an Object-Oriented Language

• Interaction of objects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• No prescribed sequence
• Benefits:
– Modularity
– Information hiding
– Code reuse
– Maintainability
s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G rabdiffers
Object-oriented programming l from procedural programming, because procedural
é
s sthe
programmingostresses fe sequence of coding steps required to solve a problem, whereas
r J
object-oriented
a a n
programming stresses the interaction of objects. Java is an object-oriented
g - t r
d on(OO) language. One of the main goals of an OO language is to create objects—
programming
E
pieces ofnautonomous code—that can interact with other objects to solve a problem. OO
programming languages began in 1967 and have led to popular programming languages
such as C++, upon which Java is loosely based.
This provides many benefits:
• Modularity: The source code for an object can be written and maintained independently
of the source code for other objects. After it is created, an object can be easily passed
around inside the system.
• Information hiding: By interacting only with an object’s methods, the details of its
internal implementation remain hidden from the outside world.
• Code reuse: If an object already exists (perhaps written by another software developer),
you can use that object in your program.
• Maintainability: If a particular object is found to be problematic, you can create another,
slightly modified one and simply replace the original one in your application. This is
analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace
the bolt, not the entire machine.
The diagram illustrates an object-oriented program’s focus on objects and object interactions.
Java SE 8 Fundamentals 2 - 13
Matis Consulting SฺCฺ

Topics

• Introduction to computer programs


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Introduction to the Java language


• Verifying the Java development environment
• Running and testing a Java program

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 2 - 14
Matis Consulting SฺCฺ

Verifying the Java Development Environment

1. Download and install the Java Development Kit (JDK) from


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

oracle.com/java.
2. Explore the Java Help menu.
3. Compile and run a Java application by using the command
line.

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é Gdevelopment
Setting up your Java
r a bl environment is a simple task. The JDK is available for free
os Javanswebsite.
from the Oracle
r J fe
d a you-have
• gAfter
n t ra installed the JDK, you can explore the Java environment by typing some
E commands
no at the command line. For example, open a terminal window and enter java.
• Review the command options displayed.
• Enter java –version to see what Java version is installed on your system.
• Compile and run a Java application using the command line.

Java SE 8 Fundamentals 2 - 15
Matis Consulting SฺCฺ

Examining the Installed JDK (Linux Example):


The Tools
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
PATH points here 2
d tude4 @ nt
d h
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
Java SE (StandardGEdition) a bDevelopment Kit
s é e r
r a n sf Kit includes both the tools and classes that you will use to develop
JoDevelopment
The Java SE
a
g program.
a Java trThe tools and utilities are stored in the bin directory. These are shown in the
Ed noon
screenshot n-the right. They include:
• A Java Virtual Machine (JVM) for the platform you choose. Here you see a Linux
example. The runtime engine is started by running the java program.
• A Java compiler, started by running the javac program
• Additional utilities, such as utilities for creating Java archive files (JAR files) and for
debugging Java programs
• The bin directory, which must be on the system PATH in order to run or compile a Java
program. The Java installer automatically adds the bin to your system PATH.
• Note: The Java Runtime Environment used in production (commonly called the JRE) is
also included with Java SE Development Kit. This is found in the jre directory.

Java SE 8 Fundamentals 2 - 16
Matis Consulting SฺCฺ

Examining the Installed JDK (Windows Example):


The Libraries
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
Java SE Development
é G Kitrab
In additionJ s fe files found in the bin directory of the JDK, various class libraries
toothe executable
s
r a n
d ga nthat
are installed - trconform to the particular platform that you chose. Here you see a Windows
E nThe
example. o core libraries are found in the lib directory as shown above.
The Java runtime engine requires these libraries.
In addition to the Java SDK download, other items are available as a separate download,
such as the Java class library (API) documentation and the Java Language Specification.

Java SE 8 Fundamentals 2 - 17
Matis Consulting SฺCฺ

Topics

• Introduction to computer programs


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Introduction to the Java language


• Verifying the Java development environment
• Running and testing a Java program

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 2 - 18
Matis Consulting SฺCฺ

Compiling and Running a Java Program


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

.java javac .class java a s a


m )h
i l ฺ co eฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The diagram aboveG
é shows what
r a bl happens when you compile and run a Java program.
• The Java
r J oscodenissfwritten
e in a file with the extension .java. This is called the “Java
d a code.”
gsourcen - tra
E• Younuseo the javac executable to compile the source code (the “c” stands for “compiler”)
into a bytecode file with the extension .class. This is called a Java class.
• You use the java executable to run the Java class. This is your Java program.

Java SE 8 Fundamentals 2 - 19
Matis Consulting SฺCฺ

Compiling a Program

1. Go to the directory where the source code files are stored.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2. Enter the following command for each .java file you want
to compile.

• Syntax:
javac SayHello.java

• Example: s a
javac SayHello.java )ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Compiling convertsG
é the source
r a blfiles that you write into bytecode that can be executed by a
Java Virtual o
J s sThe
Machine. fe source file has a .java extension. It also defines a public class of
the same
a r name.
t a
For
r nexample, the class, SayHello, must be saved in a file called
g -
Ed non (You learn more about classes later in this course.)
SayHello.java.
To compile the SayHello source code, perform the following steps:
1. Go to the directory where the source code files are stored.
2. Enter the following command for each .java file that you want to compile (Note that the
.java extension is required.):
Example: javac SayHello.java
After the compilation has finished, and assuming no compilation errors have occurred, you
should have a new file called <classname>.class in your directory for each source code
file that you compiled.
Example: SayHello.class

Java SE 8 Fundamentals 2 - 20
Matis Consulting SฺCฺ

Executing (Testing) a Program

1. Go to the directory where the class files are stored.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2. Enter the following for the class file that contains the main
method:
• Syntax:
java <classname>

• Example: Do not specify .class.

java SayHello s a
)ha
m
co eฺ
i l ฺ
• Output:
g ma Guid
Hello World!
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G rabcompiled
When you have successfully l your source code files, you can execute and test them
using the Java é
osVirtual fe
Machine.
r J n s
ga and
To execute
d n - ra your program:
ttest
E1. Gontoothe directory where the class files are stored.
2. Enter the following command for the class file that contains the main method. Note that
here the file extension (.class) should not be included.
Example: java SayHello
This command runs the SayHello class. The SayHello class contains the main method.
This is the entry point to a Java application. The java executable only works with a class
containing a main method. In the above example, the main method contains code that prints
the string "Hello World!”.

Java SE 8 Fundamentals 2 - 21
Matis Consulting SฺCฺ

Output for a Java Program

A Java program can output data in many ways. Here are some
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

examples:
• To a file or database
• To the console
• To a webpage or other user interface

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é r a bl data only to the console. You can learn more about writing
G be outputting
In this course, we will
os nssuch
to other destinations,
r J fe as a file, database, or webpage, by taking the Java SE 8
d ga n-tra
Programming course.
E no

Java SE 8 Fundamentals 2 - 22
Matis Consulting SฺCฺ

Exercise 2-1

• From a Terminal window, enter java –version to see


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

the system’s Java version.


• Look for SayHello.java in:
/labs/02-GettingStarted/Exercises/Exercise1
• Compile it: javac SayHello.java
• Run the resulting class file: java SayHello
— Did you see the output?

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
In this exercise, you
é blJava version installed on your system, and then you run a
Glook atrathe
simple Java o
J s sfrom
program fe the command line.
r
a a terminal
• gOpen t n
ra window by double-clicking the Terminal shortcut on your desktop. It will
d
E open n -
noat your home directory, which is /home/oracle.
-Note: A handy shortcut to navigate to your home directory from anywhere is ~.
Example: cd ~ to go to /home/oracle.
• Enter java to see the available command options.
• Enter java -version to verify that JDK 1.8.0 is installed on your system.
• Navigate to the folder containing the Java source file for this exercise:
cd labs/02-GettingStarted/Exercises/Exercise1
• Enter javac SayHello.java to compile it.
• Enter java SayHello to run it. You should see a “Hello World!” message as output.

Java SE 8 Fundamentals 2 - 23
Matis Consulting SฺCฺ

Quiz

Which of the following is correct? (Choose all that apply.)


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

a. javac OrderClass
b. java OrderClass
c. javac OrderClass.java
d. java OrderClass.java

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
Answer: b, c
é G rab
The .java
J s s feis needed only when you compile a class (using javac).
o extension
r n
d ga n-tra
E no

Java SE 8 Fundamentals 2 - 24
Matis Consulting SฺCฺ

Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Describe the distinction between high-level language and


machine code
• Describe what platform-independence means
• Describe how a Java program is compiled and to what
format
• Explain what it means to say that Java is an object-
oriented language a
• Determine the version number of a Java install ) has
c o m
• Use the javac tool to compile Java source code l ฺ
aiand ithe eฺ
m d
java tool to run or test your program @g Gu 4 n t
hd Stud2 e
( e d
e z t h is
d
án use
Copyright © 2014, e
r n oaffiliates. All rights reserved.
Oracle and/or tits
H s e
r r ero licen
G ue ble
o s é fera
a r J ans
g tr
Ed non-

Java SE 8 Fundamentals 2 - 25
Matis Consulting SฺCฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
e rná to us
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no
Matis Consulting SฺCฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Creating a Java Main Class

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no
Matis Consulting SฺCฺ

Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Create a Java class


• Write a main method
• Use System.out.println to write a String literal to
system output

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 3 - 2
Matis Consulting SฺCฺ

Topics

• Java classes and packages


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• The main method

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 3 - 3
Matis Consulting SฺCฺ

Java Classes

A Java class is the building block of a Java application.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Includes code that:


• Allows a customer to add
ShoppingCart.java items to the shopping cart
• Provides visual confirmation
to the customer

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 3 - 4
Matis Consulting SฺCฺ

Program Structure

• A class consists of:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– The class name. Class names begin with a capital letter.


– The body of the class surrounded with braces { }
— Data (called fields)
— Operations (called methods)
• Example:
Java is case-sensitive!
s a
public class Hello { )ha
m
co eฺ
// fields of the class a i l ฺ
// methods g m G uid
2 4 @ nt
}
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
• A class is declared
é G using
r a blthe keyword, class, followed by the class name.
• Convention
r J os dictates
n s fe that the class name start with a capital letter. If there are two words
d athe class
ginexamplen - traname (SayHello), each word should begin with a capital letter. In the
E no above, the class name is Hello.
• The keyword public is called a modifier. You learn about these in the lesson titled
“Using Encapsulation.”
• Java is case-sensitive. It does not recognize the following two words as being the
same thing: class and Class.
• A class would typically contain data (called fields) and operations (called methods). You
learn about this a little later.
• Notice that the body of the Hello class is enclosed in braces ({ }).

Java SE 8 Fundamentals 3 - 5
Matis Consulting SฺCฺ

Java Packages

• A package provides a namespace for the class.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– This is a folder in which the class will be saved.


– The folder name (the package) is used to uniquely identify
the class.
– Package names begin with a lowercase letter.
• Example:
Package name
package greeting;
s a
The class’s unique )ha
public class Hello {
name is: greeting.Hello m
co eฺ
i l ฺ
// fields and methods here
g ma Guid
}
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The use of a package
é G whenrayou bl create a Java class is not mandatory, but it is strongly
recommended.
r J osNotice n s fe semicolon after package greeting;
the
Semicolons
d ra
ga nare-trequired at the end of each statement. It is similar to the period at the end of a
E noThe sentence may wrap to another line, but it is not complete until the period. The
sentence.
Java compiler interprets a statement as being complete when it encounters the semicolon.

Java SE 8 Fundamentals 3 - 6
Matis Consulting SฺCฺ

Using the Java Code Console

For the exercises in this course, you


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

use a browser-based Java IDE.


1. Open a browser and
enter: http://localhost:8080/JavaCC
2. Click the Lessons link.
3. Click the exercise number
for the current lesson.
s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é r a bl
G Development
IDE stands for Integrated Environment. This is a type of software that makes it

r J os applications.
easier to develop
n s fe In the practices for the lesson titled “Describing Objects and
Classes”
g a and
- t r a
beyond, you use the NetBeans IDE, which is a full-featured Java IDE.
Edthe short
For n onexercises that are sprinkled throughout the lecture portions of this course, you
will use a simple web-based IDE called Java Code Console. It was written specifically for this
purpose. This IDE is hosted on your student machine.

Java SE 8 Fundamentals 3 - 7
Matis Consulting SฺCฺ

Using the Java Code Console:


Creating a New Java Class
1. Click the New button to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

create a new file.


2. Select the Java category
and Java Class file type.
3. Click Next.

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é G provide
Most of the exercises
r a bal pre-existing Java class or classes, to which you add code. If
the exercise o s selected
J you s fe has a pre-existing .java file for you, it will appear in a tabbed view
on thisa r
page. ra n
thowever,
In d g cases,
some n - you need to create a new Java class. The steps are described here
E n o
and in the next slide.
• Click the New button as shown in the top screenshot.
• The Create New File Wizard opens. Select Java in the Category column. Select Java
Class in the File Type column.
• Click Next.
• Instructions are also displayed on the Java Code Console page, just below the code
editor panel. However, if no Java file is provided and you are going to create a new one,
the code editor is not shown. Therefore, the instructions appear just below the toolbar.

Java SE 8 Fundamentals 3 - 8
Matis Consulting SฺCฺ

Using the Java Code Console:


Creating a New Java Class for an Exercise
4. Enter a class name and a package name.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

5. Click Finish.

Run code

a
Show ) has
Code Return to List solution
l ฺ c om ฺ
editor of Lessons
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Enter a class nameG
é and package
r a bl name, as specified in the exercise instructions. When you
click Finish, o
J scode sforfethis class appears in a tabbed page, bearing the class name.
the
r
- r an
• gInathe left tscreenshot, you see the ShoppingCart.java tab, containing the package
d
E statement n
no and the class declaration. This is the code editor panel.
• You will write your code between the braces.
• To test your code, click the Run button as indicated above.
• To return to the list of exercises, click the Index link.
• To view the solution for the exercise, click the Solution link. It will replace the current
.java file with the solution .java file in the same tab, but you will be able to toggle
between your code and the solution.

Java SE 8 Fundamentals 3 - 9
Matis Consulting SฺCฺ

Exercise 3-1: Creating a Class

In this exercise, you use the Java Code Console to create a


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

new Java Class.


• Click New to create a new class:
– Class name = ShoppingCart
– Package name = exercise
• Leave the tabbed view open in the browser because you
will modify the code in the next exercise.
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G name
The fully-qualified class
a l
bshould be exercise.ShoppingCart. Do not click the
Solution linko é
until fe r
s aftersexercise 3-2.
r J n
d ga n-tra
E no

Java SE 8 Fundamentals 3 - 10
Matis Consulting SฺCฺ

Topics

• Java classes
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• The main method

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 3 - 11
Matis Consulting SฺCฺ

The main Method

• It is a special method that the JVM recognizes as the


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

starting point for every Java program.


• The syntax is always the same:

public static void main (String args[]) {


// code goes here in the code block
}
a
) has
• It surrounds entire method body with braces { } . om
a ilฺc deฺ
g m Gui
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
• The main method
é bl method that the Java Virtual Machine recognizes as the
G is raaspecial
s forsafeJava program.
startingopoint
J
a
• gAny r program
t r n you want to run must have a public main method.
athat
E• d A class -
noncontaining a main method is referred to as a “main class.”
Note: Brackets ([]) can be placed to the right of String or to the right of args, but the
former is recommended:
(String[] args)
(String args[])

Java SE 8 Fundamentals 3 - 12
Matis Consulting SฺCฺ

A main Class Example

Class name
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

public class Hello {

public static void main (String[] args) {


// Entry point to the program. Comments
// Write code here:
System.out.println ("Hello World!");
}
s a
} )ha
m
co eฺ
i l ฺ
g ma Program
G u id
main 4 @ nt
method d h d tude output
2
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é G example
Here you see a simple
r a bl of a class (Hello) that includes a main method. The main
r J osa message
method writes
n s fe to the console (“Hello World!”). This is called program output.
ga include
You can - a
trcomments that the compiler will ignore, by preceding the comment line with
d
E forward n
two noslashes: //

Java SE 8 Fundamentals 3 - 13
Matis Consulting SฺCฺ

Output to the Console

• Syntax:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

System.out.println (<some string value>);

String literal
• Example:
System.out.println ("This is my message."); a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G rabl method to print a message to the console. Use double
Use the System.out.println
é
r J os to enclose
quotation marks
n s fe the text of the message (called a String literal).
d ga n-tra
E no

Java SE 8 Fundamentals 3 - 14
Matis Consulting SฺCฺ

Fixing Syntax Errors

• If you have made a syntax error, the error message


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

appears in the Output panel.


• Common errors:
– Unrecognized word (check for case-sensitivity error)
– Missing semicolon
– Missing close
quotation mark
– Unmatched brace
s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The Java Code Console
é G helps r a blyou out by using color coding. Keywords (such as class) are in
purple. String
J s are
oliterals s feshown in blue. When you click Run, it will attempt to compile your
code and
a r then run
t r a n
it. Syntax errors will be caught during compilation. The error message may
or g -
d notoben helpful in troubleshooting, so here are some common errors to avoid:
Emay n
• Unrecognized class (It may say “Cannot find symbol.”). This happens when you misspell
a method or class name, or if you get the case wrong. Remember, Java is case-
sensitive!
• Every Java statement must end with a semicolon. This example error is shown above in
line 5.
• An uneven number of symbols such as braces, brackets, and quotation marks will also
cause errors.

Java SE 8 Fundamentals 3 - 15
Matis Consulting SฺCฺ

Exercise 3-2: Creating a main Method

In this practice, you manually enter a main method that prints a


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

message to the console.


• In the code editor, add the main method structure to the
ShoppingCart class.
• In the code block, use a System.out.println method
to print “Welcome to the Shopping Cart!”
• Click the Run button to test program.

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is Example S
de se t h
á n u
Copyright © 2014, e
rn o
Oracle and/or tits
o H ense
affiliates. All rights reserved.

e r
u e rr e lic
G youraseebla class called Hello. Within the braces that define the scope of
In the example above,
é
r J ossee the
the class, you
n s fe method. The method body is also surrounded by braces.
main
When
d g you
n ra Run button as indicated in the image on the right, the program is both
a click-tthe
E n(using
compiled o javac) and executed (using java).
The println statement results in the “Hello World!” string appearing in the Output tab.

Java SE 8 Fundamentals 3 - 16
Matis Consulting SฺCฺ

Quiz

Which main method syntax is correct?


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

a. Public static void main (String[ ] args){ }


b. public Static void Main (String[ ] args){ }
c. public static void main (String ( ) args)[ ]
d. public static void main (String[ ] args){ }

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
Answer: d
é G rab
J s fe be “public”, not “Public”.
o nIt sshould
• a is incorrect.
r tra Both “Static” and “Main” should begin with a lowercase letter.
• dgbais incorrect.
n -
E• c isnincorrect
o because there should be brackets following “String” and braces defining
the method scope.
• d is correct.

Java SE 8 Fundamentals 3 - 17
Matis Consulting SฺCฺ

Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Create a class using the Java Code Console


• Create (declare) a Java class
• Define a main method within a class
• Use System.out.println to write to the program
output
• Run a program in the Java Code Console
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 3 - 18
Matis Consulting SฺCฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Data in a Cart

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no
Matis Consulting SฺCฺ

Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Describe the purpose of a variable in the Java language


• List and describe four data types
• Declare and initialize String variables
• Concatenate String variables with the '+' operator
• Make variable assignments
• Declare and initialize int and double variables
a
• Modify variable values by using numeric operators
) has
• Override default operator precedence using ( ) o m
ฺc il
g
a
m Guideฺ
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 4 - 2
Matis Consulting SฺCฺ

Topics

• Introducing variables
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Working with String variables


• Working with numbers
• Manipulating numeric data

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 4 - 3
Matis Consulting SฺCฺ

Variables

• A variable refers to something that can change.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– Variables can be initiated with a value.


– The value can be changed.
– A variable holds a specific type of data.

Variable
The value of the variable
The type of data name
a
String firstName = "Mary"; ) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
A variable is simplyG l
a storageblocation
a in memory that holds a specific value. That value can
be changed o é r
byscopyingf(or
e “assigning”) a different value to that variable.
r J n s
d ga n-tra
E no

Java SE 8 Fundamentals 4 - 4
Matis Consulting SฺCฺ

Variable Types

• Some of the types of values a variable can hold:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– String (example: "Hello")


– int (examples: -10, 0, 2, 10000)
– double (examples: 2.00, 99.99, -2042.09)
– boolean (true or false)
– If uninitialized, variables have a default value:
– String: null
– int: 0 a
– double: 0.0 ) has
– boolean: false l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é G to hold
Variables are declared
r a bal specific type of data. Some of the more common types are:
• String:
r J osThisnisstext
fe data, such as “Hello”.
a This-tisrainteger data—positive or negative whole numbers.
• gint:
d
non These are positive or negative real numbers containing a decimal portion.
E• double:
• boolean: This data type has a value of either true or false.
Most variables that have not been initialized are given a default value. The default values for
String, int, double, and boolean are shown above. (Local variables are the exception.
You will learn about local variables in the lesson titled “Creating and Using Methods.”)
Notice that String begins with an uppercase letter, but the other types do not. You will learn
the reason for this later, when you also learn about some other data types.

Java SE 8 Fundamentals 4 - 5
Matis Consulting SฺCฺ

Naming a Variable

Guidelines:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Begin each variable with a lowercase letter. Subsequent


words should be capitalized:
– myVariable
• Names are case-sensitive.
• Names cannot include white space.
• Choose names that are mnemonic and that indicate to the
casual observer the intent of the variable. a
– outOfStock (a boolean) ) has
– itemDescription (a String) l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 4 - 6
Matis Consulting SฺCฺ

Uses of Variables

• Holding data used within a method:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

String name = "Sam" ;


double price = 12.35;
boolean outOfStock = true;
• Assigning the value of one variable to another:
String name = name1;
• Representing values within a mathematical expression:
total = quantity * price ; a
• Printing the values to the screen: ) has
l ฺ c om ฺ
System.out.println(name);
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Variables are usedG
é extensively
r a blin the Java programming language for tasks such as:
• HoldingJ s used
odata s fewithin a method, such as the main method
r
a -tthe
• gAssigning
n
ra value of one variable to another. In the first example above, the name
d
E variable n
no is initialized with the value, “Sam”, and in the second example, its value is
changed to the value of name1 (unknown here).
• Representing values within a mathematical expression (* is the symbol for multiplication)
• Printing the values to the screen. For example, the same System.out.println
method that you used in the last exercise to print out the text literal, “Welcome to the
Shopping Cart”, can also be used to print out the value stored in the name variable.

Java SE 8 Fundamentals 4 - 7
Matis Consulting SฺCฺ

Topics

• Introducing variables
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Working with String variables


• Working with numbers
• Manipulating numeric data

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 4 - 8
Matis Consulting SฺCฺ

Variable Declaration and Initialization

• Syntax :
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

type identifier [= value];

Variable declared
• Examples:
String customer; Two variables
declared
String name, city;
Variable declared
String address = "123 Oak St"; and initialized as a
m )h
Two variables declared i l ฺ co eฺ
a
and initialized g m G uid
2 4 @ nt
String country = "USA", state = h
d d tude
"CO";
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G and
The syntax for declaring
a l
binitializing a variable is:
é r
os n[=sfvalue];
e
J
type identifier
r
ga n-tra
where:
d
E• type norepresents the type of information or data held by the variable. In the examples
above, you see only String variable types declared.
• identifier is the variable name. In the first example above, the variable name is
customer.
• The second example shows how you can declare multiple variables of the same type on
a single line without initializing them. Notice that they are separated by a comma.
• You can either declare a variable without assigning an initial value (as you saw in the
first example) or you can initialize the variable at the same time you declare it (as shown
in the example that declares and initializes the address variable).
• The final example shows how to declare and initialize multiple variables of the same
type. Once again, each initialization is separated by a comma. Some of the multiple
variables declared on a single line can be initialized, whereas others are just declared.

Java SE 8 Fundamentals 4 - 9
Matis Consulting SฺCฺ

String Concatenation

• String variables can be combined using the '+' operator.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– stringVariable1 + stringVariable2
– stringVariable1 + "String literal"
– stringVariable1 + "String literal" +
stringVariable2

• Example:
String greet1 = "Hello";
a
String greet2 = "World";
) has
String message = greet1 + " " + greet2 + "!";
l ฺ c om ฺ
String message = greet1 + " " + greet2 + " " + a i +"!";
2014 de g m Gui
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Combining multipleG l “concatenation.” You can concatenate a String variable
Strings isbcalled
a
é
os nvariable.
to another String r
fe You can also concatenate a String literal to a String variable.
r J s
As you
d g acan see-tinrathe example above, you can concatenate any number of String variables
E String
and
nonliterals to achieve your goal.
You may find the last example surprising. You can also concatenate a number into a String
variable. The compiler converts the numeric value to its equivalent String value. If we were
to print the message variable after the last example, the output would be “Hello World 2014!”

Java SE 8 Fundamentals 4 - 10
Matis Consulting SฺCฺ

String Concatenation Output

You can concatenate String variables within a method call:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

System.out.println(message);
System.out.println(greet1 + " " + greet2 + "!");

Output:
Hello World!
a
has
Hello World!
)
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G yourasee
In the examples above,
é bl two variations of printing out String data by using the
r J os nsfemethod.
System.out.println

d n - ra
• gInathe firsttexample, the message variable that you saw in the previous slide will be
E printed.
no
• In the second example, the expression containing the concatenation of variables plus
String literals can be used within the method parentheses. The concatenation will be
completed by the runtime engine before the println method is executed.
• As you can see, the output of both method invocations is the same.

Java SE 8 Fundamentals 4 - 11
Matis Consulting SฺCฺ

Exercise 4-1: Using String Variables

In this exercise, you declare, initialize, and concatenate


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

String variables and literals.

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
• Open the Java
é GCoderConsole
a bl and access 04-Variables > Exercise1.
• Follow
r J othes instructions
n s fe below the code editor to declare and initialize variables, and also
d n - tra a string message. Print the message by using System.out.println.
gtoaconcatenate
E If you
Note: no need help, the solution for this exercise can be found by clicking the Solution link.

Java SE 8 Fundamentals 4 - 12
Matis Consulting SฺCฺ

Quiz

Which of the following variable declarations and/or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

initializations are correct?


a. int count = 5; quantity = 2;
b. string name, label;
c. boolean complete = "false";
d. boolean complete = true;

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
Answer: d
é G rab
s
o because
• a is incorrect
J s fe each int declaration and assignment must be separated by a
r
a and n
tranot a semicolon.
d gcomma n -
E• b isnincorrect
o because String is not capitalized.
• c is incorrect because a boolean type variable does not hold String values. It holds
only true and false.
• d is correct.

Java SE 8 Fundamentals 4 - 13
Matis Consulting SฺCฺ

Topics

• Introducing variables
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Working with String variables


• Working with numbers
• Manipulating numeric data

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 4 - 14
Matis Consulting SฺCฺ

int and double Values

• int variables hold whole number values between:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– –2,147,483,648
– 2,147,483,647
– Examples: 2, 1343387, 1_343_387

• double variables hold larger values containing decimal


portions.
– Use when greater accuracy is needed. a
a s
– Examples: 987640059602230.7645 , -1111, 2.1E12
m )h
i l ฺ co eฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
• The int dataGtype stores
é r a bl 32 bits of data. This means that you can store whole numbers
r J osrange:
within the
n s fe
-2,145,483,648 and 2,147,483,647. You cannot use commas to make
the
g a number
- t r a
more readable when you assign a value to an int variable. However, you
Ed can
intnuse nunderscores (_) to make your code more readable, as shown in one of above
oexamples. The compiler ignores these underscores. If you print the number to
system output, the underscores will not appear. The only benefit of this is readability in
your code.
• The double data type stores 64 bits of data. This means that you can store extremely
large values—either negative or positive. The examples above show:
- An extremely large number with four decimal points of precision
- A negative whole number
- A decimal number using exponential notation

Java SE 8 Fundamentals 4 - 15
Matis Consulting SฺCฺ

Initializing and Assigning Numeric Values

• int variables:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– int quantity = 10;


– int quantity = 5.5; Compilation fails!

• double variables:
– double price = 25.99;
Run time will
– double price = 75; a
interpret as 75.0. has
)
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 4 - 16
Matis Consulting SฺCฺ

Topics

• Introducing variables
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Working with String variables


• Working with numbers
• Manipulating numeric data

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 4 - 17
Matis Consulting SฺCฺ

Standard Mathematical Operators

Purpose Operator Example Comments


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Addition + sum = num1 + num2;


If num1 is 10 and num2
is 2, sum is 12.

Subtraction – diff = num1 –


num2;
If num1 is 10 and num2
is 2, diff is 8.
Multiplication * prod = num1 *
num2;
If num1 is 10 and num2 s a
is 2, prod is 20. )ha
m
co eฺ
i l ฺ
a0 returns
Division Division by
uid
/ quot = num1 /
an g m
error. G
num2;
@ nt
If num1 is 31 and num2 24The remainder
is 6, quot is 5. dh
d portion t u deis discarded.
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The table above assumes
é G rthat a blall operands and result variables are integers (int). Mixing
double andoint
J s types s e alter the results. For instance, in the division example, if the
fcan
quotient
a r
and dividend
t r a n (or if all three) are double values, the quotient would show the decimal
g -
Ed non
portion:
double quot, num1;
num1 = 31;
int num2 = 5;
quot = num1 / num2;
Answer: quot = 6.2

Java SE 8 Fundamentals 4 - 18
Matis Consulting SฺCฺ

Increment and Decrement Operators (++ and --)

The long way:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

age = age + 1;
or
count = count – 1;

The short way:


age++;
a
or
) has
count--;
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
A common requirement
é a bl is to add or subtract 1 from the value of a variable. You
G inrprograms
r J osusingnthe
can do this by
s fe+ operator as follows:
age = a
d tra
g age n+ -1;
E no

Java SE 8 Fundamentals 4 - 19
Matis Consulting SฺCฺ

Operator Precedence

Here is an example of the need for rules of precedence.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Is the answer to the following problem 34 or 9?


int c = 25 - 5 * 4 / 2 - 10 + 4;

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 4 - 20
Matis Consulting SฺCฺ

Operator Precedence

Rules of precedence:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1. Operators within a pair of parentheses


2. Increment and decrement operators (++ or --)
3. Multiplication and division operators, evaluated from left to
right
4. Addition and subtraction operators, evaluated from left to
right
s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
In a complex mathematical
é bl
G rastatement with multiple operators on the same line, how does the
computer pick
r J oswhichnoperator
s fe it should use first? To make mathematical operations
consistent,
g a the
-
Java
t r a programming language follows the standard mathematical rules for
Ed nprecedence.
operator on Operators are processed in the following order:
1. Operators within a pair of parentheses
2. Increment and decrement operators
3. Multiplication and division operators, evaluated from left to right
4. Addition and subtraction operators, evaluated from left to right
If standard mathematical operators of the same precedence appear successively in a
statement, the operators are evaluated from left to right.

Java SE 8 Fundamentals 4 - 21
Matis Consulting SฺCฺ

Using Parentheses

Examples:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

int c = (((25 - 5) * 4) / (2 - 10)) + 4;


int c = ((20 * 4) / (2 - 10)) + 4;
int c = (80 / (2 - 10)) + 4;
int c = (80 / -8) + 4;
int c = -10 + 4;
int c = -6;

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é r a bl
Gbe automatically
Your expression will evaluated with the rules of precedence. However, you

r J os nsfeto provide the structure you intend:


should use parentheses
int c a
d g n - t a 5) * 4) / (2 - 10)) + 4;
= (((25 r-
E c =n((20
int o * 4) / (2 - 10)) + 4;
int c = (80 / (2 - 10)) + 4;
int c = (80 / -8) + 4;
int c = -10 + 4;
int c = -6;

Java SE 8 Fundamentals 4 - 22
Matis Consulting SฺCฺ

Exercise 4-2: Using and Manipulating Numbers

In this exercise, you declare, initialize, and concatenate


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

String variables and literals.

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
• Open the Java
é GCoderConsole
a bl and access Lessons > 04-Variables > Exercise2
• Follow
r J othes instructions
n s fe below the code editor to:
d ga- Declare
n - tra and initialize two double variables to hold the price and the tax
E - noDeclare an int to hold the number of items the shopper wishes to purchase
- Declare another double variable, total, but do not initialize it yet
- Change the existing message variable to include the number of items desired
- Calculate the total cost and then print it with a suitable descriptive String
- Run the project
Note: If you need help, the solution for this exercise can be found by clicking the Solution link.

Java SE 8 Fundamentals 4 - 23
Matis Consulting SฺCฺ

Quiz

Which of the following statements are correct Java code?


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

a. int count = 11.4;


b. double amount = 11.05;
c. int cost = 133_452_667;
d. double total = 1.05 * amount;

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
Answer: b, c, d G a b
s é e r
• a is incorrect
r n sf the assignment of a decimal value to an int is a possible loss of
Jo abecause
a
gprecision tr therefore will not compile.
and
on-
E• d b isncorrect.
• c is correct because underscores can be used to make a number more readable.
• d is correct.

Java SE 8 Fundamentals 4 - 24
Matis Consulting SฺCฺ

Quiz

Given:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

String name = "Bob";


String msg;
int num = 3;
Which of the following statements correctly assigns the value
“Bob wrote 3 Java programs.” to the msg variable?
a. msg = name + " wrote " + num " Java programs.";
b. msg = name + " wrote " + 3 + " Java programs."; a
c. msg = "Bob wrote "+ (2+1) + " Java programs."; ) has
d. msg = name + " wrote " + 2+1 + " Java l ฺ c om ฺ
m ai ide
programs."; g u
2 4 @ nt G
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
Answer: b, c
é G rab
J s
o because
• a is incorrect s fe it is missing a + sign between the num variable and the final
r tra
a -literal. n
d gStringn
E• b isncorrect
o because the compiler converts the int of value 3 to a String.
• c is correct because, due to the use of parentheses, the addition operation is performed
first, before the concatenation.
• d is incorrect because it would result in “Bob wrote 21 Java programs.” The compiler
converts each number to a String separately and concatenates them together.

Java SE 8 Fundamentals 4 - 25
Matis Consulting SฺCฺ

Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Describe the purpose of a variable in the Java language


• List and describe four data types
• Declare and initialize String variables
• Concatenate String variables with the '+' operator
• Make variable assignments
• Declare and initialize int and double variables
a
• Modify numeric values by using operators
) has
• Override default operator precedence using ( )
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 4 - 26
Matis Consulting SฺCฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Managing Multiple Items

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no
Matis Consulting SฺCฺ

Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Explain what a boolean expression is


• Create a simple if/else statement
• Describe the purpose of an array
• Declare and initialize a String or int array
• Access the elements of an array
• Explain the purpose of a for loop
a
• Iterate through a String array using a for loop
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE8 Fundamentals 5 - 2


Matis Consulting SฺCฺ

Topics

• Working with conditions


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Working with an array of items


• Processing an array of items

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE8 Fundamentals 5 - 3


Matis Consulting SฺCฺ

Making Decisions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Which way
shall I go?

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
In your daily life, you Ghavertoabmake l a lot of decisions, and you often use the word “if” with
é
Joswhen
some condition
the left,aIrwill turnra n
left,
fe those decisions. For example, “If I can see my destination on
making
sotherwise I’ll turn right.”
g - t
Ed of the
One n n that programs often perform is to evaluate a condition and, depending on the
otasks
result, execute different blocks or branches of code. This is called conditional logic, and it is
handled through the use of an if/else statement.

Java SE8 Fundamentals 5 - 4


Matis Consulting SฺCฺ

The if/else Statement

boolean expression
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

if ( <some condition is true> ) {


// do something if block
}
else {
// do something different else block
}
s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The if/else statement
é G israone bl way of branching your code depending upon some condition.
r J osJavankeywords,
It uses the two
s fe if and else.
d n - tra is true, execute the code within the if block.
• gIfasome condition
E• Else, noif that condition is false, execute the code in the else block.
The condition to be evaluated is surrounded by parentheses. It is referred to as a boolean
expression because it must evaluate to either true or false.

Java SE8 Fundamentals 5 - 5


Matis Consulting SฺCฺ

Boolean Expressions

Review:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• boolean data type has only two possible values:


– true
– false

A boolean expression is a combination of variables, values,


and operators that evaluate to true or false.
• length > 10; a
) has
• size <= maxSize;
l ฺ c om ฺ
• total == (cost * price); ai ide
@ gm t Gu
d 2 4 en
Relational operators d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G radata
Remember that a boolean
é bl type can have only two possible values: true and false.
In the sameJo s a boolean
way, s fe expression, made up of some combination of variables, values
r n
tra also evaluate to either true or false.
ga n-must
and operators,
d
E usually
This no involves a special kind of operator called a relational operator. Several of these
are used in the three examples above:
• Greater than ( > )
• Less than or equal to ( <= )
• Equal to ( == ). In the example above, the result of cost * price is compared to the
value of total. If they are equal, the entire expression evaluates to true.

Java SE8 Fundamentals 5 - 6


Matis Consulting SฺCฺ

Relational Operators

Condition Operator Example


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Is equal to == int i=1;


(i == 1)

Is not equal to != int i=2;


(i != 1)

Is less than < int i=0;


(i < 1)

Is less than or equal <= int i=1;


to (i <= 1)
s a
)ha
Is greater than > int i=2;
m
co eฺ
(i > 1)
a i l ฺ
Is greater than or >= int i=1; gm
G uid
equal to (i >=
2 4 @1) n t
hd Stud e
( e d
e z t h is
d
án use
Copyright © 2014, e
r n oaffiliates. All rights reserved.
Oracle and/or tits
H s e
r r ero licen
e llist
ucomplete e of relational operators. The table lists the different
Here you see a more G
é testfby a b
conditions you
J o scan s erusing relational operators. The result of all relational operators is a
boolean
g a rvalue. All
- t r aofnthe examples in the table yield a boolean result of true.
Ed Thenoequal
Note: n sign (=) is used to make an assignment, whereas the == sign merely makes
a comparison and returns a boolean.

Java SE8 Fundamentals 5 - 7


Matis Consulting SฺCฺ

Examples

Sometimes there is a quicker way to meet your objective.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

boolean expressions can be used in many ways.


24 int attendees = 4;
25 boolean largeVenue;
26
27 // if statement example
28 if (attendees >= 5){
29 largeVenue = true;
30 } Assign a boolean by
using an if a
31
32
else {
largeVenue = false; statement. ) h
as
33 } l ฺ c om ฺ
34 m ai ide
g tthe
Assign G u
boolean
35 // same outcome with less code 4 @
36 largeVenue = (attendees >= h d 2 directly
5); u d en from the
( e d S t boolean expression.
e z t h is
d
án use
Copyright © 2014, e
r n oaffiliates. All rights reserved.
Oracle and/or tits
H s e
r r ero licen
In the slide above, G
e le of two different ways to set the largeVenue boolean
youusee examples
é r a b
value: s e
sfif statement tests the value of the attendees variable. If it is
r Jo28–33,
• gInalines a n
Ed greater o n -tr an
than 5, largeVenue is set to true; otherwise it is set to false.
n
• In line 36, the same outcome is achieved with one line of code. The result of the same
boolean expression that was evaluated in the if statement (attendees >=5) is
directly assigned to the largeVenue boolean.

Java SE8 Fundamentals 5 - 8


Matis Consulting SฺCฺ

Exercise 5-1: Using if Statements

In this exercise, you use an if and an if/else statement:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Declare a boolean, outOfStock.


• if quantity > 1
– Change the message variable to indicate plural
• if/else:
– if item is out of stock:
— Inform the user that the item is unavailable
– else a
Print the message

) has
Print the total cost l ฺ c om ฺ
ai ide

m
g t Gu
4 @
h d 2
u d en
( e d S t
ez e th i s
n d
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
• Open the Java
é a bl and access Lessons > 05-ConditionsArraysLoops >
GCoderConsole
r J os nsfe
Exercise1.
• gFollow a
a the-trinstructions below the code editor to write two if statements in the main
d
E method. n
no
Note: If you need help, the solution for this exercise can be found by clicking the Solution link.

Java SE8 Fundamentals 5 - 9


Matis Consulting SฺCฺ

Quiz

What is the purpose of the else block in an if/else


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

statement?
a. To contain the remainder of the code for a method
b. To contain code that is executed when the expression in
an if statement is false
c. To test if an expression is false

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
Answer: b
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE8 Fundamentals 5 - 10


Matis Consulting SฺCฺ

Topics

• Working with conditions


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Working with an array of items


• Processing an array of items

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE8 Fundamentals 5 - 11


Matis Consulting SฺCฺ

What If There Are Multiple Items


in the Shopping Cart?
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

01 // Without an array Not realistic if


02 String itemDesc1 = "Shirt"; 100s of items!
03 String itemDesc2 = "Trousers";
04 String itemDesc3 = "Scarf";
05 Much better!
06 // Using an array
07 String[] items = {"Shirt","Trousers","Scarf"};

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Think about how your
é bl look if there were multiple items in the shopping cart. You
G coderawould
would have to
r J osinitialize
n s e item description separately. Imagine if you had a thousand items!
feach
d gacontinued
As you
n - trato build out this shopping cart application, the amount of code needed to
E each
handle n o item individually would not only be time-consuming, but would make your code
hard to read and difficult to maintain.
The code example above shows a better alternative that we will explore now: the array.

Java SE8 Fundamentals 5 - 12


Matis Consulting SฺCฺ

Introduction to Arrays

• An array is an indexed container that holds a set of values


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

of a single type.
• Each item in an array is called an element.
• Each element is accessed by its numerical index.
• The index of the first element is 0 (zero).
– A four-element array has indices: 0, 1, 2, 3.

0 1 2 3 s a
)ha
m
co eฺ
27 12 82 70 i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é G that
The array is a container
r a bl a set of String values, or a set of int values, or a set of
holds

r J os andnso
double values,
s fe
on.
ga n-(items)
The elements
d tra of the array are accessed through a numeric index. Using this index,
E can nsetoor get a value from a specific element.
you

Java SE8 Fundamentals 5 - 13


Matis Consulting SฺCฺ

Array Examples

Array of int types


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

27 12 82 70 54 1 30 34

Array of String types

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Gdatartype,
Arrays can be of any
é a bl but all elements have to share the same type.
r J os nsfe
d ga n-tra
E no

Java SE8 Fundamentals 5 - 14


Matis Consulting SฺCฺ

Array Indices and Length


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

The ages array has eight elements.

First Element
index at index 5

00 1 2 3 4 5 6 7 Indices

27 12 82 70 54 1
1 30 34

s a
Array length is 8.
)ha
(ages.length) m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G raobject
• An array is a container
é bl that holds a fixed number of values of a single type. The
r J osan array
length of
n s fise established when the array is created. After creation, the length of
gan
a array
- t r a changed.
cannot be
E• d Each
n n in an array is called an element, and each element is accessed by its
oitem
numerical index. As shown in the diagram above, index numbering begins with 0. For
example, the eighth element would be accessed at index 7.
• The length of an array can be accessed using dot notation to access the length field.
Assuming that the array in the diagram is called ages, you can determine how many
elements are in the array by using:
int agesLength = ages.length;

Java SE8 Fundamentals 5 - 15


Matis Consulting SฺCฺ

Declaring and Initializing an Array

• Syntax:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

type[] arrayIdentifier = {comma-separated list of values};

• Declare arrays of types String and int:


String[] names = {"Mary", "Bob", "Carlos"};
int[] ages = {25, 27, 48};

All in one
line s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é Gthe syntax
In this slide, you see
r a bl and an example of how to declare the array and initialize the
s sfthat
values. (Thisoassumes
J e you know at this time what the values will be).
r a n
a for-trdeclaring
• gSyntax an array:
d
E type n
no [] arrayIdentifier = {comma-separated list of values};
- Note: Another acceptable syntax is: type arrayIdentifier[] = {comma-
separated list of values};
where:
• type represents the data type for each of the values stored in the array
• [ ] informs the compiler that you are declaring an array
• arrayIdentifier is the variable name that you use when you refer to the array
• You can list as many values as you need. Separate the values with a comma.

Java SE8 Fundamentals 5 - 16


Matis Consulting SฺCฺ

Declaring and Initializing an Array

• Examples:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1 int[] ages = new int[3];


2 ages[0] = 19; Multistep
3 ages[1] = 42; approach
4 ages[2] = 92;
5
6 String[] names = new String[3];
Multistep
7 names[0] = "Mary";
approach
8 names[1] = "Bob";
s a
9 names[2] = "Carlos"; )ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
In this example, theG
é
int array,
r a blages, is instantiated with a size of 3 on line 1. The creation of
the array uses
r J osthe new n s e
fkeyword. You will learn much more about the purpose of this keyword
in the lesson
g a titled
- t r a“Describing Objects and Classes.”
Edlinesn2 othrough
On n 4, the elements of the ages array are initialized.
Likewise, on line 6, the String array, names, is instantiated with a size of 3, and its elements
are initialized on lines 7 through 9.

Java SE8 Fundamentals 5 - 17


Matis Consulting SฺCฺ

Accessing Array Elements

• Get values from the ages array:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

int[] ages = {25, 27, 48};

int myAge = ages[0];


int yourAge = ages[1];
System.out.println("My age is " + ages[0]);

• Set values from the names array:


String[] names = {"Mary", "Bob", "Carlos"}; s a
)ha
m
co eฺ
names[0] = "Gary"; i l ฺ
names[1] = "Rob"; g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Elements of the array
é a bl by referencing the index of that element. For example:
G are raccessed
• To get
r J othes value
n s fe the first element of the ages array, use ages[0].
from
• gTo
d n ra from the second element of the ages array, use ages[1].
a get the-tvalue
E• Youncano directly use the value of an array element in an expression by using the same
syntax. In the third example, you see ages[0] referenced directly when calling
System.out.println.
• To set a value in the first element of the names array, use names[0] = "some
value".

Java SE8 Fundamentals 5 - 18


Matis Consulting SฺCฺ

Exercise 5-2: Using an Array

In this exercise, you declare and initialize a String array to


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

hold names. Then you experiment with accessing the array:


• Declare a String array, names, and initialize it with four
String values.
• Print the number of items the customer wants to buy.
• Print one of the array elements.

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
• Open the Java
é a bl and access Lessons > 05-ConditionsLoopsArrays >
GCoderConsole
r J os nsfe
Exercise2

d n - tra
• gInathe ShoppingCart class, follow the instructions below the code editor to:
E - noDeclare and initialize a String array to hold four distinct String values.
- Change the message variable to reflect not only the customer name, but a
message that includes the number of items the customer wants to purchase. (Hint:
Use the length property of the array.)
- Print the message.
- Print the third element of the names array.
- Run the file.
- Change the element index number in the print statement to 4 and run the file
again. You will get an error. Why?
Note: If you need help, the solution for this exercise can be found by the clicking the Solution
link.

Java SE8 Fundamentals 5 - 19


Matis Consulting SฺCฺ

Quiz

Why does the following code not compile? Select all that apply.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

int[] lengths = {2, 4, 3.5, 0, 40.04};


a. lengths cannot be used as an array identifier.
b. All of the element values should have the same format (all
using double values, or all using int values).
c. The array was declared to hold int values. double
values are not allowed.
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
Answer: c
é G rab
J
a is incorrect s
obecause s fe is a perfectly valid array identifier.
a r a n lengths
g nbecause
b isdincorrect
E o -tr it implies that this array could contain elements of type double.
n
c is correct.

Java SE8 Fundamentals 5 - 20


Matis Consulting SฺCฺ

Quiz

Given the following array declaration, which of the following


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

statements are true?


int[] classSize = {5, 8, 0, 14, 194};
a. classSize[0] is the reference to the first element in the
array.
b. classSize[5] is the reference to the last element in the
array.
c. There are 5 integers in the classSize array. a
s
d. classSize.length = 5 ) ha
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
Answer: a, c, d G a b
s é e r
a r Jo ansf
a is correct.
b isdincorrect
E o -tr the array index begins with 0. Thus, the index for the last element is
g nbecause
one lessn than the total number of elements.
c is correct.
d is correct.

Java SE8 Fundamentals 5 - 21


Matis Consulting SฺCฺ

Topics

• Working with conditions


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Working with an array of items


• Processing an array of items

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE8 Fundamentals 5 - 22


Matis Consulting SฺCฺ

Loops

Loops are used in programs to repeat blocks of statements


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Until an expression is false


or
• For a specific number of times:
– I want to print each element of an array.
– I want to print each element of an ArrayList. (The
ArrayList class is covered in the lesson titled “Working
with Arrays, Loops, and Dates.”
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE8 Fundamentals 5 - 23


Matis Consulting SฺCฺ

Processing a String Array

Loop accesses each


element in turn.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

names array of String types

George Jill Xinyi Ravi

Each iteration
returns the next
for (String name : names ) { element of the
System.out.println("Name is " + name); array.
}
a
) has
Output:
Name is George l ฺ c om ฺ
Name is Jill m ai ide
Name is Xinyi @ g t Gu
d 2 4 en
Name is Ravi
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Gis: rabl
The for loop syntax
é
for J
r os ns<variable>
(<type> fe : <array name>) {
g a tr a
Ed } non-
<code_block to be performed for each array element>

where:
• for indicates that a loop is being defined
• <type> is the data type of each of the elements within the array
• <variable> is a placeholder used to store each element of an array
• : indicates that the object reference that follows is an array
• <array name> is the array, whose length determines the number of iterations to
perform
• code_block is the code that will be executed in each iteration of the loop
In the example above, there are four elements in the names array. Therefore, the code block
will be executed four times. Each time, the name variable holds a different array element.

Java SE8 Fundamentals 5 - 24


Matis Consulting SฺCฺ

Using break with Loops

break example:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

01 int passmark = 12;


02 boolean passed = false;
03 int[] scores = {4,6,2,8,12,35,9};
04 for (int unitScore : scores){
05 if (unitScore >= 12){ No need to go
06 passed = true; through the loop
07 break; again, so use break.
08 }
09 } a
10 System.out.println("At least one passed? " +passed);has
m )
o
a ilฺc deฺ
Output: g m Gui
2 4 @ nt
At least one passed? true
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Occasionally, someG l that makes it unnecessary to continue the loop. The
conditionboccurs
a
break keyword é
s enables r
feyou to do this. When break is encountered, the program execution
movesa Jofirst
tor the n s
a code outside the for block.
line of
g - t r
E• d Thenexample
on in the slide shows the use of break. You will notice that it uses an if
statement within the for block. This if statement is executed on each iteration of the
loop.
• Assuming that the purpose of the code is to find out whether any of the scores in the
array are equal or above the passmark, you can set passed to true and jump out of
the loop as soon as the first such score is found.
• When break is called on line 7, execution of the program skips to line 10.

Java SE8 Fundamentals 5 - 25


Matis Consulting SฺCฺ

Exercise 5-3: Using a Loop to Process an Array

In this exercise, you loop through an array called itemPrices


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

to print a message indicating each item price.

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
• Open the Java
é a bl and access Lessons > 05-ConditionsLoopsArrays >
GCoderConsole
r J os nsfe
Exercise3
• gFollow a
a the-trinstructions below the code editor to process the itemPrices array.
d
E If you n
Note: no need help, the solution for this exercise can be found by clicking the Solution link.

Java SE8 Fundamentals 5 - 26


Matis Consulting SฺCฺ

Quiz

Given the following code,


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

int[] sizes = {4, 18, 5, 20};


for (int size : sizes){
if (size > 16){break;}
System.out.println("Size: "+size + ", ");
}
which option below shows the correct output?
a. Size: 4,
a
b. Size: 4
) has
c. Size: 4,
l ฺ c om ฺ
m ai ide
Size: 5,
@ g t Gu
d. There is no output. d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
Answer: a
é G rab
J
a is correct.
s
o nsfe
r
ga nbecausetra the comma appears within each println method.
b isdincorrect -
E no because when the first size greater than 16 is found, the loop breaks and does
c is incorrect
not return.
d is incorrect because the first iteration of the loop would print.

Java SE8 Fundamentals 5 - 27


Matis Consulting SฺCฺ

Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Use a boolean expression


• Create a simple if/else block
• Describe the purpose of an array
• Declare and initialize a String or int array
• Access the elements of an array
• Explain the purpose of a for loop
a
• Iterate through a String Array using a for loop
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE8 Fundamentals 5 - 28


Matis Consulting SฺCฺ

Play Time!

Play Basic Puzzles 1 through 5 before the lesson titled


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

“Describing Objects and Classes.”


Your Goal: Design a solution that deflects the ball to Duke.
Consider the following:
What happens when you put a triangle wall or simple wall icon on
the blue wheel?

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é r a bl Basic Puzzle 5. Puzzles beyond Basic.05 are associated
You are welcome toGplay beyond

r J os nsfe
with later lessons.

d ga n-tra
E no

Java SE8 Fundamentals 5 - 29


Matis Consulting SฺCฺ

About Java Puzzle Ball

• It is used throughout the course.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Play a set of puzzles.


• Become familiar with the game mechanics.
• Consider a question as you play.
• The lesson titled “Describing Objects and Classes”
debriefs on what you have observed.
• Apply your observations to understand Java concepts.

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G rathe
At certain points throughout
é bl course, you will be asked to play levels of Java Puzzle Ball.
s Java
The game reflects
Jothese s feconcepts through game mechanics. It's more important to become
r
familiarawith
t r a n
mechanics than it is to solve every puzzle. Don't worry if the connection
g
d game
between -
n mechanics and Java concepts is not immediately apparent. You will debrief in
E n o
future slides and realize the connection during this debriefing. As you develop an
understanding for how the game works, you will be able to apply what you have learned as a
foundation for understanding difficult Java concepts.

Java SE8 Fundamentals 5 - 30


Matis Consulting SฺCฺ

Tips

• You must have Java 8 installed to run the game.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• The game may perform better on your personal machine.

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE8 Fundamentals 5 - 31


Matis Consulting SฺCฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
e rná to us
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no
Matis Consulting SฺCฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Describing Objects and Classes

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no
Matis Consulting SฺCฺ

Interactive Quizzes
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
Before you start today’s
é G lessons,
r a bltest your knowledge by answering some quiz questions that
r J osthe links
relate to yesterday’s
n s fe Open your quiz file from labs > Quizzes > Java SE 8 Fundamentals
lessons.
Quiz.html.
g a Click
- t r a for Lessons 1, 2, 3, 4, and 5.
Ed non

Java SE 8 Fundamentals 6 - 2
Matis Consulting SฺCฺ

Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• List the characteristics of an object


• Define an object as an instance of a class
• Instantiate an object and access its fields and methods
• Describe how objects are stored in memory
• Instantiate an array of objects
• Describe how an array of objects is stored in memory
a
• Declare and instantiate an object as a field
) has
• Use the NetBeans IDE to create and test Java classes o m
ฺc il
g
a
m Guideฺ
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 6 - 3
Matis Consulting SฺCฺ

Topics

• Describing objects and classes


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Defining fields and methods


• Declaring, instantiating, and using objects
• Working with object references
• Doing more with arrays
• Introducing NetBeans IDE
• Introducing the soccer league use case
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 6 - 4
Matis Consulting SฺCฺ

Java Puzzle Ball

Have you played Basic Puzzle 5?


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Consider the following:


What happens when you put a triangle wall or simple wall icon on
the blue wheel?

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 6 - 5
Matis Consulting SฺCฺ

Java Puzzle Ball Debrief

What happens when you put a triangle wall or simple wall icon
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

on a blue wheel?
• A wall appears on every instance of a blue bumper
object.
• Walls give bumpers behaviors that deflect and interact
with the ball.
• All blue bumper instances share these same behaviors.
s a
instance
)h a
m
instance
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
A blue bumper is anG object, and
a l instance of these objects will share the same behavior for
bevery
interacting with é
osthe ball. r
fe behaviors may include deflection via triangle or the simple wall.
These
r J n s
d ga n-tra
E no

Java SE 8 Fundamentals 6 - 6
Matis Consulting SฺCฺ

Object-Oriented Programming

• Interaction of objects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• No prescribed sequence

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
G rabefore
You have seen this diagram
é bl in the “What Is a Java Program?” lesson. The diagram
teachesayour Jhows toaidentify
n sfe theprogramming
illustrates howoobject-oriented stresses the interaction of objects. The current lesson
objects that are required for the application that you would like to
dgYou first
build.
E o n -tr what the objects are, you determine the object’s characteristics or
identify
properties,nand then you determine the object’s behaviors or operations. You then translate that
analysis into Java code to create your application. It is time to learn more about objects.

Java SE 8 Fundamentals 6 - 7
Matis Consulting SฺCฺ

Duke’s Choice Order Process


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
In the first five lessons,
é r a bl mention a shopping cart class that contains items. Take
G the exercises
another look at
r J osthe shopping
n s fe cart scenario.
Imagine
g aan online- t a called Duke’s Choice. His number one shopper is his mother, Mrs. Duke.
rstore
d
EMrs. Duke n
As
no shops, she places items in a shopping cart. Mrs. Duke likes shirts, so she places
shirts in her cart. After she fills the cart, she checks out. The checkout process applies the
purchase to a credit card, which is verified, and then Mrs. Duke receives an order number so that
she can track her order or return it.
As a software developer, when you are presented with a scenario such as Duke’s Choice for an
application that you need to develop, you can analyze the scenario by breaking it into steps and
defining the objects of the scenario.

Java SE 8 Fundamentals 6 - 8
Matis Consulting SฺCฺ

Characteristics of Objects

Objects are physical or conceptual.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Objects have properties:


– Size
– Shape
– Name
– Color
Mrs. Duke
• Objects have behaviors: Color property value is red
– Shop
s a
– Put item in cart )ha
m
co eฺ
– Pay i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
To validate objects inGa problem
a l
bdomain, such as the Duke’s Choice order process, you identify
é
the propertiesoofsall objects:
fe r
r J n s
d a can
• Objects
gconceptual
n - rbea physical or conceptual. A customer’s credit card account is an example of a
tobject,
E no because it is not something you can physically touch. A shirt is an
example of a physical object.
• Objects have properties (attributes) such as size, name, and shape that represent the state
of the object. For example, a person has a name (Mrs. Duke), and an object might have a
color property. The value of all of an object’s properties is often referred to as the object’s
current state. An object might have a color property with the value of red and a size property
with a value of large.
• Objects also have behaviors (things they can do) such as, in our example, shop, put an item
in the cart, and purchase.

Java SE 8 Fundamentals 6 - 9
Matis Consulting SฺCฺ

Classes and Instances

• A class:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– Is a blueprint or recipe for an object


– Describes an object’s properties and behaviors
– Is used to create object instances
Object instances

Class a
s
-Properties m )ha
-Behaviors i l ฺ co eฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
You just learned about G someraofbthe l objects, characteristics, and behaviors in the Duke’s Choice
scenario. Here ois é
s sfe
an example of one of Duke’s Choice objects, the Customer, and its function in
the store.
a J
rCustomer anis the class, and a class is a blueprint or recipe for an object. The class
g - t r
Ed non
describes an object’s properties and behaviors.
Classes are used to create object instances, such as the three Customer object instances, as
illustrated by the three images.

Java SE 8 Fundamentals 6 - 10
Matis Consulting SฺCฺ

Quiz

Which of the following statements is true?


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

a. An object is a blueprint for a class.


b. An object and a class are exactly the same.
c. An object is an instance of a class.
d. A class is an instance of an object.

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
Answer: c
é G rabl
• a is false
J s safeclass is a blueprint for an object.
obecause
• g a
b is
r
- t r an an object is an instantiation of a class, and a class
false because
Ed serves
noasn a blueprint for the object.
• c is correct.
• d is false because an object is an instance of a class.

Java SE 8 Fundamentals 6 - 11
Matis Consulting SฺCฺ

Topics

• Describing objects and classes


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Defining fields and methods


• Declaring, instantiating, and using objects
• Working with object references
• Doing more with arrays
• Introducing NetBeans IDE
• Introducing the soccer league use case
s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
You have just learned
é bl classes, and their characteristics (properties and behaviors).
Gaboutraobjects,
Now it is timeotoslook at fields
fe and methods.
r J n s
d ga n-tra
E no

Java SE 8 Fundamentals 6 - 12
Matis Consulting SฺCฺ

The Customer Properties and Behaviors


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Properties: Behaviors:
• Name • Shop
a
• Address • Set Address
) has
• Age • Add item to cart
l ฺ c om ฺ
• Order number • Ask for a discount
m ai ide
@ g t Gu
4
• Customer number 2 dendetails
• Displaydcustomer
dh Stu
z ( e is
d e t h
r n án use
Copyright © 2014, e
H oaffiliates. All rights reserved.
Oracle and/ortits
e
ero licen s
r r
G ueand behaviors
Think of some properties b le that are in the Customer class of Duke’s Choice. Think
about how you sé write
would f a
r information as a Java class.
ethis
J o
r tran s
g a
Ed non-

Java SE 8 Fundamentals 6 - 13
Matis Consulting SฺCฺ

The Components of a Class


Class declaration
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1 public class Customer {


2 public String name = "Junior Duke";
Fields
3 public int custID = 1205; (Properties)
4 public String address; (Attributes)
5 public int orderNum;
6 public int age;
7
8 public void displayCustomer(){ Methods
9 System.out.println("Customer: "+name); (Behaviors)
s a
10 }
)ha
11 } m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
In the previous slide,G
you haveb
a l
identified some properties and behaviors that might be in the
Customer class.
o é
s sfe
This coder example demonstrates how the properties and methods are created
J n
r basictracomponents
in Java.aThe of a Java class are:
g -
E• d Thenclass
on declaration. Notice that the entire class is surrounded by braces.
• Fields of the class. These represent the properties or attributes of the class.
• Methods of the class. These represent the behaviors or operations. Here you see just one
method, displayCustomer.
Note: In the code example above, the word “public” is a modifier, and you learn about
modifiers later in the course.

Java SE 8 Fundamentals 6 - 14
Matis Consulting SฺCฺ

Modeling Properties and Behaviors


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Customer class Class name


name
address
billing info Fields
age
customer number
order number

requestDiscount()
Methods
setAddress()
s a
shop()
displayCustomer() )ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
G raitbisl often helpful to create a simple model that describes the
As you design an application,
é
components of
r J osainclass.
n sInfethe table above, the class name is listed at the top. The properties or
fields are
g a listed
- t r a
the second row, and the behaviors, or methods, are listed in the third row. If you
E d on
compare this modeling in terms of language, you can think of the class as a noun, the properties
n
or fields as adjectives, and the behaviors or methods as verbs.

Java SE 8 Fundamentals 6 - 15
Matis Consulting SฺCฺ

Exercise 6-1: Creating the Item Class

In this exercise, you create the Item class and declare public
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

fields for ID (int), descr, quantity (int), and price (double).

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
• In the Java Code
é G Console,
r a blaccess Lessons > 06-Objects > Exercise1.
• Follow the
r J osinstructions
n s fe below the code editor to create the Item class and declare public
fields
gItem a descr, quantity (int), and price (double). You will not be able to test the
a for ID-tr(int),
d
E no n
class until Exercise 6-2.
• If you need help, click the Solution link. To go back to your code, click the Exercise link
again. Any changes that you have made will have been saved.

Java SE 8 Fundamentals 6 - 16
Matis Consulting SฺCฺ

Topics

• Describing objects and classes


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Defining fields and methods


• Declaring, instantiating, and using objects
• Working with object references
• Doing more with arrays
• Introducing NetBeans IDE
• Introducing the soccer league use case
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 6 - 17
Matis Consulting SฺCฺ

Customer Instances
customer01
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

customer02

public static void main(String[] args){

Customer customer01 = new Customer(); Create new instances


Customer customer02 = new Customer();
(instantiate).
s a
customer01.age = 40;
Fields are accessed. ) h
a
customer02.name = "Duke";
l ฺ c om ฺ
m ai ide
customer01.displayCustomer();
Methods gare called.
G u
4 @ t
customer02.displayCustomer();
h d 2
u d en
}
( e d S t
}
ez e th i s
n d
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
In the code example,G
é r a bl
two new instances of the Customer object called customer01 and
customer02o
J s sfe
are created. (Another term for created is “instantiated.”) After the objects are
n variables customer01 and customer02 can be used to access fields
gar nof-the
instantiated, the reference
anddmethods traobjects. The next two slides explain variations on instantiation, and the dot
E n o
operator. There is more information on methods in the lesson titled “Creating and Using Methods.”

Java SE 8 Fundamentals 6 - 18
Matis Consulting SฺCฺ

Object Instances and Instantiation Syntax


variable becomes a reference
to that object.
The new keyword creates
(instantiates) a new instance.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

The syntax is:


<class name> variable = new <class name>()

public static void main(String[] args){

Customer customer01 = new Customer(); //Declare and instantiate

Customer customer02; //Declare the reference


customer02 = new Customer(); //Then instantiate

s a
new Customer(); //Instantiation without a reference
)ha
//We can’t use this object later m
co eฺ
i l ฺ
ma Guid
//without knowing how to reference it.
}
@ ntg
}
2
d tude4
d h
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
G raanew
By using the new keyword,
é bl instance of the class is now available to be accessed through
r J os stores
the variable, which
n s fea reference to that object. It can be referred to as a reference variable or
d a -tra
an object reference.
gthat,
E nofollowing
Notice n the new keyword, you see the class name followed by parentheses. This
looks similar to calling a method, doesn’t it? You are calling a method—the constructor method
of the Customer class. Every class has a constructor method that has the same name as the
class. Constructors are covered in more detail in the lesson titled “Creating and Using Methods.”
To summarize, there are three steps to getting an object reference:
1. Declare the reference.
2. Instantiate the object using the new keyword and the class constructor method.
3. Assign the object to the reference.
Note that the way that the assignment operator (an = symbol) works requires that the reference
and the newly created object must be in the same statement. (Statements are ended with the
semicolon symbol and are not the same as lines. The end of a line means nothing to the Java
compiler; it only helps make the code more readable.)

Java SE 8 Fundamentals 6 - 19
Matis Consulting SฺCฺ

The Dot (.) Operator

Follow the reference variable with a dot operator (.) to access


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

the fields and methods of an object.

public static void main(String[] args){

Customer class
Customer customer01 = new Customer();
name
address //Accessing fields
billing info
System.out.println(customer01.name);
age
customer01.age = 40; a
as
customer number
order number
) h
requestDiscount()
//Calling methods
customer01.requestDiscount(); ilฺc
om ฺ
setAddress()
customer01.displayCustomer(); g ma Guide
shop()
}
2 4 @ nt
displayCustomer()
}
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 6 - 20
Matis Consulting SฺCฺ

Objects with Another Object as a Property

Customer class Cart class


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

customer number Item[]


*cart date
name total
address
billing info
order number
addItem()
requestDiscount() checkOut()
setAddress() cancel()
shop()
displayCustomer()

s a
)ha
public static void main(String[] args){ m
co eฺ
i l ฺ
Customer customer01 = new Customer(); g ma Guid
//How to 4
2 @ methodsn t of an
customer01.cart.cancel();
hd within
access
e
ud another object
( e d
//object
S t
}
e z t h is
d
án use
Copyright © 2014, e
r n oaffiliates. All rights reserved.
Oracle and/ortits
H s e
r r ero licen
So far you have seen G ue with
objects b leproperties such as boolean, int, double, and String. What
if you wanted o é fproperty
ansobject’s
a
er to be another object with its own set of properties and
behaviors, J
r such as an s
costumer with a cart property? That way, an instance of a Customer would
aproperties
have g
d ona
access to - t
the
r and behaviors found in a Cart. This would enable the customer to
E n
add items to the cart and then checkOut (purchase) the cart. Can this be done? The answer is
yes.
You can access fields and methods of objects within another object by applying the dot operator
multiple times.
Note: A best practice is to use attribute and operation names that clearly describe the attribute or
operation. The asterisk (*) denotes an attribute that is a reference to another object.

Java SE 8 Fundamentals 6 - 21
Matis Consulting SฺCฺ

Quiz

Which of the following lines of code instantiates a Boat object


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

and assigns it to a sailBoat object reference?


a. Boat sailBoat = new Boat();
b. Boat sailBoat;
c. Boat = new Boat()
d. Boat sailBoat = Boat();

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
Answer: a
é G rabl
r J os nsfe
d ga n-tra
E no

Java SE 8 Fundamentals 6 - 22
Matis Consulting SฺCฺ

Topics

• Describing objects and classes


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Defining fields and methods


• Declaring, instantiating, and using objects
• Working with object references
• Doing more with arrays
• Introducing NetBeans IDE
• Introducing the soccer league use case
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 6 - 23
Matis Consulting SฺCฺ

Accessing Objects by Using a Reference


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

The camera is like the object that is


accessed using a reference.

a
The remote is like the reference
) has
used to access the camera.
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
What you have learned
é bl point is:
G up torathis
• Objects o
J s accessed
are s fe using references.
• g
r a n
a are-trinstantiated
Objects objects of their class type.
d
E• Objectso n
n consist of properties and operations, which in Java are fields and methods.
To work with an object, you need to access it using a reference. A good analogy is using a remote
control to operate an electronic device. The buttons on the remote control can be used to modify
the behavior of the device (in this case, a camera). For example, you can make the camera stop,
play, or record by interacting with the remote.

Java SE 8 Fundamentals 6 - 24
Matis Consulting SฺCฺ

Working with Object References

1 1
Pick up the remote to gain Create a Camera object and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

access to the camera. get a reference to it.

11 Camera remote1;
12
13 remote1 = new Camera();
14
15 remove1.play();
a
) has
l ฺ c om ฺ
2 2
m ai ide
Press the remote’s controls Call a method to g havet the
G u
4 @
to have camera do something. Camera
h d 2object
u d en
do something.

( e d S t
ez e th i s
n d
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
Consider the analogyGof using a a l
bremote control to operate an electronic device. To operate an
é r
os withnasremote,
electronic device fe you need to:
r J
1. Pick
d ra (and possibly turn it on)
ga up nthe-tremote
E2. Pressnoa button on the remote to do something on the camera
Similarly, to do something with a Java object, you need to:
1. Get its “remote” (called a reference)
2. Press its “buttons” (called methods)

Java SE 8 Fundamentals 6 - 25
Matis Consulting SฺCฺ

Working with Object References


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

remote1 remote2

12 Camera remote1 = new Camera(); s a


13 There are two
)ha
14 Camera remote2 = new Camera(); Camera objects. m
co eฺ
i l ฺ
15
16 remote1.play(); g ma Guid
2 4 @ nt
17
18 remote2.play(); d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
There are two camera
é Gobjectsr a blthis example. Each camera has its own unique remote. remote2
in

r J osremote1’s
will not work on
n s fecamera, and remote1 will not work on remote2’s camera. This reflects
how in Java,
g a two
- t r a objects can be instantiated with their own unique references. These
different
Ed non
references can be used to call methods on their respective objects.

Java SE 8 Fundamentals 6 - 26
Matis Consulting SฺCฺ

Working with Object References

There is only one


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Camera object.
remote2
12 Camera remote1 = new Camera();
13
14 Camera remote2 = remote1;
15
16 remote1.play();
17
remote1 18 remote2.stop(); a
a s
m )h
i l ฺ co eฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
The diagram shows G
é r a bl aspect of how references work. In this example, a Camera
another important
object is created
J o s sfe
and its reference assigned to a Camera reference, remote1. This reference is

garCamera
then assigned an Camera reference, remote2. Now both references are associated with
to another
- t r
the d
same n object, and methods called on either reference will affect the same Camera
E n o
object. Calling remote1.play is no different than calling remote2.play. Both remotes operate
the same camera.

Java SE 8 Fundamentals 6 - 27
Matis Consulting SฺCฺ

References to Different Objects


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Television

Camcorder

Television a
remote a s
Camcorder
m )h
remote
i l ฺ co eฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
To extend the analogy
é bl further, to work with a different type of object (for example, a
Gjust aralittle
correct a r
type Jforosthe
television), you
n fe for that object. In the Java world, you need a reference of the
need a remote
s
a that you are referencing.
object
g - t r
Edcan ignore
You
n on the fact that there is such a thing as a universal remote controller, although later in
the course you will discover that Java also has the concept of references that are not limited to a
single object type! For the moment, let’s just say that a reference of the same type as the object is
one of the reference types that can be used, and is a good place to start exploring the world of
Java objects.

Java SE 8 Fundamentals 6 - 28
Matis Consulting SฺCฺ

References to Different Objects

Reference type
Reference variable
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Create a new object.

6 Camera remote1 = new Camera();


7 remote1.menu();
8
9 TV remote2 = new TV();
10 remote2.menu();
11
a
has
12 Shirt myShirt = new Shirt();
13 myShirt.display(); )
14
l ฺ c om ฺ
15 Trousers myTrousers = new Trousers(); m ai ide
16 myTrousers.display(); @ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
remote1 referencesG l
a Camerabobject.
a
é r
os nasTVfeobject.
remote2 references
r J
d
myShirt
n tra a Shirt object.
ga references
-
E no references a Trousers object.
myTrousers

Java SE 8 Fundamentals 6 - 29
Matis Consulting SฺCฺ

References and Objects in Memory

12 int counter = 10;


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

13 Shirt myShirt = new Shirt();


14 Shirt yourShirt = new Shirt();

Stack 0x034009 Heap


12 shirtID
15.99 price
B colorCode

counter s a
10
0x99f311
) ha
myShirt 0x034009 12 shirtID
c m
o ฺ
i l ฺ
yourShirt 0x99f311
15.99 price
g m a
u i de
B colorCode
2 4 @ nt G
d h d tude
Variables Objects
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
This diagram showsG
é r a bl point to a particular object in memory. Note that there are two
how references
J o s sfe
objects in memory, although they are both of type Shirt. Also note that there are two Shirt
references
g a r pointing
- t r atonthese two Shirt objects.
Eddiagram
The
n n shows two types of memory that Java uses: the stack and the heap. The stack
oalso
holds local variables, either primitives or reference types, whereas the heap holds objects. Later in
this course, you will learn a little more about local variables, but for now it is sufficient to know that
local variables are not fields of an object.

Java SE 8 Fundamentals 6 - 30
Matis Consulting SฺCฺ

Assigning a Reference to Another Reference


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

myShirt = yourShirt;

0x034009

12
15.99
B

counter s a
10
0x99f311
) ha
myShirt 0x99f311 12 shirtID
c m
o ฺ
i l ฺ
yourShirt 0x99f311
15.99 price
g m a
u i de
B colorCode
2 4 @ nt G
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
The diagram shows G
é
what happens
r a bl if the myShirt reference, after having its own object (in the
previous slide),
J o s sfe the reference yourShirt. When this happens, the myShirt
is now assigned
itsncurrent object and be reassigned to the same object that yourShirt has.
gar two
reference will drop a
As adresult, n - t r
references, myShirt and yourShirt, now point to the same object. Any
E n o
changes to the object made by using one reference can be accessed using the other reference,
and vice versa.
Another effect of assigning the reference yourShirt to the reference myShirt is that if the
previous object referred to by myShirt has no other references, it will now be inaccessible. In
due course, it will be garbage collected, meaning that its memory will become available to store
other objects.

Java SE 8 Fundamentals 6 - 31
Matis Consulting SฺCฺ

Two References, One Object

Code fragment:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

12 Shirt myShirt = new Shirt();


13 Shirt yourShirt = new Shirt();
14
15 myShirt = yourShirt; //The old myShirt object is
16 //no longer referenced
17 myShirt.colorCode = 'R';
18 yourShirt.colorCode = 'G';
19
20 System.out.println("Shirt color: “ + myShirt.colorCode);
s a
)ha
c m
o ฺ
i l ฺ
Output from code fragment:
g ma Guide
2 4 @ nt
Shirt color: G
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
This example now shows G what a l
bhappens if you use either reference to make a change or get a
é
s sfe
value from theoobject. r
References yourShirt and myShirt refer to the same object, so making
a changea J
ror getting aanold
field value by using one reference is exactly the same as doing it with the
g - t r
Ed non
other reference. The object that was previously referenced by myShirt goes away.

Java SE 8 Fundamentals 6 - 32
Matis Consulting SฺCฺ

Exercise 6-2: Modify the ShoppingCart to Use


Item Fields
• In this exercise, you:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– Declare and instantiate two variables of type Item in the


ShoppingCart class
– Experiment with accessing properties and calling methods
on the object

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
• In the Java Code
é G Console,
r a blaccess Lessons > 06-ObjectsClasses > Exercise2.
r J osinstructions
• Follow the
n s fe below the code editor to:
d g-a Declare
n - traand instantiate two variables of type Item.
E - nInitialize
o only the desc field.
- Use different values for each object.
- Display the description of each object.
• If you need help, click the Solution link. To go back to your code, click the Exercise link
again. Any changes that you have made will have been saved.

Java SE 8 Fundamentals 6 - 33
Matis Consulting SฺCฺ

Topics

• Describing objects and classes


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Defining fields and methods


• Declaring, instantiating, and using objects
• Working with object references
• Doing more with arrays
• Introducing NetBeans IDE
• Introducing the soccer league use case
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 6 - 34
Matis Consulting SฺCฺ

Arrays Are Objects

Arrays are handled by an implicit Array object.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• The Array variable is an object reference, not a primitive


data type.
• It must be instantiated, just like other objects.
– Example: This array
int[] ages = new int[4]; can hold four
elements.

• Previously, you have been using a shortcut to instantiate a


your arrays. ) has
m co eฺ
– Example: i l ฺ
int[] ages = {8,7,4,5}; g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
An array is actually an
é bl and is handled implicitly through a class called Array (not
Gobjectratype
available in the
J o s sfe
Java API documentation). Therefore, like other object types (String is an
exception)
g a - aninstantiated using the new keyword.
r it musttrbe
E• d In thenotopn example, an int array called ages is declared and instantiated with a capacity to
hold four elements.

Java SE 8 Fundamentals 6 - 35
Matis Consulting SฺCฺ

Declaring, Instantiating, and Initializing


Arrays
All in one
• Examples: line
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1 String[] names = {"Mary","Bob","Carlos"};


2
3 int[] ages = new int[3];
4 ages[0] = 19; Multistep
5 ages[1] = 42; approach
6 ages[2] = 92;

• Not permitted (compiler will show an error): s a


)ha
m
co eฺ
int [] ages;
i l ฺ
ages = {19, 42, 92}; g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
As introduced in the G
é lesson titled
r a bl“Managing Multiple Items,” there are two approaches for creating
s Using
and initializingoarrays.
J s fe the new keyword allows you to declare and instantiate an array of a
particular
a rsize and
t r a n
initialize it at a later time.
g -
Ed non

Java SE 8 Fundamentals 6 - 36
Matis Consulting SฺCฺ

Storing Arrays in Memory


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

int age = 35;


int[] ages = {19, 42, 92};

Primitive
variable of type
int
0x034009
35 0 Primitive as
a
age
1
19
42 variablesm
h
of) type
ages 0x034009
2 i l ฺ coheldeasฺ
92
m aint
i d
g array
4 Guelements
@ nt
h 2
d tude
d
(e is S
d z
e e th
n us All rights reserved.
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits

e r o H ense
u e rr e lic
G torabyblan object reference variable. The diagram in the slide illustrates
Arrays are objects referred
é
osarraynissstored
how a primitive
r J fe in memory in comparison to how a primitive data type is stored in
memory.
d ga of the
n - ra
tage
E no
The value variable (an int primitive) is 35. The value of ages is 0x034009, an object
reference pointing to an object of type array (of int types) with three elements.
• The value of ages[0] is 19.
• The value of ages[1] is 42.
• The value of ages[2] is 92.

Java SE 8 Fundamentals 6 - 37
Matis Consulting SฺCฺ

Storing Arrays of Object References in Memory

Item item = new Item();


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Item[] items = { new Item(), new Item(), new Item() };

0 itemId
item 0x034009 0.0 price
U colorCode

items 0x99f311 0 itemId


0x99f311 price
0.0
0x00099 U colorCode
s a
0x00327
0 itemId ) ha
0x00990
0.0 price m
co eฺ
U a i l ฺ
colorCode
g m itemId G uid
2 4 @ 0
n t
0.0
hd StUud colorCode e price

( e d
e z t h is
d
án use
Copyright © 2014, e
r n oaffiliates. All rights reserved.
Oracle and/ortits
H s e
r r ero licen
e lehow an object reference array is stored in memory. The value
uillustrates
é G
The diagram in the slide
r a b
J o s
of the item object
s f e
reference is x034009, which is an address to an object of type Item with the
values 0,
g a - an
r0.0, andtrU.
Edvaluenofothe
The n items[ ] object reference is x99f311, which is an address to an object of type
Array (of Item object references) containing three object references:
• The value of the items[0] index is 0x00099, which is an object reference pointing to an
object of type Item.
• The value of the items[1] index is 0x00327, which is an object reference pointing to
another object of type Item.
• The value of the items[2] index is 0x00990, which is an object reference pointing to
another object of type Item.

Java SE 8 Fundamentals 6 - 38
Matis Consulting SฺCฺ

Quiz

The following code is the correct syntax for _____ an array:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

array_identifier = new type[length];


a. Declaring
b. Setting array values for
c. Instantiating
d. Declaring, instantiating, and setting array values for

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
Answer: c
é G rabl
a is incorrect.
J s sthe
oDeclaring fe array would look like this, assuming an array of object types: Type[]
r n
ga n-tra
array_identifier;
d
bE no Setting array values would look like this, assuming an array of object types:
is incorrect.
array_identifier[0]= new Type();
c is correct. The code example shows the array being initialized to a specific size.
d is incorrect. Declaring, instantiating, and setting array values would look like this, assuming an
array of object types:
Type[] array_identifier = {new Type(), new Type(), new Type()};

Java SE 8 Fundamentals 6 - 39
Matis Consulting SฺCฺ

Quiz

Given the following array declaration, which of the following


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

statements are true?


int [ ] ages = new int [13];
a. ages[0] is the reference to the first element in the array.
b. ages[13] is the reference to the last element in the
array.
c. There are 13 integers in the ages array.
d. ages[5] has a value of 0. a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
Answer: a, c, d
é G rabl
r J os nsfe
d ga n-tra
E no

Java SE 8 Fundamentals 6 - 40
Matis Consulting SฺCฺ

Topics

• Describing objects and classes


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Defining fields and methods


• Declaring, instantiating, and using objects
• Working with object references
• Doing more with arrays
• Introducing NetBeans IDE
• Introducing the soccer league use case
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 6 - 41
Matis Consulting SฺCฺ

Java IDEs

A Java Integrated Development Environment (IDE) is a type of


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

software that makes it easier to develop Java applications.


• An IDE provides:
– Syntax checking
– Various automation features
– Runtime environment for testing
• It enables you to organize all your Java resources and
environment settings into a Project. a
a s
m )h
i l ฺ co eฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
G IDEsraare
Some well-known Java
é blNetBeans (used in this class to perform the practices), Eclipse,
r J os nsfe
and JDeveloper.

d ga n-tra
E no

Java SE 8 Fundamentals 6 - 42
Matis Consulting SฺCฺ

The NetBeans IDE

Code Editor
Project
Navigator
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Class
a
Navigator
) has
l ฺ c om ฺ
m ai ide
Program Output @ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
é G armechanism
The Java project provides
a bl by which you can organize all of the source and class
s sf(connection
files and otheroresources
J e profiles, configuration information, and so on) required by
the Java r
a -tra
application. n
d gWhen n begin working in NetBeans, you either create a project or open an existing one.
E noyou

• The Project Navigator gives you a visual representation of the project contents.
• You can open files from your project in the code editor by double-clicking the file or using the
context menu.
When you select a class within the project, the structure of that class is displayed in the Class
Navigator, shown in the lower left part of the NetBeans window.
When you run a file or the entire Java program, any program output appears in the Output panel in
the lower right part of the window.

Java SE 8 Fundamentals 6 - 43
Matis Consulting SฺCฺ

Creating a Java Project

1. Select File > New Project.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2. Select Java Application.


3. Name and set the location
for the project.
4. Select “Create Main Class”
if you want it done for you
automatically.
5. Click Finish. a
a s
m )h
i l ฺ co eฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
A NetBeans project is
é r a bl for organizing the related files and resources used in a Java
Ga mechanism
oscreatenasnew
Application. To
r J fe project, perform the following steps:
d ga File
1. Select
n - t>raNew Project from the menu.
E2. On the
n ofirst page of the New Project Wizard (not shown here), select Java as the category
and Java Application as the project type. Click Next.
3. On the second page of the wizard (shown above), enter a name for the project, and then
enter or browse to the directory location to store project files.
4. It is possible to have NetBeans automatically generate a main class for the project.
5. Click Finish.

Java SE 8 Fundamentals 6 - 44
Matis Consulting SฺCฺ

Creating a Java Class

1. Select File > New File.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2. Select your project and choose Java Class.


3. Name the class.
4. Assign a package.
5. Click Finish.

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
G yourranew
To create a class within
é bl project, perform the following steps:
r J os> New
1. Select File
n s fe from the menu.
File
2. g
d On
n ra of the New File Wizard, select your project, and then accept the default file
athe first-tpage
E typenofoJava Class. Click Next.
3. On the next page of the wizard, enter a name for the Java class. By convention, Java
classes should start with an uppercase letter and each subsequent word in the class name
should be capitalized (for example, SayHello). This is illustrated in the screenshot above.
4. Assign a package for the class.
5. Click Finish.
Note: If the package for this new class already exists, you can create the class by right-clicking
the package in the Project Navigator panel in NetBeans and selecting New > Java class from the
context menu instead of starting from the File menu.

Java SE 8 Fundamentals 6 - 45
Matis Consulting SฺCฺ

Avoiding Syntax Problems

The code editor will tell you when you have done something
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

wrong.

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
G thercode
Most Java editors check
é a bl syntax and show alerts by using icons and red underlines where
r J osin thencode.
there are errors
s fe
d gasyntax
To avoid
n - tra
problems, be sure to do the following:
E• Observe
no any red bubble indicators in the code editor to locate syntax errors.
• Have a semicolon at the end of every line where one is required.
• Have an even number of symbols such as braces, brackets, and quotation marks.
The screenshot shows an error in Line 13, in which there is a missing semicolon. If you place your
cursor over the red bubble, the editor offers a suggestion for fixing the error.

Java SE 8 Fundamentals 6 - 46
Matis Consulting SฺCฺ

Compile Error: Variable Not Initialized

1 public static void main(String[] args){


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2
3 Customer customer01; //Declare the reference
4 //No instantiation
5 customer01.name = "Robert";
9
10 }

s a
)ha
NetBeans indicates that c m
o ฺ
i l ฺ
the variable may not
g m a
u i de
have been initialized. @ nt G
2
d tude4
d h
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
G rthat
If you try to use a reference
a l been declared but has had no object assigned to it, the class
bhas
will not compile.
o é
s sfe there is no Customer object assigned to the customer01
This is because
reference.
a J
rNetBeans anwill flag this, and indicate that “the variable may not have been initialized.”
g - t r
Ed non

Java SE 8 Fundamentals 6 - 47
Matis Consulting SฺCฺ

Runtime Error: NullPointerException

1 public static void main(String[] args){


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2
3 Customer customer01; //Declare the reference
4 customer01 = new Customer(); //Instantiate and assign
5 customer01.name = "Robert";
6
7 Customer[] customers = new Customer[5];
8 customers[0].name = "Robert";
9
10 }

a
NetBeans output window
) has
indicates a m
This reference has NullPointerException. li ฺco eฺ
not been assigned. g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
If an array has beenG
é created but
r a blthe individual elements have had no objects assigned, the class
will compile, but
J o s sfe
you will get a runtime error. The error is a NullPointerException. Later in the

g a r “Handling
lesson titled
- t r an Exceptions,” you will learn exactly what this means; for now it is just
Ed non
important to recognize
assigned; that it is null.
that a NullPointerException indicates that a reference has no object

Java SE 8 Fundamentals 6 - 48
Matis Consulting SฺCฺ

Compiling and Running a Program by


Using NetBeans
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
)ha
m
co eฺ
Save is equivalent i l ฺ
to javac. g ma Guid
2 4 @ nt
Run is equivalent
d h d tude
to java. z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
Save invokes the javac
é r a bl
G <classname(s)> command for all .java files in the project. Right-

J o s sfe
clicking the source code and selecting Run File invokes the java <classname> command. Be
sure to a r for red
look
t r n indicators in the code editor to locate syntax errors.
abubble
g -
Ed non

Java SE 8 Fundamentals 6 - 49
Matis Consulting SฺCฺ

Topics

• Describing objects and classes


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Defining fields and methods


• Declaring, instantiating, and using objects
• Working with object references
• Doing more with arrays
• Introducing NetBeans IDE
• Introducing the soccer league use case
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 6 - 50
Matis Consulting SฺCฺ

Soccer Application

Practices 6 through 14 build a soccer league application with


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

the following features:


• Any number of soccer teams, each with up to 11 players
• Set up an all-play-all league.
• Use a random play game generator to create test games.
• Determine the rank order of teams at the end of the
season.
s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
G inrathisblcourse, you will build an application that manages a Soccer
In the remaining practices
é
os nsfwill
League. The application
r J e keep details on teams and players, as well as the results of games.
You will
g aalso write
- t a that will randomly generate game results so that you can then develop
rcode
d n
E to listnothe Teams in rank order.
code

Java SE 8 Fundamentals 6 - 51
Matis Consulting SฺCฺ

Creating the Soccer Application

A separate
project
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

for each
practice

Sample output
showing events in
a game a
) has
l ฺ c om ฺ
Sample output m ai ide
@ g t Gu
showing rank 4
order of teams h d 2
u d en
( e d S t
ez e th i s
n d
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
G willrbe
Initially, your application
a l
bdeveloped in NetBeans and you will see the results of running
your code as o texté
s in thesoutput
fe window.
r J n
d ga n-tra
E no

Java SE 8 Fundamentals 6 - 52
Matis Consulting SฺCฺ

Soccer Web Application


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Points and as
a
Click the score goalsm )h
scored
Teams listed in of a game to l ฺ o forฺ
cused
a i e
rank order show game gm ordering uid
details.
2 4 @ nt G
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
é G in the
The code that you write
r a bl
practices can be used by a simple web application to view the

r J osin the
results of games
n s fe You will see a demonstration of this.
league.

d ga n-tra
E no

Java SE 8 Fundamentals 6 - 53
Matis Consulting SฺCฺ

Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Describe the characteristics of a class


• Define an object as an instance of a class
• Instantiate an object and access its fields and methods
• Describe how objects are stored in memory
• Instantiate an array of objects
• Describe how an array of objects is stored in memory
a
• Declare an object as a field
) has
• Use the NetBeans IDE o m
ฺc il
g
a
m Guideฺ
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 6 - 54
Matis Consulting SฺCฺ

Challenge Questions: Java Puzzle Ball

• How many objects can you identify in the game?


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Given that a class is a blueprint for an object, which game


components best reflect the class/instance relationship?
• How many object properties can you find?
• Can you guess what some of the methods might be?

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u e rr e lic
G rabtol play the game, see if you can answer these questions, applying
When you have an opportunity
é
r J os concepts
the object-oriented
n s fe that you learned in this lesson.
For some
d g a possible
n - t raanswers to these questions and more discussion, see “Appendix A: Java
E BallnoChallenge Questions Answered.”
Puzzle

Java SE 8 Fundamentals 6 - 55
Matis Consulting SฺCฺ

Practice 6-1 Overview:


Creating Classes for the Soccer League
This practice covers creating the five classes required for the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

soccer application:
• Goal
• Game
• Player
• Team
• League
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 6 - 56
Matis Consulting SฺCฺ

Practice 6-2 Overview:


Creating a Soccer Game
This practice covers the following topics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Creating a new game


• Adding some goals

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/ortits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 6 - 57
Matis Consulting SฺCฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
e rná to us
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no
Matis Consulting SฺCฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Manipulating and Formatting the Data in Your


Program

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no
Matis Consulting SฺCฺ

Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Describe the String class and use some of the methods


of the String class
• Use the JDK documentation to search for and learn how to
use a class
• Describe the StringBuilder class
• Explain what a constant is and how to use it
• Explain the difference between promoting and casting of a
variables has
m) co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 7 - 2
Matis Consulting SฺCฺ

Topics

• Using the String class


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Using the Java API docs


• Using the StringBuilder class
• Doing more with primitive data types
• Using the remaining numeric operators
• Promoting and casting variables

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 7 - 3
Matis Consulting SฺCฺ

String Class

String hisName = “Fred Smith"; Standard syntax


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

The new keyword can be used,


but it is not best practice:

String herName = new String(“Anne Smith”);

• A String object is immutable; its value cannot be


changed. a
a s
• A String object can be used with the string concatenation
m )h
operator symbol (+) for concatenation.
i l ฺ co eฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
• The String G
é
class is one
r a blof the many classes included in the Java class libraries. The
String
J sclass provides
oString s fe you with the ability to store a sequence of characters. You will
use
a r the
t r a n class frequently throughout your programs. Therefore, it is important to
g -
Ed understand
non Because
language.
some of the special characteristics of strings in the Java programming
a String object is immutable, its value cannot be changed. (There
are technical reasons, beyond the scope of this course, as to why this immutability is
useful. One simple example is that this immutability ensures that a String can be used
by several different classes safely because it cannot be changed.)
• Creating a String object using the new keyword creates two String objects in
memory, whereas creating a String object by using a string literal creates only one
object; therefore, the latter practice is more memory-efficient. To avoid the unnecessary
duplication of String objects in memory, create String objects without using the new
keyword.

Java SE 8 Fundamentals 7 - 4
Matis Consulting SฺCฺ

Concatenating Strings
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

String myString = "Hello";

0x034009

Hello

a
) has
myString 0x034009
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Because String isGimmutable,
é r a bl concatenating two strings requires creating a new string.
The diagram
J s asString
oshows fe object containing the string “Hello”.
r n
d ga n-tra
E no

Java SE 8 Fundamentals 7 - 5
Matis Consulting SฺCฺ

Concatenating Strings
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

String myString = "Hello";


myString = myString.concat(" World");

0x034009

"Hello"

s a
0x99f311
) ha
myString 0x99f311
c m
o ฺ
i l ฺ
"Hello World"
g ma Guide
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Here is the string “ G
é r a bl concatenated to the original string. The concat method is
World” being
Jos and
being used here,
is rcreated
object a n fe you use that or the concatenation operator (+), a new String
but whether
s
a new String reference is returned that points to this new object.
a
g
d diagram, - t r
Ethe
In
n on this is shown by the fact that the String reference myString is no longer
0x034009, and because that object is no longer referred to, it is now inaccessible and will be
garbage collected.

Java SE 8 Fundamentals 7 - 6
Matis Consulting SฺCฺ

Concatenating Strings

String myString = "Hello";


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

myString = myString.concat(" World");


myString = myString + "!"

0x99f311

"Hello World"

s a
0x74cd23
) ha
myString 0x74cd23
c m
o ฺ
i l ฺ
"Hello World!"
g ma Guide
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é G another
Finally, on concatenating
r a bl string, this time using the concatenation operator, the same
thing happens
r J osagain.nsAfnew
e object is created and the reference for this object is assigned to
ga n-tra
myString.
d
E no

Java SE 8 Fundamentals 7 - 7
Matis Consulting SฺCฺ

String Method Calls with Primitive Return


Values
A method call can return a single value of any type.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• An example of a method of primitive type int:


String hello = "Hello World";
int stringLength = hello.length();

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Like most classes, G
é
the String
r a blclass has a number of useful methods. Almost all of these
methods do o
J s useful
their
s fework by returning a single value (Java allows only a single return from
a r
a method). The
t a n
return
r type (essentially the type of the method) can be a primitive or a
g -
Ed ntoonan object.
reference
To be able to use the return value in your code, you will typically use the assignment operator
to assign the value (or reference) to a type that you have declared for this purpose.
The example in the slide shows the use of reference hello to call the method length.
Because the object this reference refers to is the string Hello World, this method call will
return the value 11 and place it in the variable stringLength. int is the type of the method
length.

Java SE 8 Fundamentals 7 - 8
Matis Consulting SฺCฺ

String Method Calls with Object Return Values

Method calls returning objects:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

String greet = " HOW ".trim();


String lc = greet + "DY".toLowerCase();
Or
String lc = (greet + "DY").toLowerCase();

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
This example shows Gseveral a l calls that return object references.
bmethod
é
os object r
fe" HOW " is instantiated and has the method trim called on it.
First, the String
r J n s
Because
d g a a string
n - tra
literal returns an object reference, this is exactly the same as calling the
E trim
method
n o on the reference. Notice that the string " HOW " has two spaces on either
side of the word. The string returned will be just three characters long because these spaces
will be removed. This new string will be referenced by greet.
The next example shows a method call not being assigned to a type, but simply used in an
expression. The method toLowerCase is called on the string "DY", returning "dy". lc now
references an object containing "HOWdy".
Finally, note how an alternative version with parentheses ensures that the two strings are
concatenated (creating a new string) before toLowerCase is called. lc now references an
object containing "howdy".

Java SE 8 Fundamentals 7 - 9
Matis Consulting SฺCฺ

Topics

• Using the String class


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Using the Java API docs


• Using the StringBuilder class
• Doing more with primitive data types
• Using the remaining numeric operators
• Promoting and casting variables

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 7 - 10
Matis Consulting SฺCฺ

Java API Documentation

Consists of a set of webpages;


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Lists all the classes in the API


– Descriptions of what the class does
– List of constructors, methods, and fields for the class
• Highly hyperlinked to show the interconnections between
classes and to facilitate lookup
• Available on the Oracle website at:
http://download.oracle.com/javase/8/docs/api/index.html a
a s
m )h
i l ฺ co eฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G rJDKs
All of the Java technology
é a bl contain a series of prewritten classes for you to use in your
r J os Java
programs. These
n s e
ftechnology class libraries are documented in the Java API
documentation
g a -
for
t r athe version of the JDK that you are using. The class library specification is
d ofoHTML
aEseries n webpages that you can load in your web browser.
n
A Java class library specification is a very detailed document outlining the classes in the API.
Every API includes documentation describing the use of classes and their fields and methods.
When you are looking for a way to perform a certain set of tasks, this documentation is the
best source for information about the classes in the Java class libraries.
You learn more about constructors in the “Using Encapsulation” lesson.

Java SE 8 Fundamentals 7 - 11
Matis Consulting SฺCฺ

Java Platform SE 8 Documentation


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Details about the


Select All Classes class selected
or a particular
package.

The classes for the


selected package(s)
are listed here.
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
In the screenshot inG l can see the three main panels of the webpage.
the slide,byou
a
é
s allows
opanel r
fe you to select a package. Java classes are organized into
The top-right
r J n s
a do not know the package of a particular class, you can select All
ga butn-iftryou
packages,
d
E no
Classes.
The bottom-left panel gives the list of classes in a package, or all classes if that has been
selected. In this panel, the class String has been selected, populating the main panel on the
right with the details of the class String. The main panel on the right contains a lot of
information about the class, so you need to scroll down to access the information you need.

Java SE 8 Fundamentals 7 - 12
Matis Consulting SฺCฺ

Java Platform SE 8: Method Summary

public int charAt(String str)


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

The type of the parameter that must


The name of
be passed into the method
The return type the method
of the method

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é Gthrough
If you keep scrolling
r a bl details for the String class, you will come to the list of
the
methods (only
r J osa small
n s fe of this list is shown here).
subset
This g
d a list-toframethods gives the basic details for the method. In this case, you can see
master
E the name
that
n on of the method is charAt, its type is char, and it requires an index (of type
int) to be passed in. There is also a brief description that this method returns the char value
at a particular index in the string. For any of the methods, the method name and the
parameter types are hyperlinked so that you can get more details.

Java SE 8 Fundamentals 7 - 13
Matis Consulting SฺCฺ

Java Platform SE 8: Method Detail

Click here to get the detailed


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

description of the method.

Detailed description for the


indexOf() method

a
) has
l ฺ c om ฺ
Further details about m ai ide
parameters and return value @ g t Gu
are shown in the method list. d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
For any of the methods,
é bl name and the parameter types are hyperlinked so that
G theramethod
you can get more
J s details.
omethods s feThe example here shows the detailed description for one of the
a
indexOf()r t r n
a String.
of
g -
Ed non

Java SE 8 Fundamentals 7 - 14
Matis Consulting SฺCฺ

indexOf Method Example


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1 String phoneNum = "404-543-2345"; The 1-arg version


2 int idx1 = phoneNum.indexOf('-');
3 System.out.println("index of first dash: "+ idx1);
4 The 2-arg version
5
6 int idx2 = phoneNum.indexOf('-', idx1+1);
7 System.out.println("second dash idx: "+idx2);

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
This example shows
é bl the location of the first ‘-’ character by using the 1-arg version
Ghow rtoaget
of indexOf,oand
J s thensby
feusing the 2-arg version to get the location of the second ‘-’.
r n
a the phone number to an int, you could do something like this:
a to-trconvert
If yougwanted
d n
E1. Findnothe dashes by using the indexOf method (as shown above).
2. Build a new String without dashes by using the substring method and
concatenation.
3. Convert this String to an int by using the parseInt method of Integer.
The parseInt method of the Integer class is covered in the lesson “Using Encapsulation.”

Java SE 8 Fundamentals 7 - 15
Matis Consulting SฺCฺ

Topics

• Using the String class


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Using the Java API docs


• Using the StringBuilder class
• Doing more with primitive data types
• Using the remaining numeric operators
• Promoting and casting variables

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 7 - 16
Matis Consulting SฺCฺ

StringBuilder Class

StringBuilder provides a mutable alternative to String.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

StringBuilder:
• Is instantiated using the new keyword
• Has many methods for manipulating its value
• Provides better performance because it is mutable
• Can be created with an initial capacity
String is still needed because:
• It may be safer to use an immutable object a
) has
• A method in the API may require a string
l ฺ c om ฺ
• It has many more methods not available on mai uide
g
StringBuilder 4@ nt G 2
d h d t u de
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The StringBuilder
é G classr a bl“mutable.” This means that it can be changed in place. You will
is

r os youString
recall that when
Jvalue. n s fe the value of a String variable, a new String object is created
modify
for the a
g new
- t r a objects are “immutable.” A String object’s value cannot be
Ed non
changed.
• Unlike String, there is no shortcut to instantiate a StringBuilder. It is simply
instantiated like any other object by using the new keyword.
• A small sampling of the StringBuilder methods for manipulation of data values are:
append, delete, insert, and replace.
• StringBuilder provides better performance because it does not create new objects
in memory whenever a change is made. Performance is also benefited whenever you
can set an initial capacity for the object, as opposed to letting it grow and allocate
memory dynamically.
• StringBuilder is not a complete replacement for String, but it is more suitable if
many modifications are likely to be made to its value.

Java SE 8 Fundamentals 7 - 17
Matis Consulting SฺCฺ

StringBuilder Advantages over String


for Concatenation (or Appending)

•String concatenation
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

String myString = "Hello";


• Costly
myString in terms
= myString + "of World";
creating new objects

0x99f311

"Hello "

s a
0x74cd23
) ha
myString 0x74cd23
c m
o ฺ
i l ฺ
"Hello World"
g ma Guide
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G raofbwhat
This slide offers a reminder l happens when the strings "Hello" and " World" are
concatenated. é
osA newnsString
fe object is created, and the reference for that object is assigned
r J
ga n-tra
to myString.
d
E no

Java SE 8 Fundamentals 7 - 18
Matis Consulting SฺCฺ

StringBuilder: Declare and Instantiate


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

StringBuilder mySB = new StringBuilder("Hello");

0x034009

"Hello" a
) has
mySB 0x034009
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
This diagram shows
é Gthe start
r a bofl a sequence involving a StringBuilder. A new
StringBuilder
r J osis assigned
n s fe
is instantiated, populated with the string "Hello", and the reference for

d ga n-tra
this new object to mySB.
E no

Java SE 8 Fundamentals 7 - 19
Matis Consulting SฺCฺ

StringBuilder Append
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

StringBuilder mySB = new StringBuilder("Hello");


mySB.append(" World");

0x034009

"Hello World"
s a
) ha
mySB 0x034009 m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
To append the string
é G" World",
r a bl all you need to do is call the append method and pass in
“World”. Note
r J osthat non s fe
assignment (=) is necessary because there is already a reference to
the StringBuilder
g a - t r a object, and this StringBuilder object now contains a representation
of d combined
Ethe on strings "Hello World".
n
Even if you did assign the return type of the append method (which is StringBuilder),
there would still be no object creation cost; the append method modifies the current object
and returns the reference to that object, the one already contained in mySB.

Java SE 8 Fundamentals 7 - 20
Matis Consulting SฺCฺ

Quiz

Which of the following statements are true? (Choose all that


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

apply.)
a. The dot (.) operator creates a new object instance.
b. The String class provides you with the ability to store a
sequence of characters.
c. The Java API specification contains documentation for all
of the classes in a Java technology product.
d. String objects cannot be modified. a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
Answer: b, c, d G a b
s é e r
a r Jo ansf
g tr
Ed non-

Java SE 8 Fundamentals 7 - 21
Matis Consulting SฺCฺ

Exercise 7-1: Use indexOf and substring


Methods
In this exercise, you use indexOf and substring methods to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

get just the customer’s first name and display it.

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
• Open the Java
é a bl and access 07-ManipulateFormat > Exercise1.
GCoderConsole
• Follow
r J othes instructions
n s fe below the code editor to:
d ga- Use
n - ra indexOf method to get the index of the space character (“ ”) within
tthe
E nocustName. Assign it to spaceIdx.
- Use the substring method and the spaceIdx to get just the first name portion of
custName. Assign it to firstName. Print firstName.
• If you need help, click the Solution link. To go back to your code, click the Exercise link
again. Any changes that you have made will have been saved.

Java SE 8 Fundamentals 7 - 22
Matis Consulting SฺCฺ

Exercise 7-2: Instantiate the StringBuilder


object
In this exercise, you instantiate a StringBuilder object,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

initializing it to firstName using the StringBuilder


constructor.

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
• Open the Java
é GCoderConsole
a bl and access 07-ManipulateFormat > Exercise2.
• Follow
r J othes instructions
n s fe below the code editor to:
d n - tra the StringBuilder object (sb), initializing it to firstName, using the
ga- Instantiate
E noStringBuilder constructor.
- Use the append method of the StringBuilder object to put the customer full
name back together again, and then print the StringBuilder object.
• If you need help, click the Solution link. To go back to your code, click the Exercise link
again. Any changes that you have made will have been saved.

Java SE 8 Fundamentals 7 - 23
Matis Consulting SฺCฺ

Topics

• Using the String class


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Using the Java API docs


• Using the StringBuilder class
• Doing more with primitive data types
• Using the remaining numeric operators
• Promoting and casting variables

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 7 - 24
Matis Consulting SฺCฺ

Primitive Data Types

• Integral types (byte, short, int, and long)


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Floating point types (float and double)


• Textual type (char)
• Logical type (boolean)

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Many of the valuesG
é r a bl
in Java technology programs are stored as primitive data types. The slide

r J ssome
lists the eightoprimitive
learnedaabout n s fe built in to the Java programming language. You have already
types
a these and have been using them in your exercises and practices. Now
of
g - t r
Edwill see
you
nonthe remaining primitive types.

Java SE 8 Fundamentals 7 - 25
Matis Consulting SฺCฺ

Some New Integral Primitive Types

Type Length Range


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

byte 8 bits –27 to 27 – 1


(–128 to 127,
or 256 possible values)
short 16 bits –215 to 215 – 1
(–32,768 to 32,767, or 65,535 possible
values)
int 32 bits –231 to 231 –1
(–2,147,483,648 to 2,147,483,647, or
4,294,967,296 possible values)
s a
long 64 bits 63 –2 to 2 – 1
63
)h a
(–9,223,372,036854,775,808 to co m
9,223,372,036854,775,807,aoril
ฺ eฺ
18,446,744,073,709,551,616 m u i
g tpossible d
4 @ G
values)
h d 2
u d en
( e d S t
ez e th i s
n d
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
There are four integral
é G primitive
r a bl types in the Java programming language. You have already
r Josint
been using the
to storeanumbers n fetype, so the focus here is on the other three. Integral types are used
data
s
a not have decimal portions. They are shown here in order of size.
that do
g - t r
E• d byte:
n oIfnyou need to store people’s ages, a variable of type byte would work because
byte types can accept values in that range.
• short: A short will hold 16 bits of data.
• long: When you specify a literal value for a long type, put a capital L to the right of the
value to explicitly state that it is a long type. Integer literals are assumed by the
compiler to be of type int unless you specify otherwise by using an L indicating long
type.
• You can express any of the integral types as binary (0s and 1s). For instance, a
binary expression of the number 2 is shown as an allowed value of the byte integral
type. The binary value is 0b10. Notice that this value starts with 0b (that is, zero
followed by either a lowercase or uppercase letter B). This indicates to the compiler that
a binary value follows.

Java SE 8 Fundamentals 7 - 26
Matis Consulting SฺCฺ

Examples of allowed literal values:


• byte = 2, -114, 0b10 (binary number)
• short = 2, -32699
• int (default type for integral literals) = 2, 147334778, 123_456_678
• long = 2, –2036854775808L, 1
Note: The only reason to use the byte and short types in programs is to save memory
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

consumption. Because most modern desktop computers contain an abundance of memory,


most desktop application programmers do not use byte and short types. This course uses
primarily int and long types in the examples.

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
e rná to us
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 7 - 27
Matis Consulting SฺCฺ

Floating Point Primitive Types

Type Float Length


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

float 32 bits
double 64 bits
(default type for floating
point literals)

Example:
public float pi = 3.141592F;
s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
There are two typesGfor floating
é r a blpoint numbers: float and double. Again, the focus is on the
new data type
r J oshere,nthe
s fefloat. Floating point types are used to store numbers with values to
the right
g a of the
- t r a point, such as 12.24 or 3.14159.
decimal
E• d float
nonis used to store smaller floating point numbers. A float variable can hold 32 bits.
• Floating point values are assumed to be of type double unless you specify by putting a
capital F (float) to the right of the value to explicitly state that it is a float type, not a
double type.
Examples of allowed literal values:
float = 99F, -327456,99.01F, 4.2E6F (engineering notation for 4.2 * 106
)
double = -1111, 2.1E12, 99970132745699.999
Note: Use the double type when a greater range or higher accuracy is needed.

Java SE 8 Fundamentals 7 - 28
Matis Consulting SฺCฺ

Textual Primitive Type

• The only primitive textual data type is char.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• It is used for a single character (16 bits).


• Example:
– public char colorCode = 'U';

Single quotes must be used with char literal values.

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Another data type that
é G yourauseblfor storing and manipulating data is single-character
information. o
J Thes primitive
s fetype used for storing a single character (such as a 'y') is char,
which is
a r
16 bits
tin
r n
a The Shirt class shows the use of one textual literal value to specify
size.
g -
Eddefault
the
n n for a colorCode:
ovalue
public char colorCode = 'U';
When you assign a literal value to a char variable, you must use single quotation marks
around the character as shown in the code example above.

Java SE 8 Fundamentals 7 - 29
Matis Consulting SฺCฺ

Java Language Trivia: Unicode

• Unicode is a standard character encoding system.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– It uses a 16-bit character set.


– It can store all the necessary characters from most
languages.
– Programs can be written so they display the correct
language for most countries.

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Did You Know? Many G oldera l
bcomputer languages use American Standard Code for
é r
os nsfe(ASCII), an 8-bit character set that has an entry for every English
Information Interchange
r
character,
a J a mark, number, and so on.
punctuation
g - t r
EdJavanprogramming
The on language uses a 16-bit character set called Unicode that can store all
the necessary displayable characters from the vast majority of languages used in the modern
world. Therefore, your programs can be written so that they work correctly and display the
correct language for most countries. Unicode contains a subset of ASCII (the first 128
characters).

Java SE 8 Fundamentals 7 - 30
Matis Consulting SฺCฺ

Constants

• Variable (can change):


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– double salesTax = 6.25;


• Constant (cannot change):
– final int NUMBER_OF_MONTHS = 12;

The final keyword causes


a variable to be read only.
s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
In this lesson, you have
é G learned
r a bl about variables that have values that you can change. In this
section, you o
J s howsftoeuse constants to represent values that cannot change.
learn
Assumeg a r
that you
- t r aarenwriting part of a scheduling application, and you need to refer to the
Ed ofnomonths
number n in a year. Make the variable a constant by using the final keyword to
inform the compiler that you do not want the value of the variable to be changed after it has
been initialized. Example:
final int NUMBER_OF_MONTHS = 12;
Any values that do not need to change are good candidates for a constant variable (for
example, MAX_COUNT, or PI).
If someone attempts to change the value of a constant after it has already been assigned a
value, the compiler gives an error message. If you modify your code to provide a different
value for the constant, you need to recompile your program.
Guidelines for Naming Constants
You should name constants so that they can be easily identified. Generally, constants should
be capitalized, with words separated by an underscore (_).

Java SE 8 Fundamentals 7 - 31
Matis Consulting SฺCฺ

Quiz

The variable declaration public int myInteger=10;


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

adheres to the variable declaration and initialization syntax.


a. True
b. False

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
Answer: a
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 7 - 32
Matis Consulting SฺCฺ

Topics

• Using the String class


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Using the Java API docs


• Using the StringBuilder class
• Doing more with primitive data types
• Using the remaining numeric operators
• Promoting and casting variables

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 7 - 33
Matis Consulting SฺCฺ

Modulus Operator

Purpose Operator Example Comments


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Remainder % num1 = 31; Remainder finds the


num2 = 6; remainder of the first
number divided by the
modulus mod = num1 % num2; second number.
5 R 1
mod is 1 6 31
30
-----
1
Remainder always gives a
an answer with the
same sign as the first ) has
operand. l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Programs do a lot of
é r a bl calculating, from the simple to the complex. Arithmetic
Gmathematical
s specify
operators letoyou
J s fehow the numerical values within variables should be evaluated or
a r
combined. The n
a mathematical operators (often called binary operators) used in the
standard
t r
g -
Ed programming
Java
n on language are shown in the tables in this section.
Note: The % is known as the modulus operator.

Java SE 8 Fundamentals 7 - 34
Matis Consulting SฺCฺ

Combining Operators to Make Assignments

Purpose Operator Examples Result


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

int a = 6, b = 2;
Add to and assign += a += b a=8
Subtract from and -= a -= b a=4
assign
Multiply by and assign *= a *= b a = 12
Divide by and assign /= a /= b a=3
Get remainder and %= a %= b a=0
assign a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Several very usefulG shortcutsb
a l shown in the table above. You can combine any operator
are
with the equal é
ossign to fe r
abbreviate your code. For example:
r J n s
d gaa = na-t+rab;
Ecan benexpressed
o as:
a += b;

Java SE 8 Fundamentals 7 - 35
Matis Consulting SฺCฺ

More on Increment and Decrement Operators

Operator Purpose Example


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

++ Preincrement int id = 6;
(++variable) int newId = ++id;
id is 7, newId is 7

Postincrement int id = 6;
(variable++) int newId = id++;
id is 7, newId is 6
-- Predecrement (same principle applies)
(--variable)
Postdecrement s a
(variable--) )ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G rand
You have used increment
a l
bdecrement operators before, placing them after the variable
that you wishoto é
s affect.sfBut
e did you know that these operators can come before (preincrement
r J
and predecrement)
a a n
or after (postincrement and postdecrement) a variable.
g - t r
Ed younoputn the ++ or -- operator before a variable, the value is changed immediately.
When
When you put the operator after the variable, it is not changed until after that expression is
evaluated.
• In the first code example above, id is initialized to 6. In the next line, you see newId =
++id. Because the operator precedes id, this increment is immediately evaluated and,
therefore, the value assigned to newId is 7.
• In the second code example, the ++ operator follows id, rather than precedes it. id was
incremented after the assignment occurred. Therefore, newId is 6.
• These same behaviors apply to a decrement (--) operator, in regard to its placement
before or after the variable.

Java SE 8 Fundamentals 7 - 36
Matis Consulting SฺCฺ

Increment and Decrement Operators (++ and ––)

Examples:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1 int count=15;
2 int a, b, c, d;
3 a = count++;
4 b = count;
5 c = ++count;
6 d = count;
7 System.out.println(a + ", " + b + ", " + c + ", " + d);

a
Output: ) has
15, 16, 17, 17 l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The example in theG
é slide shows
r a bl basic use of the increment and decrement operators:
J os nsfe
int count=15;
r
d a a, -b,
gint n trac, d;
E a n= ocount++;
b = count;
c = ++count;
d = count;
System.out.println(a + ", " + b + ", " + c + ", " + d);
The result of this code fragment is:
15, 16, 17, 17
Discussion: What is the result of the following code?
int i = 16;
System.out.println(++i + " " + i++ + " " + i);

Java SE 8 Fundamentals 7 - 37
Matis Consulting SฺCฺ

Topics

• Using the String class


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Using the Java API docs


• Using the StringBuilder class
• Doing more with primitive data types
• Using the remaining numeric operators
• Promoting and casting variables

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 7 - 38
Matis Consulting SฺCฺ

Promotion

• Automatic promotions:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– If you assign a smaller type to a larger type

byte short int long

– If you assign an integral type to a floating point type

s a
3 3.0
)ha
m
co eฺ
i l ฺ
• Examples of automatic promotions: g ma Guid
2 4 @ nt
– long intToLong = 6;
d h d tude
– double intToDouble = 3; z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
In some circumstances,
é bl changes the type of a variable to a type that supports a
G theracompiler
r J os This
larger size value.
n s fe is referred to as a promotion. Some promotions are done
action
automatically
g a by
- t r a
the compiler. These promotions include:
E• d If you n a smaller type (on the right of the =) to a larger type (on the left of the =)
noassign
• If you assign an integral type to a floating point type (However, in some cases, such as
an assignment of long to float, this could lead to loss of data.)

Java SE 8 Fundamentals 7 - 39
Matis Consulting SฺCฺ

Caution with Promotion

Equation:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

55555 * 66666 = 3703629630


Example of potential issue:
1 int num1 = 55555;
2 int num2 = 66666;
3 long num3;
4 num3 = num1 * num2; //num3 is -591337666
Example of potential solution:
s a
1 int num1 = 55555;
)ha
Changed from int to long m
2 long num2 = 66666;
i l ฺ co eฺ
a
uid
3 long num3;
g m G
4 num3 = num1 * num2; @ nt
//num3 is 3703629630
2 4
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Before being assigned
é bl the result of an equation is placed in a temporary location
G to aravariable,
in memory. The s location’s
Jotype s fe size is always equal to the size of an int type or the size of the
r
largestadata
t r a n
used in the expression or statement. For example, if your equation multiplies
g -
Edint ntypes,
two on the container size will be an int type in size, or 32 bits.
If the two values that you multiply yield a value that is beyond the scope of an int type, (such
as 55555 * 66666 = 3,703,629,630, which is too big to fit in an int type), the int value must
be truncated to fit the result into the temporary location in memory. This calculation ultimately
yields an incorrect answer because the variable for your answer receives a truncated value
(regardless of the type used for your answer). To solve this problem, set at least one of the
variables in your equation to the long type to ensure the largest possible temporary container
size.

Java SE 8 Fundamentals 7 - 40
Matis Consulting SฺCฺ

Caution with Promotion

Equation:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

7 / 2 = 3.5
Example of potential issue:
1 int num1 = 7;
2 int num2 = 2;
3 double num3;
4 num3 = num1 / num2; //num3 is 3.0
Example of potential solution:
s a
1 int num1 = 7;
)ha
2 double num2 = 2; Changed from int to double m
co eฺ
a i l ฺ
uid
3 double num3;
g m G
4 num3 = num1 / num2; //num3 is 3.5
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The same issue occurs
é G with r a bl data types. Before being assigned to a variable, the result
other
of an equation
r J osis placed
n s fein a temporary location in memory. The location’s size is always
equal to
g a the size
- t r a largest data type used in the expression or statement. For example, if
of the
Ed equation
your
n ondivides two int types, the container size will be an int type in size, or 32 bits.
If the two values that you use yield a value that is beyond the scope of an int type, (such as
7 / 2 = 3.5), the value must be truncated to fit the result into the temporary location in memory.
This calculation ultimately yields an incorrect answer because the variable for your answer
receives a truncated value (regardless of the type used for your answer). To solve this
problem, set at least one of the variables in your equation to the double type to ensure the
largest possible temporary container size.

Java SE 8 Fundamentals 7 - 41
Matis Consulting SฺCฺ

Type Casting

• When to cast:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– If you assign a larger type to a smaller type

byte short int long

– If you assign a floating point type to an integral type


a
3 3.0
) has
l ฺ c om ฺ
m ai ide
• Examples of casting:
@ g t Gu
– int longToInt = (int)20L; d2 4 en
h u d
– short doubleToShort =z(short)3.0; (ed is St
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Type casting lowers
é Gthe range
r a bofl a value, chopping it down to use a smaller amount of
memory, by o
J s sthe
changing fetype of the value (for example, by converting a long value to an
a r
int value). You
t do
r n
a so that you can use methods that accept only certain types as
this
g
d oso
arguments, -
n that you can assign values to a variable of a smaller data type, or so that you
E n
can save memory.
The syntax for type casting a value is: identifier = (target_type) value, where:
• identifier is the name you assign to the variable
• value is the value you want to assign to the identifier
• (target_type) is the type to which you want to type cast the value. Notice that the
target_type must be in parentheses.

Java SE 8 Fundamentals 7 - 42
Matis Consulting SฺCฺ

Caution with Type Casting

Example of potential issue:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1 int myInt;
2 long myLong = 123987654321L;
3 myInt = (int) (myLong); // Number is "chopped“
4 // myInt is -566397263

Safer example of casting:


1 int myInt;
a
2 long myLong = 99L;
) has
3 myInt = (int) (myLong); // No data loss, only zeroes.
l ฺ c om ฺ
4 // myInt is 99 ai e m Guid
@ ntg
2
d tude4
d h
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The loss of precision
é a bl can sometimes lead to situations where numbers are
Gwith rcasting
r J os tonerrors
truncated, leading
s fe in calculations.
d ga n-tra
E no

Java SE 8 Fundamentals 7 - 43
Matis Consulting SฺCฺ

Caution with Type Casting

• Be aware of the possibility of lost precision.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Example of potential issue:


1 int myInt;
2 double myPercent = 51.9;
3 myInt = (int) (myPercent); // Number is "chopped“
4 // myInt is 51

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
If you type cast a float
é bl value with a fractional part to an integral type such as an
G orradouble
r J os values
int, all decimal
n s e lost. However, this method of type casting is sometimes useful if
fare
you want
g a to truncate
- t r a number down to the whole number (for example, 51.9 becomes 51).
the
Ed non

Java SE 8 Fundamentals 7 - 44
Matis Consulting SฺCฺ

Using Promotion and Casting


Example of potential issue:
1 int num1 = 53; // 32 bits of memory to hold the value
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2 int num2 = 47; // 32 bits of memory to hold the value


3 byte num3; // 8 bits of memory reserved
4 num3 = (num1 + num2); // causes compiler error
Solution using a larger type for num3:
1 int num1 = 53;
2 int num2 = 47;
3 int num3; Changed from byte to int
4 num3 = (num1 + num2);
s a
Solution using casting: )ha
m
o ฺ
cvalue
1 int num1 = 53; // 32 bits of memory to hold the i l ฺ
2 int num2 = 47; // 32 bits of memory to hold g ma
the valueu ide
3 byte num3; // 8 bits of memory dreserved 2 4@ ent G
4 num3 = (byte)(num1 + num2); //(eno dhdataSloss tud
e z t h is
d
án use
Copyright © 2014, e
r n oaffiliates. All rights reserved.
Oracle and/or tits
H s e
r r ero licen
G
Assigning a variable uean expression
or b le to another variable can lead to a mismatch between the
sécalculation
data types ofothe f a
er and the storage location that you are using to save the result.
J s
an will either recognize that precision will be lost and not allow you to
r thetrcompiler
Specifically,
g a
d theoprogram,-
compile
E n n or the result will be incorrect. To fix this problem, variable types have to
be either promoted to a larger size type, or type cast to a smaller size type. In the above
example, the compiler assumes that because you are adding int values, the result will
overflow the space allocated for a byte.
A byte, though smaller than an int, is large enough to store a value of 100. However, the
compiler will not make this assignment and, instead, issues a “possible loss of precision” error
because a byte value is smaller than an int value. To fix this problem, you can either type
cast the right-side data type down to match the left-side data type, or declare the variable on
the left side (num3) to be a larger data type, such as an int.

Java SE 8 Fundamentals 7 - 45
Matis Consulting SฺCฺ

Compiler Assumptions for


Integral and Floating Point Data Types
• Most operations result in an int or long:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– byte, char, and short values are automatically promoted


to int prior to an operation.
– If an expression contains a long, the entire expression is
promoted to long.
• If an expression contains a floating point, the entire
expression is promoted to a floating point.
• All literal floating point values are viewed as double.
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The Java technology Gcompiler
a l
bmakes certain assumptions when it evaluates expressions.
é
os nsthese
You must understand r
fe assumptions to make the appropriate type casts or other
a r J
accommodations. a
The next few slides give examples.
g - t r
Ed non

Java SE 8 Fundamentals 7 - 46
Matis Consulting SฺCฺ

Automatic Promotion

Example of potential problem:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

short a, b, c;
a = 1 ;
a and b are automatically promoted to integers.
b = 2 ;
c = a + b ; //compiler error

Example of potential solutions:


• Declare c as an int type in the original declaration:
s a
int c;
)ha
• Type cast the (a+b) result in the assignment line: m
i l ฺ co eฺ
ma Guid
c = (short)(a+b);
@ ntg
2
d tude4
d h
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é G an
In the following example,
r a bl occurs because two of the three operands (a and b) are
error
J s sfe
automaticallyopromoted from a short type to an int type before they are added. In the last
line, the
a r
values of
t r an
a b are converted to int types and the converted values are added to
and
g -
Edan int
give
non (c). However, this assignment is illegal and causes a compiler error.
short variable
result. Then the assignment operator (=) attempts to assign the int result to the

The code works if you do either of the following:


• Declare c as an int in the original declaration:
int c;
• Type cast the (a+b) result in the assignment line:
c = (short)(a+b);

Java SE 8 Fundamentals 7 - 47
Matis Consulting SฺCฺ

Using a long

1 public class Person {


Using the L to indicate a long
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2
3 public int ageYears = 32; will result in the compiler
4 recognizing the total result as
4 public void calculateAge() { a long.
5
6 int ageDays = ageYears * 365;
7 long ageSeconds = ageYears * 365 * 24L * 60 * 60;
8
9 System.out.println("You are " + ageDays + " days old.");
10 System.out.println("You are " + ageSeconds + " seconds old.");
11 s a
12 } // end of calculateAge method )ha
m
co eฺ
13 } // end of class
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The code example G
é r a bl from this section to calculate a person’s age in days and
uses principles

r J os inthe
seconds. Because
n s fe
ageSeconds variable is declared as a long, one of the literal values
used as
g a operands
- t r a the assigned expression must be initialized as a long value (‘L’) so that
Edcompiler
the
nonwill allow the assignment.

Java SE 8 Fundamentals 7 - 48
Matis Consulting SฺCฺ

Using Floating Points


Expressions are automatically promoted
Example of potential problem: to floating points.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

int num1 = 1 + 2 + 3 + 4.0; //compiler error


int num2 = (1 + 2 + 3 + 4) * 1.0; //compiler error

Example of potential solutions:


• Declare num1 and num2 as double types:
double num1 = 1 + 2 + 3 + 4.0; //10.0
s a
double num2 = (1 + 2 + 3 + 4) * 1.0; //10.0
)ha
c m
o ฺ
i l ฺ
• Type cast num1 and num2 as int types in the assignment
g ma Guiline: de
int num1 = (int)(1 + 2 + 3 + 4.0);
2 4 @ n//10 t
int num2 = (int)((1 + 2 + 3 + 4)h*d 1.0); e
ud //10
( e d S t
e z t h is
d
án use
Copyright © 2014, e
r n oaffiliates. All rights reserved.
Oracle and/or tits
H s e
r r ero licen
G ue a floating
If an expression contains b le point, the entire expression is promoted to a floating point.
sé sfer a
J o
r tran
g a
Ed non-

Java SE 8 Fundamentals 7 - 49
Matis Consulting SฺCฺ

Floating Point Data Types and Assignment

• Example of potential problem:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

float float1 = 27.9; //compiler error

• Example of potential solutions:


– The F notifies the compiler that 27.9 is a float value:
float float1 = 27.9F;
– 27.9 is cast to a float type:
float float1 = (float) 27.9;
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é G default
Just as integral types
r a btolint under some circumstances, values assigned to floating
r
floatatype.Jos adefault
point types always
n sfe to a double type, unless you specifically state that the value is a
g nthe
Edexample,
For o -trfollowing line causes a compiler error. Because 27.9 is assumed to be a
n
double type, a compiler error occurs because a double type value cannot fit into a float
variable.
float float1 = 27.9; //compiler error
Both of the following work correctly:
• The F notifies the compiler that 27.9 is a float value:
float float1 = 27.9F;
• 27.9 is cast to a float type:
float float1 = (float) 27.9;

Java SE 8 Fundamentals 7 - 50
Matis Consulting SฺCฺ

Quiz

Which statements are true?


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

a. There are eight primitive types built in to the Java


programming language.
b. byte, short, char, and long are the four integral
primitive data types in the Java programming language.
c. A boolean type variable holds true, false, and nil.
d. short Long = 10; is a valid statement that adheres to
the variable declaration and initialization syntax. a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
Answer: a, d
é G rab
J s
o nsfe
• a is correct.
r tra It should be byte, short, int, and long.
• dgbais incorrect.
n -
E• c isnincorrect
o because a boolean type variable holds only true and false.
• d is correct. long is a reserved keyword but Long is not.

Java SE 8 Fundamentals 7 - 51
Matis Consulting SฺCฺ

Exercise 7-3: Declare a Long, Float, and Char

In this exercise, you experiment with the data types introduced


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

in this lesson. You:


• Declare and initialize variables
• Cast one numeric type to another

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
• Open the Java
é GCoderConsole
a bl and access 07-ManipulateFormat > Exercise3.
• Follow
r J othes instructions
n s fe below the code editor to:
d ga- Declare
n - tra a long, using the L to indicate a long value. Make it a very large number
E no(in the billions).
- Declare and initialize a float and a char.
- Print the long variable with a suitable label.
- Assign the long to the int variable. Correct the syntax error by casting the long
as an int.
- Print the int variable. Note the change in value when you run it.
• If you need help, click the Solution link. To go back to your code, click the Exercise link
again. Any changes that you have made will have been saved.

Java SE 8 Fundamentals 7 - 52
Matis Consulting SฺCฺ

Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Describe the String class and use some of the methods


of the String class
• Use the JDK documentation to search for and learn how to
use a class
• Use the StringBuilder class to manipulate string data
• Create a constant by using the final keyword in the
variable declaration
• Describe how the Java compiler can use promotion or has
a
casting to interpret expressions and avoid a compilerom )
error
a ilฺc deฺ
g m Gui
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 7 - 53
Matis Consulting SฺCฺ

Play Time!

Play Basic Puzzle 8 before the lesson titled “Creating and


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Using Methods.”

Consider the following:


What happens when you rotate the blue wheel?
How else can you affect the rotation of bumpers?

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é G question
You will be asked these
r a bl in the lesson titled “Creating and Using Methods.”
r J os nsfe
d ga n-tra
E no

Java SE 8 Fundamentals 7 - 54
Matis Consulting SฺCฺ

Practice 7-1 Overview:


Manipulating Text
This practice covers the following topics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Searching for a particular player and printing out the last


name
• Reversing the player name so that the family name is
printed first

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 7 - 55
Matis Consulting SฺCฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
e rná to us
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no
Matis Consulting SฺCฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Creating and Using Methods

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no
Matis Consulting SฺCฺ

Objectives

After completing this lesson, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Instantiate a class and call a method on the object


• Describe the purpose of a constructor method
• Create a method that takes arguments and returns a value
• Access a static method from a different class
• Use a static method of the Integer class to convert a
string into an int
• Overload a method a
as )h
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 8 - 2
Matis Consulting SฺCฺ

Topics

• Using methods and constructors


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Method arguments and return values


• Using static methods and variables
• Understanding how arguments are passed to a method
• Overloading a method

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 8 - 3
Matis Consulting SฺCฺ

Basic Form of a Method

The void keyword indicates that Empty parentheses indicate that no


the method does not return a value. arguments are passed to the method.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1 public void display () {


2 System.out.println("Shirt description:" + description);
3 System.out.println("Color Code: " + colorCode);
4 System.out.println("Shirt price: " + price);
5 } // end of display method

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
This is an exampleG
é of a simple
r a blmethod that does not receive any arguments or return a value.
r J os nsfe
d ga n-tra
E no

Java SE 8 Fundamentals 8 - 4
Matis Consulting SฺCฺ

Calling a Method from a Different Class

1 public class ShoppingCart {


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2 public static void main (String[] args) {


3 Shirt myShirt = new Shirt();
4 myShirt.display();
5 }
6 }
Method
Dot operator
Reference variable

Output:
s a
Item description:-description required- )ha
c m
o ฺ
Color Code: U
i l ฺ
Item price: 0.0
g ma Guide
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
In the example in this
é bl
G slide,radisplay is called by typing the reference variable for the object,

r J os followed
the dot operator,
n s fe by the method to be called. The default values, as set in the Shirt
d ga n-tra
constructor, are displayed.
E no

Java SE 8 Fundamentals 8 - 5
Matis Consulting SฺCฺ

Caller and Worker Methods


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Caller

s a
)ha
m
co eฺ
Worker
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
In the previous example,G the a l
bShoppingCart class calls the display method on a Shirt
object from within é
s thesmain
oinvoking r
fe method. The main method is referred to as the calling method
becausea rit J
is n
a “calling” another method to do some work. Conversely, the display
or
g - t r
Ed isnoreferred
method n to as the worker method because it does some work for the main method.
When a calling method calls a worker method, the calling method stops execution until the
worker method is done. After the worker method has completed, program flow returns to the
point after the method invocation in the calling method.

Java SE 8 Fundamentals 8 - 6
Matis Consulting SฺCฺ

A Constructor Method

A constructor method is a special method that is invoked when


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

you create an object instance.


• It is called by using the new keyword.
• Its purpose is to instantiate an object of the class and store
the reference in the reference variable.
Constructor method
Shirt myShirt = new Shirt(); is called.

s a
• It has a unique method signature. )ha
m
co eฺ
i l ฺ
ma Guid
<modifier> ClassName()
@ ntg
2
d tude4
d h
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G using
A constructor is invoked
a l new keyword. Its job is to instantiate an object of the class
bthe
é
osa reference
and to provide r
fe to the new object. If you do not write your own constructor in a
r
class, Java
Jwill n s
a one for you. The constructor's name is the same as the class name.
provide
g a
d Shirt - t r
Ethe
In
n onexample above, the reference returned by the Shirt constructor is assigned to
the myShirt reference variable.

Java SE 8 Fundamentals 8 - 7
Matis Consulting SฺCฺ

Writing and Calling a Constructor


1 public static void main(String[] args){
2 Shirt myShirt = new Shirt();
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

3 }

1 public class Shirt {


2 //Fields
3 public String description;
4 public char colorCode;
5 public double price;
6
7 //Constructor
8 public Shirt(){
9 description = "--description required--";
10 colorCode = 'U'
a
has
11 price = 0.00;
12 }
)
13
l ฺ c om ฺ
14 //Methods
m ai ide
15
16
public void display(){
System.out.println("Shirt description:" + description);
@ g t Gu
17 System.out.println("Color Code: " + colorCode);
d 2 4 en
18 System.out.println("Shirt price: " + price);
d h t u d
( e i s S
ez e th
19 }…

n d
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The constructor is the
é a bl called when an object is instantiated. Its purpose is
G firstrmethod
r J osdefault
primarily to set
n s fe
values.

d ga n-tra
E no

Java SE 8 Fundamentals 8 - 8
Matis Consulting SฺCฺ

Calling a Method in the Same Class

1 public class Shirt {


2 public String description;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

3 public char colorCode;


4 public double price;
5
6 public Shirt(){
7 description = "--description required--";
8 colorCode = 'U'
9 price = 0.00;
10
11 display(); //Called normally
12 this.display(); //Called using the 'this' keyword
13 }
14
s a
15 public void display(){
)ha
16 System.out.println("Shirt description:" + description);
m
co eฺ
17 System.out.println("Color Code: " + colorCode);
i l ฺ
18
19 }
System.out.println("Shirt price: " + price);
g ma Guid
20 …
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Calling a method inGthe samebclass
a l is very straightforward. You can simply use the method
name without é
oasreference.r
fe This is the same as when accessing a field; you can simply use the
r J n s
ga n-tra
field name.
d
E nifoyou have local variables with similar names and you want to make it obvious that
However,
your code is accessing a field or method of the current object, you can use the this keyword
with dot notation. this is a reference to the current object.
In this example, the display method is called twice from the constructor.

Java SE 8 Fundamentals 8 - 9
Matis Consulting SฺCฺ

Topics

• Using constructors and methods


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Method arguments and return values


• Using static methods and variables
• Understanding how arguments are passed to a method
• Overloading a method

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 8 - 10
Matis Consulting SฺCฺ

Method Arguments and Parameters

• An argument is a value that is passed during a method call:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Calculator calc = new Calculator();


double denominator = 2.0
Arguments
calc.calculate(3, denominator); //should print 1.5

• A parameter is a variable defined in the method declaration:


3 2.0 a
public void calculate(int x, double y){
) has
System.out.println(x/y);
Parameters
l ฺ c om ฺ
}
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Note: A value passed G intorthe
a l
bmethod when it is called is called an argument, whereas a
variable thato é
issdefined finethe method declaration is called a method parameter.
In this a r J
example, t r
3 a ns2.0 are passed to be the values of x and y within the calculate
and
g
Ed non-
method.

Java SE 8 Fundamentals 8 - 11
Matis Consulting SฺCฺ

Method Parameter Examples

• Methods may have any number or type of parameters:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

public void calculate0(){


System.out.println("No parameters");
}

public void calculate1(int x){


System.out.println(x/2.0);
}

public void calculate2(int x, double y){ a


System.out.println(x/y); ) has
}
l ฺ c om ฺ
m ai ide
public void calculate3(int x, double y, int @ gz){ t Gu
d 2 4 en
System.out.println(x/y +z);
d h t u d
} ( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é G number
Methods can take any
r a blof parameters and use these values within the method code
block.
r J os nsfe
d ga n-tra
E no

Java SE 8 Fundamentals 8 - 12
Matis Consulting SฺCฺ

Method Return Types

• Variables can have values of many different types:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

long
int[]

• Method calls can also return values of many different types:


long
int[]
a
) has
• How to make a method return a value:
l ฺ c om ฺ
– Declare the method to be a non-void return type.
m ai ide
– Use the keyword return within a method, followed g by ta G u
value.
4 @
h d 2
u d en
( e d S t
ez e th i s
n d
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Variables may haveGvalues ofbmany
a l different types, including primitive data types, objects,
and arrays. os é fe r
r J n s
d ga methods
Likewise,
n - tramay return values of many different types, including primitive data types,
E and
objects, no arrays.
Note: Constructors are special. They cannot have a return type, not even void.

Java SE 8 Fundamentals 8 - 13
Matis Consulting SฺCฺ

Method Return Types Examples

• Methods must return data that matches their return type:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

public void printString(){


Void methods cannot
System.out.println("Hello");
return values in Java.
}

public String returnString(){


return("Hello");
}

public int sum(int x, int y){ a


return(x + y); ) has
}
l ฺ c om ฺ
m ai ide
public boolean isGreater(int x, int y){ @g G u
2 4 en t
return(x > y);
d h d t u d
} ( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Void methods and G
é r a bl should not have a return statement. Void methods are
constructors
incapable of o
J s safevalue in Java. The type of value a method returns must match the
returning
g a r
return type you
- t r an For instance, a boolean type method must return a boolean. A
declare.
Ed ntype
String onmethod must return a String.

Java SE 8 Fundamentals 8 - 14
Matis Consulting SฺCฺ

Method Return Animation

• The following code examples produce equivalent results:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

public static void main(String[] args){


int num1 = 1, num2 = 2;
int result = num1 + num2;
System.out.println(result);
}

public static void main(String[] args){


int num1 = 1, num2 = 2;
1 3 num2);
int result = sum(num1, 2 s a
System.out.println(result); )ha
} m
co eฺ
i l ฺ
g ma Guid
public static
int sum(intint1sum(int
x, int 2 y){
x, int y){
2 4 @ nt
return(x1 + 32 y);
d h d tude
}
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
In the top example,G num1 andbnum2
a l are added together. In the bottom example, this logic is
é
s method.
put into the sum r
feValues are passed to the sum method and added, with the resulting
r Jobeing
integeravalue a n s
passed back and assigned to the result variable.
g - t r
Ed non

Java SE 8 Fundamentals 8 - 15
Matis Consulting SฺCฺ

Passing Arguments and Returning Values

1 2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Value passed from Value received by


caller method to worker method
Object
worker method

method
1
2
3 1
4 2
5 3
6 4
7
a
) has
l ฺ c om ฺ
3 m ai ide
Value returned to @
g t Gu
caller methodd2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 8 - 16
Matis Consulting SฺCฺ

More Examples

1 public void setCustomerServices() {


Itemabout
parameter required
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2 String message ="Would you like to hear "


3 +"special deals in your area?";
4 if (cust.isNewCustomer()) {
5
6 cust.sendEmail(message);
7 }
8 }

1 public class Customer{


2 public boolean isNew;
3 a
4 public boolean isNewCustomer(){
Return a boolean ) has
om ฺ
5 return isNew;
6 } l ฺ c
7 public void sendEmail(String message){ m ai ide
8 // send email @ g t Gu
String argument required 4
9 }
h d 2
u d en
10 }
( e d S t
ez e th i s
n d
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G method,
Here you see a caller
a l
bsetCustomerServices, invoking worker methods in the
é
os nsfe
Customer class. r
r J
d a example
• gThe
n - traat the bottom of the slide shows the Customer class, which defines two
E methods:
no
- isNewCustomer is defined with a return value of type boolean, but it does not
define any input parameters.
- sendEmail is defined with an input parameter of type String, called message.
This method does not return a value.
• The example at top of the slide shows the setCustomerServices method in the
ShoppingCart class invoking the methods of a Customer object by using dot notation
(object_reference.method).
- In line 4, isNewCustomer is called on the cust object reference. Because the
method returns a boolean, the method invocation becomes a boolean
expression evaluated by the if statement.
- In line 6, sendEmail is called on the cust object reference, passing the message
string as an argument.

Java SE 8 Fundamentals 8 - 17
Matis Consulting SฺCฺ

Code Without Methods

1 public static void main(String[] args){


2 Shirt shirt01 = new Shirt();
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

3 Shirt shirt02 = new Shirt();


4 Shirt shirt03 = new Shirt();
5 Shirt shirt04 = new Shirt();
6
7 shirt01.description = "Sailor";
8 shirt01.colorCode = 'B';
9 shirt01.price = 30;
10
11 shirt02.description = "Sweatshirt";
12 shirt02.colorCode = 'G';
13 shirt02.price = 25;
14
s a
15 shirt03.description = "Skull Tee";
)ha
16 shirt03.colorCode = 'B';
m
co eฺ
17 shirt03.price = 15;
i l ฺ
18
19 shirt04.description = "Tropical"; g ma Guid
20 shirt04.colorCode = 'R';
2 4 @ nt
21 shirt04.price = 20;
d h d tude
22 }
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G rTo
Why are methods useful?
a l
banswer that question, take a look at this code without methods.
é
os ofnsthefeShirt object that you want to create, you need many more lines of
For every instance
r Jeach
code toaedit aobject. Methods can help this code be more efficient and less cumbersome
g
d with. - t r
to
Ework non

Java SE 8 Fundamentals 8 - 18
Matis Consulting SฺCฺ

Better Code with Methods

1 public static void main(String[] args){


2 Shirt shirt01 = new Shirt();
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

3 Shirt shirt02 = new Shirt();


4 Shirt shirt03 = new Shirt();
5 Shirt shirt04 = new Shirt();
6
7 shirt01.setFields("Sailor", 'B', 30);
8 shirt02.setFields("Sweatshirt", 'G', 25);
9 shirt03.setFields("Skull Tee", 'B', 15);
10 shirt04.setFields("Tropical", 'R', 20);
11 }

1 public class Shirt {


2 public String description;
s a
3 public char colorCode;
)ha
4 public double price;
m
co eฺ
5
i l ฺ
6
7
public void setFields(String desc, char color, double price){
this.description = desc; g ma Guid
8 this.colorCode = color;
2 4 @ nt
9 this.price = price;
d h d tude
10 }
z (e is S
11 …
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é G coding
With a little bit of extra
r a binl the Shirt class, we can create a method that sets all the
r J os This
appropriate fields.
n s e
freduces the amount of code needed in the main method to create and

d ga n-tra
edit Shirt objects.
E no

Java SE 8 Fundamentals 8 - 19
Matis Consulting SฺCฺ

Even Better Code with Methods

1 public static void main(String[] args){


2 Shirt shirt01 = new Shirt("Sailor", "Blue", 30);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

3 Shirt shirt02 = new Shirt("SweatShirt", "Green", 25);


4 Shirt shirt03 = new Shirt("Skull Tee", "Blue", 15);
5 Shirt shirt04 = new Shirt("Tropical", "Red", 20);
6 }

1 public class Shirt {


2 public String description;
3 public char colorCode;
4 public double price;
5
6 //Constructor
7 public Shirt(String desc, String color, double price){ a
8 setFields(desc, price);
) has
om ฺ
9 setColor(color);
10 }
l ฺ c
11 public void setColor (String theColor){
m ai ide
12 if (theColor.length() > 0)
@ g t Gu
13 colorCode = theColor.charAt(0);
d 2 4 en
14 }
d h t u d
15 }
( e i s S
16 }
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Taking advantage of Ga Shirt a l
bconstructor can further reduce the amount of code needed in
é
os nsfe
the main method. r
r J a
aissue -istrmaintenance.
Another
g Imagine if you wanted to change the constructor so that the
d
E passed n
color
no in is a String, but the instance variable, colorCode, remains a char type.
You could create a method setColor that receives a String as an argument and then
modifies it so that it sets colorCode correctly.
Remember, methods can call other methods (as shown by the call to setColor).

Java SE 8 Fundamentals 8 - 20
Matis Consulting SฺCฺ

Variable Scope
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Instance variable (field)


1 public class Shirt {
2 public String description;
3 public char colorCode;
4 public double price; Local variable
5
6 public void setColor (String theColor){
7 if (theColor.length() > 0)
Scope of
8 colorCode = theColor.charAt(0);
9 } theColor
10 }
11
s a
12 public String getColor(){ Not scope of) ha
13 return theColor; //Cannot find symbol
theColor
l ฺ c om ฺ
ai ide
14 }
15
16 } m
g t Gu
4 @
h d 2
u d en
( e d S t
ez e th i s
n d
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
This code illustrates
é Gthe scope
r a blof two different types of variables. Variables live in the block
where they are
r J osdefined.
n s feThis is called “scope.” The scope of a variable determines its
accessibility
g a and
- t r a
also how long you can count on its value to persist.
E• d ThencolorCode
on variable is an instance variable, usually called a field. It is a member of
the Shirt class. It is accessible from any code within this class. The value of fit is stored
only during the lifespan of an instance.
• theColor is a local variable. It is accessible only from within the setColor method.
The value of theColor is deleted from memory when the method ends. Another way of
saying this is that its scope is the setColor method.
• Regardless of whether a local variable is declared within a method, a loop (discussed
later), or an if statement, its scope is always the block within which it is declared.
• In the example above, the setColor method uses the charAt method of the String
object to extract the first character in the theColor String. It assigns it to the fit
instance variable, which is a char.
Note: Local variables are stored in short-term memory, called “the stack,” whereas instance
variables (fields) are stored in a longer-term area of memory called “the heap.”

Java SE 8 Fundamentals 8 - 21
Matis Consulting SฺCฺ

Advantages of Using Methods

Methods:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Are reusable
• Make programs shorter and more readable
• Make development and maintenance quicker
• Allow separate objects to communicate and to distribute
the work performed by the program

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 8 - 22
Matis Consulting SฺCฺ

Exercise 8-1: Declare a setColor Method

In this exercise you:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Declare a setColor method that takes a char as an


argument
• In the ShoppingCart class, call the setColor method
on item1
• Test the method with both a valid color and an invalid one

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
• Open the Java
é GCoderConsole
a bl and access Lessons > 08-Methods > Exercise1.
• Follow
r J othes instructions
n s fe below the code editor.
• gIfayou need- a click the Solution link. To go back to your code, click the Exercise link
trhelp,
d
E again. n
noAny changes that you have made will have been saved.

Java SE 8 Fundamentals 8 - 23
Matis Consulting SฺCฺ

Topics

• Using constructors and methods


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Method arguments and return values


• Using static methods and variables
• Understanding how arguments are passed to a method
• Overloading a method

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 8 - 24
Matis Consulting SฺCฺ

Java Puzzle Ball

Have you played through Basic Puzzle 8?


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Consider the following:


What happens when you rotate the blue wheel?
How else can you affect the rotation of bumpers?

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G that
These are the questions
a l were asked to think about before this lesson began. What
byou
conclusions odid é
s you reach? r
fe In this topic, some Java concepts and principles will be discussed
that can r J
help explaina n s
this behavior.
g a - t r
Ed non

Java SE 8 Fundamentals 8 - 25
Matis Consulting SฺCฺ

Java Puzzle Ball Debrief

• What happens when you rotate the blue wheel?


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

– The orientation of all blue bumpers change.


– All blue bumpers share the orientation property of the wheel.
• How else can you affect the rotation of bumpers?
– After the ball strikes a rotation wall, the rotation of an
individual bumper changes.

a
) has
Rotation wall
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 8 - 26
Matis Consulting SฺCฺ

Static Methods and Variables

The static modifier is applied to a method or variable.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

It means the method/variable:


• Belongs to the class and is shared by all objects of that
class
• Is not unique to an object instance
• Can be accessed without instantiating the class
Comparison:
• A static variable is shared by all objects in a class. s a
) ha
• An instance variable is unique to an individual object.om
a ilฺc deฺ
g m Gui
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
So far you learned G
é r a bl variables and methods by creating an object instance of the
how to access
s sorfemethod belongs to. The Java language allows you to declare a
class that theovariable
J
variable
a r
or method
t r n static. This means that you can access it without creating an object
aas
g -
Ed nofothe
instance n class. Sometimes these are referred to as class variables or class methods.

Java SE 8 Fundamentals 8 - 27
Matis Consulting SฺCฺ

Example: Setting the Size for a New Item

1 public class ItemSizes {


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2 static final String mSmall = “Men’s Small”;


3 static final String mMed = “Men’s Medium”;
4 }
Passing the static mMed variable
to the setSize method
Item item1 = new Item();
item1.setSize(ItemSizes.mMed);
a
1 public class Item {
) has
2 public String size;
l ฺ c om ฺ
3 public void setSize(String sizeArg){
m ai ide
4 this.size = sizeArg;
@ g t Gu
5 }
d 2 4 en
h u d
6 } ed St z ( is
d e t h
r n án use
Copyright © 2014, e
H oaffiliates. All rights reserved.
Oracle and/or tits
e
ero licen s
r r
e classleItemSizes contains two static variables of type String:
In the example above,G uthe b
s
mSmall andomMed. é These f e r a
are initialized to a description of a particular men’s size. These
valuesa r
canJbe used a n s
without instantiating
g - t r ItemSizes.
E• d Thencode
on snippet shown in the middle of the slide shows an Item object being
instantiated and then the setSize method of the Item object is invoked, passing in
ItemSizes.mMed as an argument.
• The code example at the bottom of the slide shows the Item class. It contains a
String field, size. The setSize method requires a String parameter to set the
size field.

Java SE 8 Fundamentals 8 - 28
Matis Consulting SฺCฺ

Creating and Accessing Static Members

• To create a static variable or method:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

static String mSmall;


static void setMSmall(String desc);
• To access a static variable or method:
‒ From another class
ItemSizes.mSmall;
ItemSizes.setMSmall("Men’s Small");
– From within the class s a
mSmall; )ha
m
co eฺ
setMSmall("Men’s Small");
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G thatraare
Variables and methods
é bl unique to an instance are referred to as instance variables or
r J os arenaccessed
methods. If they
s fe from an object of another class, you qualify the reference with
d g a -tra
the object reference (shirt01.size).
E• Whenn n
oaccessing a static variable or method from an object of a different class, you
qualify the reference with the class name as shown above:
ItemSizes.setMSmall("Men’s Small") or ItemSizes.mSmall
• If you are referencing the static variable or method from within the class, there is no
need to qualify it.
• The main method is an example of a static method. As you know, it is used as the entry
point to an application. Because the main method is static, the Java runtime can
implicitly invoke it on the class without first instantiating the class.

Java SE 8 Fundamentals 8 - 29
Matis Consulting SฺCฺ

When to Use Static Methods or Fields

• Performing the operation on an individual object or


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

associating the variable with a specific object type is not


important.
• Accessing the variable or method before instantiating an
object is important.
• The method or variable does not logically belong to an
object, but possibly belongs to a utility class, such as the
Math class, included in the Java API.
a
• Using constant values (such as Math.PI) has )
o m
a ilฺc deฺ
g m Gui
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 8 - 30
Matis Consulting SฺCฺ

Some Rules About Static Fields and Methods

• Instance methods can access static methods or fields.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Static methods cannot access instance methods or fields.


Why?

1 public class Item{


2 int itemID;
3 public Item(){
4 setId();
5 } s a
)ha
6 static int getID(){ m
7 // whose itemID?? i l ฺ co eฺ
8 } g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The code example G
é r a bl why a static method is not allowed to access an instance
above illustrates

r J os nsfe
method or field.
a -istran
• gitemID a instance variable. That means that each Item object has its own
d n
E (presumably)
no unique itemID. In this example, its value is set in the constructor.
• The getID method is static, so it can be invoked even if there are no Item objects
created.
Instance methods and fields are only available by referencing the individual object instance.

Java SE 8 Fundamentals 8 - 31
Matis Consulting SฺCฺ

Static Fields and Methods vs. Instance Fields and


Methods
Object (instance)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

public class Item{


static int staticItemID; referenced by item01.
int instanceItemID;
static int staticItemID;
static main(){
int instanceItemID;
Item item01 = new Item();
static main(){ ... }

1 staticItemId = 6;
showItemID(){

2 instanceItemID = 3
5 ...println(staticItemID);

3 showItemID();
6 ...println(instanceItemID);
a
4 item01.showItemID();
ha s
}
m )
}
i l ฺ co eฺ
ma Guid
showItemID(){
...println(staticItemId);
@ ntg
...println(instanceItemId);
Other 2 4
d tude
instances
}
d h
}
z (ofe Itemis S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The code example G
é
above shows
r a bl a more complex example of an Item class that has an
r J os instanceItemID
instance variable
n s fe and a static variable staticItemID. In its main
method,
g a it
- t r a
instantiates an object referenced by item01. Look at the six lines of code and see
Edexplanations
the
n on below for why some work and some do not.
1. staticItemID is a static variable, and referenced from within a static method, main,
so it does not need to access an instance.
2. instanceItemID is an instance variable, and referenced from within a static method,
main, so it cannot be accessed unless a reference points to the particular object whose
instance variable needs to be set.
3. showItemID() is a call to an instance method, and referenced from within a static
method, main, so it cannot be accessed without a reference.
4. item01.showItemID() is a call to an instance method, but in this case the reference
points to the particular object whose instance method needs to be called.
5. ...println(staticItemID) refers to a static variable, but it is referred to from an
instance. Instances can always access static variables.
6. ...println(instanceItemID refers to an instance variable, but it is referred to from
an instance. No object reference is given, so it accesses the instance variable on the
object itself.

Java SE 8 Fundamentals 8 - 32
Matis Consulting SฺCฺ

Static Methods and Variables in the Java API

Examples:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Some functionality of the Math class:


– Exponential
– Logarithmic
– Trigonometric
– Random
– Access to common mathematical constants, such as the
value PI (Math.PI)
a
• Some functionality of the System class: ) has
– Retrieving environment variables l ฺ c om ฺ
m ai ide
– Access to the standard input and output streams
@ g t Gu
– Exiting the current program (System.exit d 4
2 method) en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Certain Java class G
é r a bl as the System and the Math class, contain only static
libraries, such
J s sfe
methods andovariables. The System class contains utility methods for handling operating
a r
system–specific
t r a n
tasks. (They do not operate on an object instance.) For example, the
g
d on - method of the System class gets information about the computer that
E
getProperties()
n
you are using.
The Math class contains utility methods for math operations. Because these methods and
variables are static, you do not need to create a new object every time you want your program
to do some math.

Java SE 8 Fundamentals 8 - 33
Matis Consulting SฺCฺ

Examining Static Variables in the JDK Libraries


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

out is a static
field of System
and contains
and is an
object s a
reference to a )ha
m
co eฺ
PrintStream
i l ฺ
object.
g ma Guid
2 4 @ nt
d h d tude
System is a class in java.lang.
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The next few slidesG show how
a l might use the Java API documentation to find out more
byou
é
s sfe
about System.out.println().
omethods r As you will see, this is a little unusual, because the class
that has
a r J
the a n that you need to investigate is not System. Rather, it is the class that is
g - t r
Edtype nofothe
the n out field of the System object. Consider the following:
System is a class (in java.lang).
out is a static field of System. This is the reason that you reference it from the class name,
not from an object instance: System.out
out is a reference type that allows calling println() on the object type it references.
To find the documentation:
1. Go to System class and find the type of the out field.
2. Go to the documentation for that field.
3. Review the methods available.

Java SE 8 Fundamentals 8 - 34
Matis Consulting SฺCฺ

Using Static Variables and Methods:


System.out.println
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Some of the methods


of PrintStream

The field, out, on System is s a


)ha
of type PrintStream. m
i l ฺ co eฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The diagram showsG the Fieldb
a l
Summary for the class System. Here, you can see that there is
indeed a field é
s out,
ocalled r
feand it is of type PrintStream. By clicking PrintStream, you can
now see r J
the details n s
a that class and, if you scroll down to the Method Summary, you will find
for
g a - t r
Ed many
(among n other methods) the print method and the println method. The print
novery
method is similar to println, except that it does not create a new line after printing, like
println does.
Example:
println("Hello"); println("Hello") yields the following output:
Hello
Hello

print("Hello"); print("Hello"); yields the following output:


HelloHello

Java SE 8 Fundamentals 8 - 35
Matis Consulting SฺCฺ

More Static Fields and Methods in the Java API

Java provides wrapper classes for


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

each of the primitive data types.


• Boolean: Contains a single field
of type boolean
• Double: Contains a single field
of type double
• Integer: Contains a single field
of type int a
They also provide utility methods to ) has
work with the data. l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
A wrapper class is G
é a class with
r a blthe same name as one of the primitive data types. Wrapper
r J os nsfeto contain a single value of the primitive type.
classes are instantiated

d gaInteger
n - tramyInt = new Integer(10);
E arenovery useful classes because they provide methods to help you work with the
These
primitive values stored within.

Java SE 8 Fundamentals 8 - 36
Matis Consulting SฺCฺ

Converting Data Values

• Methods often need to convert an argument to a different


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

type.
• Most of the object classes in the JDK provide various
conversion methods.
Examples:
• Converting a String to an int
int myInt1 = Integer.parseInt(s_Num);
• Converting a String to a double a
a s
double myDbl = Double.parseDouble(s_Num);
m )h
• Converting a String to boolean i l ฺ co eฺ
boolean myBool = Boolean.valueOf(s_Bool); g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The examples show
é a bl
Gstaticrconversion methods for Integer, Double, and Boolean.

r J ossomensconversion
There are also fe methods for the object classes (Integer, Double, and so
a
g n-tr
on) that are not a
static. These methods are invoked on an object reference for one of these
d
E and
classes no convert the value of that specific object.

Java SE 8 Fundamentals 8 - 37
Matis Consulting SฺCฺ

Topics

• Using constructors and methods


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Method arguments and return values


• Using static methods and variables
• Understanding how arguments are passed to a method
• Overloading a method

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 8 - 38
Matis Consulting SฺCฺ

Passing an Object Reference

Thank you!
An object reference is similar to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

a house address. When it is


passed to a method:
• The object itself is not
passed 11
00
• The method can access the 11 2
object using the reference
• The method can act upon Paint my 1
house. s a
the object Here’s the )ha
101 m
address.
i l ฺ co eฺ
House myHouse = new House(); g ma Guid
2 4 @ nt
PainterMan.paint(myHouse);
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
An object referenceG l as the object. It simply provides a reference for access to
is not thebsame
a
é
os is similar
that object. This r
feto the way a house address provides directions for finding a
r J n s
d g a -tra
particular house.
In
n onabove, the house (call it myHouse) has an address (the myHouse reference) of
Ethe graphic
101. When the painter gets this address, he jots it down in his notebook (he makes a copy of
it). This enables the house painter to find the house and paint it.
When you send an object reference as an argument to a method, you are sending a copy of
the reference—not the object nor the actual reference.
The receiving method has the information it needs to act directly upon the object itself.

Java SE 8 Fundamentals 8 - 39
Matis Consulting SฺCฺ

What If There Is a New Object?

myHouse = new House();


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Hey! My house
2 Move to new wasn’t painted!
house.

11
00
11 3
Paint my house. 1
1 Here’s the 0
a
address. 2 s
)ha
101 m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
House myHouse = new House();
d h d tude
PainterMan.paint(myHouse);
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Suppose that the owner G ofrthe a l
bhouse moves to another house before the job is finished. Will
the painter be é
osable fe the owner’s new house in order to paint it? The object reference
to find
(myHouse) r J has a n
changed
s to point to a new house, but the notation in the painter’s notebook
g a - t r
drefers toonthe old house. If the owner expects the new house to be painted, he or she will
still
E n
be disappointed.

Java SE 8 Fundamentals 8 - 40
Matis Consulting SฺCฺ

A Shopping Cart Code Example


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1 public class ShoppingCart {


2 public static void main (String[] args) {
3 Shirt myShirt = new Shirt();
4 System.out.println("Shirt color: " + myShirt.colorCode);
5 changeShirtColor(myShirt, 'B');
6 System.out.println("Shirt color: " + myShirt.colorCode);
7 }
8 public static void changeShirtColor(Shirt theShirt, char color) {
9 theShirt.colorCode = color; }
10 }

theShirt is a new reference of type Shirt. s a


)ha
m
co eฺ
i l ฺ
Output:
g ma Guid
2 4 @ nt
Shirt color: U
Shirt color: B d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
G rathe
When a method is invoked,
é blvalues of the arguments are used to initialize the parameter
r J os thenbody
variables before
s feof the method is executed. This is true for both primitive types and
reference
g a types.
- t r a
(Objects are not passed to methods.)
d example
Ethe
In on shown in the slide, the reference myShirt is passed by value into the
n
changeShirtColor method. The reference, theShirt is assigned the value of the
myShirt reference (the address). They now both point to the same object, so the change to
the color made using theShirt is printed out by accessing myShirt.color.
Note: The call to the changeShirtColor method is made from the main method, which is
static. Remember that a static method can only access other static methods. The
changeShirtColor method is also static.

Java SE 8 Fundamentals 8 - 41
Matis Consulting SฺCฺ

Passing by Value
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Shirt myShirt = new Shirt();


changeShirtColor(myShirt, 'B');

0x034009
12 shirtID
myShirt 0x034009
15.99 price
B colorCode
a
theShirt 0x034009
) has
Before
l ฺ c om ฺ
m ai ide is
changeShirtColor()
u is U.
g tthisGvalue
invoked,
4 @
h d 2
u d en
( e d S t
ez e th i s
n d
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The diagram in theG
é
slide shows
r a bl how the value of the myShirt reference passed into the
r J os nsfemethod is used to initialize a new Shirt reference (in this case,
changeShirtColor()

d g a -traRemember that when a new Shirt is created, the colorCode is


called theShirt).
E ntoon“U”.
initialized

Java SE 8 Fundamentals 8 - 42
Matis Consulting SฺCฺ

Reassigning the Reference


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1 public class ShoppingCart {


2 public static void main (String[] args) {
3 Shirt myShirt = new Shirt();
4 System.out.println("Shirt color: " + myShirt.colorCode);
5 changeShirtColor(myShirt, 'B');
6 System.out.println("Shirt color: " + myShirt.colorCode);
7 }
9 public static void changeShirtColor(Shirt theShirt, char color) {
10 theShirt = new Shirt();
11 theShirt.colorCode = color;
12 }

s a
)ha
m
co eฺ
i l ฺ
Output:
g ma Guid
2 4 @ nt
Shirt color: U
Shirt color: U d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
Here is another example
é G with r a bal small change in the code of the changeShirtColor()
method. In this
r J osexample,
n s fethe reference value passed into the method is assigned to a new
shirt. The
g a reference
- t r a points to a different Shirt object than the myShirt reference does.
now
Edbefore,othen Shirt.color is changed to 'B'. The println method called on line 6 shows
As
the colornof the myShirt object still is 'U' (Unset). These references point to two different Shirt
objects.
This illustrates that the reference myShirt is indeed passed by value. Changes made to a
reference passed into a worker method (reassignment to a different object, for instance) do
not affect the references in the calling method.

Java SE 8 Fundamentals 8 - 43
Matis Consulting SฺCฺ

Passing by Value
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Shirt myShirt = new Shirt();


changeShirtColor(myShirt, 'B');

0x034009
12 shirtID
myShirt 0x034009
15.99 price
U colorCode

s a
0x99f311
) ha
12 shirtID
c m
o ฺ
i l ฺ
theShirt 0x99f311
15.99 price
g m a
u i de
B colorCode
2 4 @ nt G
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The diagram in theG
é slide shows
r a bl the situation that results from the code in the previous slide.
When myShirt
r J os is passed
n s fe into the changeShirtColor() method, a new reference
d g a theShirt,
variable,
n - tra is initialized with the value of myShirt. Initially, this reference points to
E objectnothat the myShirt reference points to. But after a new Shirt is assigned to
the
theShirt, any changes made using theShirt affect only this new Shirt object.

Java SE 8 Fundamentals 8 - 44
Matis Consulting SฺCฺ

Topics

• Using constructors and methods


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Method arguments and return values


• Using static methods and variables
• Understanding how arguments are passed to a method
• Overloading a method

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 8 - 45
Matis Consulting SฺCฺ

Method Overloading

Overloaded methods:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Have the same name


• Have different signatures
– The number of parameters
– The types of parameters
– The order of parameters
• May have different functionality or similar functionality
• Are widely used in the foundation classes s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
é G language,
In the Java programming
r a bl a class can contain several methods that have the same
r Jos aarguments
name but different
methodaoverloading. n sfeas you
Just
(so the method signature is different). This concept is called
can distinguish between two students named “Jim” in the
g
d classoby
same - t r
n calling them “Jim in the green shirt” and “Jim with the beeper,” you can
E n
distinguish between two methods by their name and arguments.

Java SE 8 Fundamentals 8 - 46
Matis Consulting SฺCฺ

Using Method Overloading


The method
signature
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

1 public final class Calculator {


2 The method type
3 public static int sum(int num1, int num2){
4 System.out.println("Method One");
5 return num1 + num2;
6 }
7
8 public static float sum(float num1, float num2) {
9 System.out.println("Method Two");
10 return num1 + num2; s a
11 } )ha
m
co eฺ
12 public static float sum(int num1, float num2) {
i l ฺ
13 System.out.println("Method Three");
g ma Guid
14 return num1 + numb2;
2 4 @ nt
15 }
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The example in theG
é
slide shows
r a bl three methods to add two numbers, such as two int types or
r J os With
two float types.
n s e overloading, you can create several methods with the same
fmethod
d g a -tra
name and different signatures.
onmethod accepts two int arguments and returns an int value. The second sum
E first nsum
The
method accepts two float arguments and returns a float value. The third sum method
accepts an int and a float as arguments and returns a float.
The callout shows the part of the method declaration that is called the method signature.
The method signature of a method is the unique combination of the method name and the
number, types, and order of its parameters. The method signature does not include the return
type. To invoke any of the sum methods, the compiler compares the method signature in your
method invocation against the method signatures in a class.

Java SE 8 Fundamentals 8 - 47
Matis Consulting SฺCฺ

Using Method Overloading

1 public class CalculatorTest {


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2
3 public static void main(String[] args) {
4
5 int totalOne = Calculator.sum(2, 3);
6 System.out.println("The total is " + totalOne);
7
8 float totalTwo = Calculator.sum(15.99F, 12.85F);
9 System.out.println(totalTwo);
10
a
11 float totalThree = Calculator.sum(2, 12.85F);
) has
12 System.out.println(totalThree);
l ฺ c om ฺ
13 }
m ai ide
14 }
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
The code example G
in the slide
a l a main method that invokes each of the previous sum
bhas
é
osCalculator
methods of the r
fe class.
r J n s
d ga n-tra
E no

Java SE 8 Fundamentals 8 - 48
Matis Consulting SฺCฺ

Method Overloading and the Java API


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Method Use
void println() Terminates the current line by writing the line
separator string

void println(boolean x) Prints a boolean value and then terminates the line

void println(char x) Prints a character and then terminates the line

void println(char[] x) Prints an array of characters and then terminates


the line

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
GJavarAPI
Many methods in the
é a blare overloaded, including the System.out.println
s in the
method. Theotable
J s feslide shows four variations of the println method.
r n
d ga n-tra
E no

Java SE 8 Fundamentals 8 - 49
Matis Consulting SฺCฺ

Exercise 8-2: Overload a setItemFields Method

In this exercise, you create an overloaded method in the Item


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

class:
• setItemFields with three parameters that returns void
• setItemFields with four parameters that returns an int
• Then you invoke these from ShoppingCart.

s a
)ha
m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
• Open the Java
é GCoderConsole
a bl and access 08-Methods > Exercise2.
• Follow
r J othes instructions
n s fe below the code editor.
• gIfayou need- a click the Solution link. To go back to your code, click the Exercise link
trhelp,
d
E again. n
noAny changes that you have made will have been saved.

Java SE 8 Fundamentals 8 - 50
Matis Consulting SฺCฺ

Quiz

Which method corresponds to the following method call?


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

myPerson.printValues(100, 147.7F, "lavender");


a. public void printValues (int i, float f)

b. public void printValues (i, float f, s)

c. public void printValues (int i, float f, String s)

d. a
has
public void printValues (float f, String s, int i)
)
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
Answer: c
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 8 - 51
Matis Consulting SฺCฺ

Summary

In this lesson, you should have learned how to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Add an argument to a method


• Instantiate a class and call a method
• Overload a method
• Work with static methods and variables
• Convert data values using Integer, Double, and
Boolean object types
a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 8 - 52
Matis Consulting SฺCฺ

Challenge Questions: Java Puzzle Ball

Which of the scenarios below reflect the behavior of:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• A static variable?
• An instance variable?

1. A single bumper rotates after being struck by the ball.

s a
2. Rotating the red wheel changes the orientation of all red
)ha
bumpers. m
co eฺ
i l ฺ
g ma Guid
2 4 @ nt
d h d tude
z (e is S
n d e e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u e rr e lic
When you have anG
é opportunity
r a blto play the game, see if you can answer these questions,
applying the o
J s sfe concepts that you learned in this lesson.
object-oriented
a
For some r t
possibler n
aanswers to these questions and more discussion, see “Appendix A: Java
d g n -
E Ball
Puzzle noChallenge Questions Answered.”

Java SE 8 Fundamentals 8 - 53
Matis Consulting SฺCฺ

Practice 8-1 Overview:


Using Methods
This practice covers the following topics:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Creating a static method, createTeams, to return an


array of teams
• Creating another static method, createGames, that
takes an array of teams and returns an array of games

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 8 - 54
Matis Consulting SฺCฺ

Practice 8-2 Overview:


Creating Game Data Randomly
This practice covers creating a method for playing a soccer
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

game that randomly creates Goal objects.

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 8 - 55
Matis Consulting SฺCฺ

Practice 8-3 Overview:


Creating Overloaded Methods
This practice covers overloading a method.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

a
) has
l ฺ c om ฺ
m ai ide
@ g t Gu
d 2 4 en
d h t u d
( e i s S
n d ez e th
Copyright © 2014, e
rná oaffiliates.
Oracle and/or tits
us All rights reserved.
e r o H ense
u err le lic
é G rab
J s
o nsfe
r
ga n-tra
d
E no

Java SE 8 Fundamentals 8 - 56

You might also like