Java SE 8 - Guía de Estudio Vol.1
Java SE 8 - Guía de Estudio Vol.1
Java SE 8 - Guía de Estudio Vol.1
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
Authors Copyright © 2014, 2015, 2016 Oracle and/or its affiliates. All rights reserved.
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
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ฺ
Summary 4-26
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
v
Matis Consulting SฺCฺ
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ฺ
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ฺ
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ฺ
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ฺ
x
Matis Consulting SฺCฺ
xi
Matis Consulting SฺCฺ
xii
Matis Consulting SฺCฺ
xiii
Matis Consulting SฺCฺ
xiv
Matis Consulting SฺCฺ
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ฺ
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ฺ
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ฺ
Java SE 8 Fundamentals 1 - 2
Matis Consulting SฺCฺ
Audience
Java SE 8 Fundamentals 1 - 3
Matis Consulting SฺCฺ
Course Objectives
Java SE 8 Fundamentals 1 - 4
Matis Consulting SฺCฺ
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ฺ
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ฺ
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 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 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ฺ
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ฺ
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
) 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
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ฺ
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
Java SE 8 Fundamentals 2 - 2
Matis Consulting SฺCฺ
Topics
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ฺ
Java SE 8 Fundamentals 2 - 4
Matis Consulting SฺCฺ
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ฺ
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
r J os nsfe
d ga n-tra
E no
Java SE 8 Fundamentals 2 - 7
Matis Consulting SฺCฺ
Topics
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ฺ
Some of the features that set Java apart from most other
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 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
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ฺ
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ฺ
Step 1
followed a paradigm called Procedural
Programming.
• These languages use a sequential 2 Step 2
Java SE 8 Fundamentals 2 - 12
Matis Consulting SฺCฺ
• 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
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ฺ
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ฺ
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ฺ
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
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ฺ
Java SE 8 Fundamentals 2 - 19
Matis Consulting SฺCฺ
Compiling a Program
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ฺ
2. Enter the following for the class file that contains the main
method:
• Syntax:
java <classname>
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ฺ
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
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
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
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ฺ
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
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
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
) 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
Java SE 8 Fundamentals 3 - 5
Matis Consulting SฺCฺ
Java Packages
Java SE 8 Fundamentals 3 - 6
Matis Consulting SฺCฺ
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ฺ
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ฺ
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ฺ
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ฺ
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ฺ
Java SE 8 Fundamentals 3 - 12
Matis Consulting SฺCฺ
Class name
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Java SE 8 Fundamentals 3 - 13
Matis Consulting SฺCฺ
• Syntax:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
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ฺ
Java SE 8 Fundamentals 3 - 15
Matis Consulting SฺCฺ
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
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
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
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ฺ
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
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
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ฺ
Java SE 8 Fundamentals 4 - 6
Matis Consulting SฺCฺ
Uses of Variables
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ฺ
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ฺ
• Syntax :
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
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
– 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ฺ
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ฺ
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
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ฺ
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ฺ
– –2,147,483,648
– 2,147,483,647
– Examples: 2, 1343387, 1_343_387
Java SE 8 Fundamentals 4 - 15
Matis Consulting SฺCฺ
• int variables:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
• 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ฺ
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ฺ
Java SE 8 Fundamentals 4 - 18
Matis Consulting SฺCฺ
age = age + 1;
or
count = count – 1;
Java SE 8 Fundamentals 4 - 19
Matis Consulting SฺCฺ
Operator Precedence
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ฺ
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ฺ
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
Java SE 8 Fundamentals 4 - 22
Matis Consulting SฺCฺ
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
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ฺ
Java SE 8 Fundamentals 4 - 25
Matis Consulting SฺCฺ
Summary
Java SE 8 Fundamentals 4 - 26
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
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
Topics
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
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.
boolean expression
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Boolean Expressions
Review:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Relational Operators
Examples
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.
Quiz
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
Topics
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
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.
Introduction to Arrays
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
Array Examples
27 12 82 70 54 1 30 34
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
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;
• Syntax:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
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.
• Examples:
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 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.
Quiz
Why does the following code not compile? Select all that apply.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Quiz
Topics
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
Loops
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.
break example:
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 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.
Quiz
Summary
Play Time!
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
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.
Tips
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
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ฺ
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
Java SE 8 Fundamentals 6 - 3
Matis Consulting SฺCฺ
Topics
Java SE 8 Fundamentals 6 - 4
Matis Consulting SฺCฺ
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ฺ
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ฺ
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
Java SE 8 Fundamentals 6 - 9
Matis Consulting SฺCฺ
• A class:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
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
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
Java SE 8 Fundamentals 6 - 12
Matis Consulting SฺCฺ
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ฺ
Java SE 8 Fundamentals 6 - 14
Matis Consulting SฺCฺ
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ฺ
In this exercise, you create the Item class and declare public
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 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
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
Java SE 8 Fundamentals 6 - 18
Matis Consulting SฺCฺ
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ฺ
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ฺ
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
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
Java SE 8 Fundamentals 6 - 23
Matis Consulting SฺCฺ
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ฺ
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ฺ
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ฺ
remote1 remote2
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ฺ
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ฺ
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ฺ
Reference type
Reference variable
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Java SE 8 Fundamentals 6 - 29
Matis Consulting SฺCฺ
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ฺ
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ฺ
Code fragment:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Java SE 8 Fundamentals 6 - 32
Matis Consulting SฺCฺ
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
Java SE 8 Fundamentals 6 - 34
Matis Consulting SฺCฺ
Java SE 8 Fundamentals 6 - 35
Matis Consulting SฺCฺ
Java SE 8 Fundamentals 6 - 36
Matis Consulting SฺCฺ
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ฺ
0 itemId
item 0x034009 0.0 price
U colorCode
( 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
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
Java SE 8 Fundamentals 6 - 40
Matis Consulting SฺCฺ
Topics
Java SE 8 Fundamentals 6 - 41
Matis Consulting SฺCฺ
Java IDEs
d ga n-tra
E no
Java SE 8 Fundamentals 6 - 42
Matis Consulting SฺCฺ
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ฺ
Java SE 8 Fundamentals 6 - 44
Matis Consulting SฺCฺ
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ฺ
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ฺ
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ฺ
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ฺ
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
Java SE 8 Fundamentals 6 - 50
Matis Consulting SฺCฺ
Soccer Application
Java SE 8 Fundamentals 6 - 51
Matis Consulting SฺCฺ
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ฺ
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
Java SE 8 Fundamentals 6 - 54
Matis Consulting SฺCฺ
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ฺ
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ฺ
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ฺ
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
Java SE 8 Fundamentals 7 - 2
Matis Consulting SฺCฺ
Topics
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
Java SE 8 Fundamentals 7 - 4
Matis Consulting SฺCฺ
Concatenating Strings
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
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ฺ
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
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ฺ
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ฺ
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
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 SE 8 Fundamentals 7 - 11
Matis Consulting SฺCฺ
Java SE 8 Fundamentals 7 - 12
Matis Consulting SฺCฺ
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ฺ
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ฺ
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
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:
• 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ฺ
•String concatenation
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
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ฺ
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ฺ
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
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ฺ
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ฺ
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
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ฺ
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ฺ
Java SE 8 Fundamentals 7 - 26
Matis Consulting SฺCฺ
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ฺ
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ฺ
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ฺ
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
Java SE 8 Fundamentals 7 - 31
Matis Consulting SฺCฺ
Quiz
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
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
Java SE 8 Fundamentals 7 - 34
Matis Consulting SฺCฺ
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ฺ
++ 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ฺ
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
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ฺ
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ฺ
Equation:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Java SE 8 Fundamentals 7 - 40
Matis Consulting SฺCฺ
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ฺ
Java SE 8 Fundamentals 7 - 42
Matis Consulting SฺCฺ
1 int myInt;
2 long myLong = 123987654321L;
3 myInt = (int) (myLong); // Number is "chopped“
4 // myInt is -566397263
Java SE 8 Fundamentals 7 - 43
Matis Consulting SฺCฺ
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ฺ
Java SE 8 Fundamentals 7 - 45
Matis Consulting SฺCฺ
Java SE 8 Fundamentals 7 - 46
Matis Consulting SฺCฺ
Automatic Promotion
short a, b, c;
a = 1 ;
a and b are automatically promoted to integers.
b = 2 ;
c = a + b ; //compiler error
Java SE 8 Fundamentals 7 - 47
Matis Consulting SฺCฺ
Using a long
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ฺ
Java SE 8 Fundamentals 7 - 49
Matis Consulting SฺCฺ
Java SE 8 Fundamentals 7 - 50
Matis Consulting SฺCฺ
Quiz
Java SE 8 Fundamentals 7 - 51
Matis Consulting SฺCฺ
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
Java SE 8 Fundamentals 7 - 53
Matis Consulting SฺCฺ
Play Time!
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 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ฺ
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ฺ
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
Java SE 8 Fundamentals 8 - 2
Matis Consulting SฺCฺ
Topics
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ฺ
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ฺ
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
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
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ฺ
3 }
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ฺ
Java SE 8 Fundamentals 8 - 9
Matis Consulting SฺCฺ
Topics
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ฺ
Java SE 8 Fundamentals 8 - 11
Matis Consulting SฺCฺ
Java SE 8 Fundamentals 8 - 12
Matis Consulting SฺCฺ
long
int[]
Java SE 8 Fundamentals 8 - 13
Matis Consulting SฺCฺ
Java SE 8 Fundamentals 8 - 14
Matis Consulting SฺCฺ
Java SE 8 Fundamentals 8 - 15
Matis Consulting SฺCฺ
1 2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
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
Java SE 8 Fundamentals 8 - 17
Matis Consulting SฺCฺ
Java SE 8 Fundamentals 8 - 18
Matis Consulting SฺCฺ
d ga n-tra
edit Shirt objects.
E no
Java SE 8 Fundamentals 8 - 19
Matis Consulting SฺCฺ
Java SE 8 Fundamentals 8 - 20
Matis Consulting SฺCฺ
Variable Scope
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Java SE 8 Fundamentals 8 - 21
Matis Consulting SฺCฺ
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ฺ
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
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ฺ
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ฺ
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ฺ
Java SE 8 Fundamentals 8 - 27
Matis Consulting SฺCฺ
Java SE 8 Fundamentals 8 - 28
Matis Consulting SฺCฺ
Java SE 8 Fundamentals 8 - 29
Matis Consulting SฺCฺ
Java SE 8 Fundamentals 8 - 30
Matis Consulting SฺCฺ
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ฺ
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ฺ
Examples:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Java SE 8 Fundamentals 8 - 33
Matis Consulting SฺCฺ
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ฺ
Java SE 8 Fundamentals 8 - 35
Matis Consulting SฺCฺ
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ฺ
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
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ฺ
Thank you!
An object reference is similar to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Java SE 8 Fundamentals 8 - 39
Matis Consulting SฺCฺ
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ฺ
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ฺ
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()
Java SE 8 Fundamentals 8 - 42
Matis Consulting SฺCฺ
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ฺ
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
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ฺ
Java SE 8 Fundamentals 8 - 46
Matis Consulting SฺCฺ
Java SE 8 Fundamentals 8 - 47
Matis Consulting SฺCฺ
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 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
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ฺ
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
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
Java SE 8 Fundamentals 8 - 52
Matis Consulting SฺCฺ
• A static variable?
• An instance variable?
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ฺ
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ฺ
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ฺ
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