Vous êtes sur la page 1sur 1360

Java Fundamentals

1-1
Introduction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Examine the course sections
State the goal of the course
Become familiar with Oracle iLearning
Explain the course map
Describe the software used in this course
Recognize the IDEs used in this course

JF 1-1
Introduction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Java Fundamentals Course Sections


Section 4:
Java Fundamentals

Section 0:
Resources

Section 5:
Program Structure

Section 1:
Introduction

Section 6:
Arrays and Exceptions

Section 2:
Alice 3
Section 3:
Greenfoot
Midterm
Exam
JF 1-1
Introduction

Section 7:
Java Classes
Final
Exam

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Course Goal
You will learn the basic elements of computer programming
and the Java programming language to start writing your own
Java programs.
By the end of this course you should be able to:
Create animations and games.
Demonstrate your knowledge of Java technology and the Java
programming language.
Use the Java programming language to create applications.
Integrate decision, looping, and other intermediate code to create
applications.

JF 1-1
Introduction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Oracle iLearning
Oracle iLearning is a learning management system used for
this course.
Your instructor will provide you with an Oracle iLearning
username and password.
You will use iLearning to access:
Curriculum
Quizzes
Exams

JF 1-1
Introduction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Course Materials in Oracle iLearning


Course Materials include:

Student Guides PDF slides with additional notes for each lesson
Practice Guides PDF document with practice activities
Project Guides* PDF document with project activities
Quizzes Online quiz for each lesson
Exams Online midterm and final exam for each course
Additional Resources Some lessons include additional materials as
needed

*Projects are not provided for every lesson

JF 1-1
Introduction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Course Map
The course map is located in Section 0 of the course
It is a lesson planning tool used to plan how you will complete
lessons in the amount of time you have available over a unit
or semester.
Lessons are designed in a modular way.
The course map provides a recommended duration of each
lesson.
The map is based upon 45 minute class duration, but can be
adapted to shorter or longer class timings.

JF 1-1
Introduction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Software
In this course you will use the following software:

Alice 3: A 3D environment for creating animations.


Greenfoot: An interactive 2D environment for creating games.
Eclipse: A popular environment for Java application development.
Internet Browsers: Internet Explorer or Mozilla Firefox.

Be sure to identify and remember the folder configuration


(where files are saved) for your classroom computer lab.

JF 1-1
Introduction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Integrated Development Environment


As a developer, you will use Alice, Greenfoot, and Eclipse,
which are Integrated Development Environment s (IDEs), to
create Java applications.
An Integrated Development Environment, referred to as simply IDE,
is a software programming tool used by computer programmers to
develop software applications. An IDE includes tools for writing,
editing, compiling, deploying and debugging programs.

JF 1-1
Introduction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Terminology
Key terms used in this lesson included:
Oracle iLearning
IDE

JF 1-1
Introduction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Summary
In this lesson, you should have learned how to:
State the goal of the course
Explain the course map
Describe the teaching format used in class
Become familiar with Oracle iLearning
Recognize the IDEs used in this course

JF 1-1
Introduction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Java Fundamentals

2-1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Identify scene components
Create and save a new project
Add an object to a scene
Communicate the value of saving multiple versions of a scene
Code a simple programming instruction
Use the copy and undo command
Understand the value of testing and debugging

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Initial Scene
An initial scene is the starting point of your animation. It has
three components:
A background template which provides the sky, ground, and light.
Non-moving scenery objects which provide the setting.
Moving objects which provide the action.

The initial scene is the first scene of an animation where you select
the background template and position the objects.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Initial Scene Components


Below are components of a room scene.
Furniture Items
are
scenery objects.

Room is a
template.

Bipeds are
acting objects.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Create a New Project


Launch Alice 3.
In the Welcome dialog box, select the Blank Slates tab.
Select a template, and click OK.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Save a Project


In the File menu, select Save As.
Select the location to save the project (i.e., computer, file
server, memory stick).
Enter the project name.
Click Save.
Save projects frequently to avoid losing your work.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Navigating Between Editors


Alice provides two different workspace editors, called
perspectives, that you will toggle between frequently as you
build your project. The two editors are:
Code editor (Edit Code perspective, shown on the left)
Scene editor (Setup Scene perspective, on the right)

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Navigating Between Editors


Switch between the two editors by using either the Edit Code
button or Setup Scene button.
You are in the Code editor when you see programming
instructions in the left window pane.
You are in the Scene editor when you see the gallery of
objects.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

The Default Editor


By default, Alice starts in the Code editor. Click the Setup
Scene button to switch to the Scene editor.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Add an Object to a Scene


In the Scene editor, add an object (instance of a class) to a
scene in one of two ways:
Drag an object from the gallery into the scene with your mouse,
complete the dialog box. Alice 3 adds the object where you placed it in
the scene.
Click the object, complete the dialog box, and let Alice 3 add the object
to the center of the scene.
In programming terms, a class is a blueprint used to build an object,
and an object is an instance of a class. After an object is added to a
scene, it is referred to as an instance of the object. You can add
many instances of the same object to a scene (multiple coral objects
in the water, for example). Each instance must have a unique name.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Add an Object to a Scene Display


Click the object once, or drag the object from the gallery into
the scene with your mouse.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Naming the Object


Review the name provided for the object. Modify the name,
or click OK to accept the name and add the instance to the
scene.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Scene Editor
In the Scene editor, you can:

Select objects from the gallery to add to the scene.


Position objects in the scene using the Handles palette.
Edit an object's properties using the Properties panel.
Access the Code editor to add programming statements.
Run the animation after the programming statements are added to the
Code editor.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Scene Editor Display


The Scene editor contains two panels:
Scene Setup at the top
Gallery at the bottom

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Gallery
The gallery is a collection of three-dimensional objects that
you can insert into the scene.
The gallery is organized using tabs.
To find objects, browse the gallery tabs or use the Search
Gallery feature to search by keyword.
Breadcrumb menus display as you select classes.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Gallery Tabs
The gallery has six tabs:
Tab

Function

Browse Gallery by Class


Hierarchy

Organizes objects by mobility.

Browse Gallery by Theme

Organizes objects by region and folklore


context.

Browse Gallery by Group

Organizes objects by categories.

Search Gallery

Allows an object search by name.

Shapes/Text

Organizes object shapes, 3D text, and the


billboard.

My Classes

Allows you to add external classes into


your project
JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Select a Class
The Class Hierarchy tab groups objects by mobility type
(biped, flyer, etc.).
A class contains the instructions that define the appearance and
movement of an object. All objects within a class have common
properties. The class provides instructions to Alice 3 for creating and
displaying the object when it is added to your scene.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Class Example
Classes can contain sub-classes. Consider the example below.
The Alice class is a sub-class of the Biped class. There are two
Alice sub-classes in the gallery.
Every Alice added to a scene inherits the properties that all
Biped objects have in common: two legs, moveable joints etc.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Save New Project Version


Save time by creating multiple versions of your project.
After objects are positioned in the initial scene, save multiple
versions of your project, giving each version a different name.
Benefits of saving multiple versions of projects:
Use the same scene to create different animations.
Save time re-creating the scene if you encounter programming errors.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Steps to Save a Project Version


With file open, select Save As...
Select the location to save the project (i.e., computer, file
server, memory stick).
Enter the project name.
Click Save.
Save projects frequently in case of a power failure or a
computer crash.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Code Editor
Click the Edit Code button to display the Code editor. The
Code editor is where you add the programming instructions
to program your animation.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Methods Panel
The Procedures tab, located within the Methods Panel in the
Code editor, displays pre-defined methods for the selected
instance, as well as methods defined for the class of objects.
A procedure is a piece of program
code that defines how the object
should execute a task. Alice 3 has a
set of procedures for each class;
however, users can create or
"declare" new procedures.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Instance Menu in Methods Panel


The instance menu displays above the Procedures tab. The
down pointing triangle on the right side of the menu indicates
that the menu drops down when selected.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Create a Programming Instruction


From the Methods Panel, click and drag the desired
programming instruction into the myFirstMethod tab of the
Code editor.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Select Values for Method Arguments


After you drag the programming instruction into the
myFirstMethod tab, use the cascading menus to select the
value for each argument used in the method.
An argument is a value that is used by the method to perform an
action.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Procedure Argument Types


Argument types may include:

Direction
Amount
Duration
Text

Alice 3 recognizes how many arguments are needed for each


programming instruction. It presents you with the correct
number of cascading menus to specify the values for each of
those arguments.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Copy Programming Instructions


To copy a programming instruction, you may use any one of
these methods:
The CTRL + Drag method copies the code.
Right-click and use the Copy to Clipboard option copies the code.
Click and dragging the programming instruction to the clipboard moves
the code.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Steps to Use the CTRL + Drag Method


Hold down the CTRL key on your keyboard.
Click on and hold the programming instruction handle.

Drag the handle to the desired location in the code, or to the


clipboard. Release the mouse button before releasing the
CTRL key.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Steps to Use the Right-Click Copy Method


Right-click on the programming instruction handle.
Select the Copy to Clipboard option.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Steps to Use the Click + Drag To Clipboard


Method
Click and drag the programming instruction to the clipboard
icon. The clipboard changes color when the mouse pointer
makes contact with the clipboard icon. Use this method when
moving programming instructions between tabs.

The clipboard can store multiple programming instructions at


the same time. They are dragged from the clipboard in the
opposite order that they were placed on it. The clipboard
displays the number of items stored on it.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Undo an Action
Undo an action using the Undo option on the Edit menu, or
the keyboard shortcut CTRL + Z.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Test and Debug Your Animation


Testing
Once you create the programming instructions for your
animation, you need to test your program.
To test your program, click the Run button.
Run the animation to test that it functions properly and
executes as planned and without error.
Test the animation frequently during development.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Test and Debug Your Animation


Testing the Limits of Your Program
Testing the limits of your program is an important part of the
process. For example, change the value of an argument in a
procedure to intentionally "break" the code proves the code
works under extreme conditions.
What happens if a number is very large? or negative?
Test the limits of the animation frequently during
development.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Test and Debug Your Animation


Debugging
Debugging your program refers to the cycle that involves:
testing your program, identifying errors or unintended
results, rewriting the code, and re-testing.
Software programs, such as animations, are tested by entering
unanticipated commands to try and "break" the code. When
something is broken or doesn't work as intended in a software
program, it is often referred to as a "bug". Debugging is the process
of finding bugs in a software program.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

35

Testing and Debugging Techniques


Use some of the following techniques as you program the
animation in Alice 3:
Adjust the arguments that specify the direction, distance, and duration
that objects move.
Adjust the mathematical expressions that manipulate the direction,
distance, and duration that objects move.
Refine or replace instructions in the code that do not work as intended.
Resolve errors created by the programmer.

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

36

Terminology
Key terms used in this lesson included:
Argument
Bug
Class
Code editor
Debugging
Gallery

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

37

Terminology
Key terms used in this lesson included:
Initial scene
Instance
Procedure
Scene editor
Template

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

38

Summary
In this lesson, you should have learned how to:
Identify scene components
Create and save a new project
Add an object to a scene
Communicate the value of saving multiple versions of a scene
Code a simple programming instruction
Use the copy and undo commands
Understand the value of testing and debugging

JFS2L1
Getting Started with Alice 3

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

39

Java Fundamentals

2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Open a saved version of a project
Add multiple objects to a scene
Describe the difference between precise positioning and
drag-and-drop (or imprecise) positioning
Use a one-shot procedure to precisely position an object in a
scene

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Edit properties of an object in the Scene editor
Describe three-dimensional positioning axes
Position the sub-parts of an object in the Scene editor

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Open an Existing Project


Saved Alice 3 project files can be opened and edited.
There are two ways to open an existing Alice 3 project file
after launching Alice 3:
Select the project from the My Projects tab.
Browse for the project using the File System tab.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Open an Existing Project Using the


My Projects Tab
Open Alice 3.
From the Select Project dialog box, select the My Projects tab.
Scroll to the name or thumbnail of the project to open.
Select the name or thumbnail of the project and click OK.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Open an Existing Project Using the


File System Tab
Open Alice 3.
From the Select Project dialog box, select the File System tab.
Select the Browse button.
Use the navigation window to navigate to the directory
structure on your computer where the Alice 3 file is located.
Note: Alice 3 cannot open animations created with previous versions of
Alice.

Click OK after the Alice 3 file has been selected.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Positioning Objects Within Initial Scene


Positioning objects within your initial scene includes choosing
the:

Direction the object should face.


Orientation of objects relative to other objects in the scene.
Position of objects in the scene.
Position of the object's sub-parts (arms, legs, etc.).

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Positioning Features of Objects


All Alice 3 objects share the same positioning features:
3D coordinates on x, y, and z axes.
A center point, where its own axes intersect (usually at the center of
mass).
Sub-parts that can move.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Orientation of Objects
Objects and their sub-parts move relative to their own
orientation, or sense of direction.
An object that is facing toward the back of the scene,
programmed to move forward 2 meters, moves 2 meters
further toward the back of the scene.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Ways to Position an Object


There are two ways to position an object:
Precise positioning using one of two methods:
Use a one-shot procedure.
Enter values for the x, y, and z coordinates and press the Enter key.

Imprecise positioning using the drag-and-drop method with your


cursor.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Select Instance to Position


There are two ways to select the instance that you want to
position. Rings or arrows surround the object once it is
selected.
Click the name of the instance from the object list in the
upper left corner of the scene window.
- OR Click the instance in the scene window.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

One-Shot Procedures Precise Positioning


One-shot procedures:
Are used to make scene adjustments and position objects.
Are not executed when the Run button is selected to play the
animation.
A procedure is a set of instructions, or programmed code, for how
the object should perform a task. One-shot procedures are
available in the Scene editor. They are the same as the procedures
in the Code editor; however, they only execute one time to reposition the object, unlike in the Code editor where they will
execute every time the Run button is clicked to play the animation.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Positioning Objects in the Scene Precise


Positioning
After adding multiple objects to the center of a scene, use
one-shot procedures to precisely place them in different
locations in the scene so that all objects are visible.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Steps to Open the One-Shot Procedures


Menu Precise Positioning
Right-click on an object in
the Scene editor.
Select procedures.
OR
Select the one shots
procedure menu in the
Properties panel.
Select procedures.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Steps to Use One-Shot Procedures


Precise Positioning
From the one-shots procedures menu, select the desired
procedure.
Specify the argument values (direction and distance).
The object will automatically re-position based on the
procedure selected and the arguments specified.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Positioning Example Precise Positioning


Sometimes it is convenient to have many instances positioned
in the center of the scene. For example:
If you want to add three playing card characters to the scene
you can add them to the center of the scene first.
Move them with one-shot procedures as opposed to trying to
drag-and-drop them into the correct location in the room.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Position Property Precise Positioning


The Position property tells you where the object is positioned
in the scene on the x, y, and z axes.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Steps to Position an Object Using


Coordinates Precise Positioning
In the Properties panel, locate the Position property.
Enter a value in the x axes and press enter.
Enter a value in the y axes and press enter.
Enter a value in the z axes and press enter.
The object will automatically re-position to the coordinates
entered in the x, y, and z axes fields. You must press the enter
key after entering each value.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Steps to Use the Drag and Drop Method


Imprecise Positioning
Select the object, or the sub-part of the object, using the
cursor.
Select a handle style. Each handle style presents rings or
arrows to assist you with your positioning. For example, the
Translation handle style will present three arrows to use in
positioning the object along the x, y, and z axes.
Position the object with your cursor by selecting and dragging
the rings that surround the object.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Types of Handle Styles Imprecise


Positioning
Handle Style

Description

Default

Simple rotation and movement.

Rotation

Rotate about the x, y, and z axes.

Translation

Move along the x, y, and z axes.


Change the size of the object and stretch it along the x, y,
and z axes.

Resize

Note: If you select a very large object in the scene, and then
select the Resize handle, the positioning arrow that helps you
resize the object may appear off of the screen. If this
happens, select the Resize handle and then use the scrolling
button on your mouse to resize the object.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Selected Object Properties Menu


The Selected Object Properties menu in the Scene editor
provides you with the ability to change the properties of the
instance that is currently selected in the scene.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Modifying Properties
Properties can be modified during scene setup and during
animation execution. For example:
Change the Opacity property of an instance to 0 during scene setup to
make it disappear.
Create a programming statement to set the Opacity property of the
instance to 1 so the instance reappears in the scene during execution
of the animation.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Steps to Change an Instance's Properties in


the Scene Editor
Select the instance in the Scene editor.
Change properties such as its paint (color), opacity, or size
using the menus in the properties panel
The triangle in front of the Selected Object Properties button
can hide or display the properties of an instance.
If the property fields for an instance are not displaying, click
the triangle to display them.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Positioning an Object's Sub-Parts


Use handle styles to position an object's sub-parts during
scene setup.
For example, you may want an object's head looking to the right when
the animation begins.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Steps to Position Object Sub-Parts


Select the instance from the object properties menu.
The right-pointing triangle next to the instance name
indicates that there are additional menus for the instance's
sub-parts.
Select the sub-part that you want to position.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Steps to Position Object Sub-Parts


Use the rings around the sub-part to position it.
Repeat these steps to position additional sub-parts.
Use the Undo feature when necessary.

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Terminology
Key terms used in this lesson included:
Orientation
One-shot procedure
Procedure
Properties

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Summary
In this lesson, you should have learned how to:
Open a saved version of a project
Add multiple objects to a scene
Describe the difference between precise positioning and
drag-and-drop (or imprecise) positioning
Use a one-shot procedure to precisely position an object in a
scene

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Summary
In this lesson, you should have learned how to:
Edit properties of an object in the Scene editor
Describe three-dimensional positioning axes
Position the sub-parts of an object in the Scene editor

JF 2-2
Add and Position Objects

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Java Fundamentals

2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Toggle between, and describe the visual differences between,
the Scene editor and the Code editor
Locate and describe the purpose of the methods panel and
the procedures tab
Use procedures to move objects
Add Java programming procedures to the Code editor

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Demonstrate how procedure values can be altered
Create programming comments
Reorder, edit, delete, copy, and disable programming
statements
Test and debug an animation

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Display the Code Editor


Click Edit Code (from the scene editor) to display the Code
editor.
The Code editor is where you program your animation.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Select Instance
First, select the instance that
you want to program.
This ensures that you are
creating a programming
instruction for the correct
instance.
Select an instance by clicking
on the instance in the small
scene window or by using
the instance pull down menu
below the small scene
window.
JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Methods Panel
The Methods Panel
contains two tabs:
Procedures: All pre-defined
procedures for an object.
Functions: All pre-defined
functions for an object.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Procedures Tab
The Procedures tab displays pre-defined procedures for the
selected instance, as well as procedures of your own that you
define.
A procedure is a piece of program
code that defines how the object
should execute a task. Alice 3 has a
set of procedures for each class;
however, users can create
("declare") new procedures.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Functions Tab
The Functions tab displays pre-defined functions for the
selected instance, as well as functions of your own that you
define.
A Function computes and answers a
question about an object, such as,
"What is its width or height?", or
"What is its distance from another
object?" Alice 3 has a set of
functions for each class; however,
users can declare new functions.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Code Editor Tabs


The Class Menu displays to the left of the Scene tab.
You create your programming instructions on the
myFirstMethod tab.
By default, Alice creates a Do In Order control statement in
the myFirstMethod procedure.
The area labeled drop statement here is the location onto
which you will place programming instructions.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Control Statements
At the bottom of the myFirstMethod tab you will find the
Alice 3 control statements.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Object Movement
Object movement is egocentric:
Objects move based on the direction they face.

An object can move in six directions:

Up
Down
Forward
Backward
Right
Left

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Examples of Movement Procedures


Procedure

Description

Move

Moves the object in any one of its six directions.

Move Toward

Moves the object toward another object.

Move Away From

Moves the object away from another object.

Move To

Moves the object from its current position to the center


point of the target object.

Move and Orient To

Moves the object from its current position to the center


point of the target object and adjusts the object's
orientation to match the orientation of the target object.

Delay

Halts an object's movement for a certain number of


seconds. Delay can be used to slow down the execution
of an animation.

Say

Creates a call-out bubble with text that makes the object


appear to talk.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Examples of Rotation Procedures


Procedure

Description

Turn

Rotates an object left, right, forward, or backward on its


center point. Left and right turn on the object's vertical axis;
forward and backward turn on the object's horizontal axis.

Roll

Rolls an object left or right on its center point using the


object's horizontal axis.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Create a Programming Instruction


From the Procedures tab, click and drag the desired
procedure into myFirstMethod in the Code editor.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Select and Set Argument Values


After the programming statement is created, use the dropdown menus to set the values for each argument. To access
the argument drop-down menu, click on the down-pointing
triangle to the right of the argument value.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Execute the Program


Click the Run button to execute the programming
instructions. Run the program frequently to test for the
desired results, and alter the values of the arguments as
necessary.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Arguments
Arguments are selected
after the procedure is
dropped onto the Code
editor.
Argument types may
include:

Object
Direction
Direction amount
Time duration
Text

An argument is a value that the procedure


uses to complete its task. A computer
program uses arguments to tell it how to
implement the procedure.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Argument Menu
The argument menu offers default argument values to select
from. If none of the defaults are suitable, select the Custom
DecimalNumber option so that you can specify a more
accurate argument value.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Steps to Edit Arguments


Next to the argument's value, click the arrow to display the
menu of values.
Select a new value.
Use the Custom DecimalNumber option to specify a value
that differs from the default list of values.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Arguments as Placeholders
When a procedure is dropped into the Code editor, all
argument values must be specified.
There will be times that you select an argument value as a
temporary placeholder value that will be replaced later.
For example, you may want an object to move forward but
you are not sure how far.
Select a placeholder value of 2 meters, run the animation,
determine that a different value is needed, and then edit the
value.
You can also specify a placeholder value that you will replace
later with a function or a variable.
JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Steps to Reorder Programming Statements


Use "Drag and Drop": Select the handle of the programming
statement.
Drag the programming statement to its new position.
Drop the programming statement into its new position by deselecting the handle.*

*Note: A green position indicator line will appear to help you


align the programming statement to the desired position.
JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Edit Programming Statements


Use the drop-down lists to edit the values of a programming
statement.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Delete Programming Statements


Right-click programming statements to remove parts of the
statement.

Or delete the entire statement

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Edit and Test the Program


Run the animation to test it, and edit the code as necessary.
It may take several cycles of testing and editing to get the
animation to run as desired.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Debugging and Testing


Debugging and Testing is the process of running the
animation many times, and adjusting the control statements,
procedures, and arguments after each execution.
Save often while debugging your program.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Insert Temporary Programming Statements


to Help with Debugging
You can insert temporary programming statements into your
code to help with debugging. For example: imagine that you
have an object that is not moving forward.
Temporarily enter a Say programming statement to announce
that the object is about to move forward.
Test the program to see whether or not the Say programming
statement executes.
If the Say statement executes, but the object does not move,
this indicates one type of problem; if both the Say and Move
statements do not execute, this may indicate another type of
problem.
JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Disabling Programming Statements


Programming statements can be disabled in the Code editor.
Disable programming statements to:
Help isolate portions of code during testing.
Help you focus on programming, testing, and debugging a specific
instruction.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Steps to Disable a Programming Statement


Right-click on the programming statement.
Unselect "Is Enabled" from the drop-down list.

The color of the programming statement will change to gray


hash marks to show that it is disabled.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Steps to Re-Enable a Disabled


Programming Statement
Right-click on the programming statement that has been
disabled.
Select "Is Enabled" from the drop-down list.

This re-enables the code and removes the grey lines.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Programming Comments
Including programming comments in an animation helps
humans understand the flow of the programming.
Comments:
Describe the intention of the programming instructions.
Do not affect the functionality of the program because they are ignored
during its execution.
Are typically placed above the block of programming statements that it
describes.
Are often written first, in large programs, as an outline of the
programming instructions.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Steps to Enter Comments in a Program


Drag and drop the comments tile above a code segment.
The comment tile is located at the bottom of the
myFirstMethod.
Type comments that describe the sequence of actions in the
code segment.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Using Comments to Organize Your Program


Comments can be an excellent tool for organizing the
development of a program.
For large programs, create a comment that indicates the end
of the program.
An "end of program" comment helps to minimize scrolling
when adding programming statements to a lengthy
myFirstMethod.

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Terminology
Key terms used in this lesson included:
Argument
Code editor
Comments
Functions
Methods panel
Orientation
Procedure

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Summary
In this lesson, you should have learned how to:
Toggle between, and describe the visual differences between,
the Scene editor and the Code editor
Locate and describe the purpose of the methods panel and
the procedures tab
Use procedures to move objects
Add Java programming procedures to the Code editor

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

35

Summary
In this lesson, you should have learned how to:
Demonstrate how procedure values can be altered
Create programming comments
Reorder, edit, delete, copy, and disable programming
statements
Test and debug an animation

JF 2-3
Procedures and Arguments

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

36

Java Fundamentals

2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Correlate storyboard statements with program execution
tasks
Add a control statement to the Code editor
Use random numbers to randomize motion

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Program Development Using a Top-Down


Approach
Just as a homebuilder uses a set of blueprints and follows a
series of steps, a programmer uses a plan and follows a series
of steps to build a program.
Homebuilders work with a purpose and set specific goals as
they buildthe rooms are energy efficient, the home meets
building codes, etc.
Programmer's also work with a purpose and set goals,
because without them, success cannot be measured.
Another term for the goal or purpose of an animation is a
high-level scenarioa story with a purpose.
JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Use a Top-Down Approach to


Programming
Define the high-level scenario (the purpose/goal of the
program).
Document the actions step-by-step in a textual storyboard.
This helps to gain a thorough understanding of the actions
that need to be programmed.
Create a table to align the storyboard steps to the
programming instructions.
Review the table during the animation's development to
ensure the animation meets specifications.
Revise the table as necessary.
JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Textual Storyboard Example


Program the following actions in order:

Bunny walks in.


Alice turns to look at the Bunny.
Bunny says, "Is this the party!"
Alice says, "Oh no!"
Bunny turns to left.
Program the following actions together:
Bunny walks away quickly.
Alice shakes her head.

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Align Storyboard to Programming


Instructions
Order of
Instructions
Do in order

Do together

Storyboard Action

Programming Instructions

Bunny walks in.

Bunny moves forward 2 meters.

Alice turns to look at the


Bunny.

Alice turns to face the bunny.

Bunny says, "Is this the


party!"

Bunny says "Is this the party!"

Alice says, "Oh no!"

Alice says, "Oh no!"

Bunny turns to left.

Bunny turns left 0.25.

Bunny walks away quickly.


Alice shakes her head.

Bunny moves forward 4meters in 1


second.
Alice turns her head left right and left
again.

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Object Movement
Object movement is egocentric:
Objects move based on the direction they face.

An object can move in six directions:

Up
Down
Forward
Backward
Right
Left

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Examples of Rotation Procedures


Procedure

Description

Turn

Rotates an object left, right, forward, or backward on its


center point. Left and right turn on the object's vertical axis;
forward and backward turn on the object's horizontal axis.

Roll

Rolls an object left or right on its center point using the


object's horizontal axis.

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Comparison of Turn and Roll Procedures


The object turning left and right on its
center point using a vertical axis.

The object rolling left and right on its


center point using a horizontal axis.

The object turning forward on its


center point using a horizontal axis.

The object turning backwards on its


center point using a horizontal axis.

(The card was already


facing left. Turning
forward caused it to lean
forward)
JF 2-4
Rotation and Randomization

(The card was facing left.


Turning backward caused
it to lean backward)

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Sub-Part Rotation Example


Some objects have moveable sub-parts that can turn and roll.
The pocket watch has moveable hour and minute hands that
can roll on the clock's center point.
The key to successful rotation is knowing the center point of
an object.

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Steps to Program an Object to Rotate


Select the instance of the object
to rotate.
Drag a turn or roll procedure to
the Code editor.
Set the direction argument.
Set the amount argument (1.0 =
one full turn or roll).
*Note: A green position indicator
line will appear to help you align
the programming statement in the
desired position.
JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Sub-Part Rotation
Some objects have moveable sub-parts.
For example, the clock's hands can turn or roll.
Rotation can be applied to an entire object, or select subparts of the object.
An object's sub-part displays rings that show its range of
motion.

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Steps to Program an Object's Sub-Part to


Rotate
Select the instance of the object sub-part to rotate.
Drag a turn or roll procedure to the Code editor.

Select the direction value for the direction argument.


Select a rotation value for the amount argument
(1.0 = one full turn or roll).
JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Control Statements
Control statements define how programming statements are
executed in the program.
myFirstMethod is created with a default Do in order control
statement. Within it, all programming statements execute
sequentially by default.
Procedure

Description

Do in order

Execute the statements contained within the control statement in


sequential order.

Do together

Execute the statements contained within the control statement


simultaneously.

Count

Execute the statements contained within the control statement a


specific number of times.

While

Execute the statements contained within the control statement


while a specified condition is true.
JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Control Statements in the Code Editor


Control statements
are located at the
bottom of the Code
editor.
They represent blocks
of code into which
individual statements
are grouped.
Drag control tiles into
the Code editor, and
then add statements
to them.
JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Add Procedures to a Control Statement


Drag new or existing programming statements into the
Control statement.
In the example illustrated below, the Alice object will move
forward, turn left, and roll to the right in order.

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Tip: Create Programming Blocks


Even though myFirstMethod contains a default Do in order
control statement, you can always add other Do in order tiles
to the programming area.
This allows you to keep your programming instructions
together in organized blocks.
Blocks can be easily copied to the clipboard or moved around
in a large program.
Nested Do in order control statements do not impact the
performance of the animation; they make program-editing
easier for the programmer.

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Nested Do In Order Control Statements


Here, three Do in order
statements and a do
together statement are
nested inside a fourth Do
in order statement.
Nested statements add
visual structure to a
program, much like an
outline brings structure to
a report.

JF 2-4
Rotation and Randomization

Nesting is the process of putting


one thing inside of another, like
eggs lying next to each other in a
nest.
Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Random Numbers
Random numbers are numbers generated by the computer
with no predictable pattern to their sequence.
Random numbers are generated within a given range of
numbers.
Computers may require random numbers for:
Security: for example, randomly generated passwords.
Simulation: for example, earth science modeling
(i.e., erosion over time).

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Examples of Random Numbers


Random numbers can be generated within a wide range of
numbers, both positive and negative, and may include whole
numbers and fractional parts of a number.
Examples of random numbers:

15674
-6934022
0.371
-89.763

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Random Numbers in Animations


Animals do not move in straight geometric lines.
They change direction slightly as they walk, swim, and fly.
Random numbers may be utilized in the distance argument of
a method so that the object moves in a less predictable, more
life-like manner.
Random numbers are often used when creating games that
require unpredictable behavior.

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Steps to Use Random Numbers


For any numerical argument, one of the options is a random
number. Select the argument from the drop-down list.
Select Random.
Select nextRandomRealNumberInRange.
Select the low and high values.
Run the animation. Alice 3 will randomly generate a value
within the selected range when the statement is executed.

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Random Number Animation Example


The bunny moves forward a random distance moving up and
down before turning towards Alice at run-time.

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Terminology
Key terms used in this lesson included:
Control statements
Nesting
Random numbers
Textual storyboard

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Summary
In this lesson, you should have learned how to:
Correlate storyboard statements with program execution
tasks
Add a control statement to the Code editor
Use random numbers to randomize motion

JF 2-4
Rotation and Randomization

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Java Fundamentals

2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Compare and define an animation and a scenario
Write a storyboard
Flowchart a storyboard
Describe inheritance and how traits are passed from
superclasses to subclasses

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Describe when to implement procedural abstraction
Demonstrate how to declare a procedure
Identify and use procedural abstraction techniques to simplify
animation development

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Object Movement
Professional animators begin their process by developing a
scenarioor storythat gives the animation a purpose.
Examples:

A story representing a conflict and resolution.


A lesson to teach a math concept.
A process to simulate or demonstrate.
A game to play for entertainment or training.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Scenario and Animation Examples


Defining the scenario, and the animation to represent the
scenario, is the first step to programming your animation.
Scenario Type

Scenario

Animation

Story

A cat needs help to get


down from a tree.

A firefighter climbs up the tree to


save the cat.

Lesson

Memorizing chemistry
symbols is difficult.

A timed game matches chemistry


symbols with their definitions.

Process

A car has a flat tire.

A demonstration shows how to


change a tire on a virtual car.

Game

An airplane must avoid


objects in its path as it
flies through the sky.

An interactive game maneuvers an


airplane around objects in the sky.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

What is a Storyboard?
A storyboard identifies the design specifications for the
animation scenario:
How objects appear, move, speak, interact, and so on.

Once a scenario is defined, you can begin to develop the


animation storyboard.
Two types of storyboards are used to plan an animation:
Visual: A series of illustrated images that represent the main scenes of
the animation.
Textual: A detailed, ordered list of actions that each object performs in
each scene of the animation.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Storyboard Formats
Storyboards are created in the following formats:
Drawn with paper and pencil.
Created using digital tools such as a word processing program, paint or
drawing program, or presentation.
Created using comments in the Alice 3 Code editor.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Visual Storyboards
A visual storyboard helps the reader understand:

The components of a scene.


How the initial scene will be set-up.
The moving and non-moving objects in a scene.
The actions that will take place.
The user interactions that will occur during the animation execution.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Visual Storyboard Example

Boy and girl sit on a park


bench. The boy walks
away, leaving his phone
behind.

Girl notices the mobile


phone. She thinks, "Hey!
That boy forgot his
phone!"

JF 2-5
Declare Procedures

Girl says out loud "Hey!


You forgot your phone!"
Boy turns around and
walks back to bench. He
says, "Oh! thank you!"

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Textual Storyboards
A textual storyboard helps the reader understand the actions
that will take place during the animation.
The moving and non-moving objects can be easily identified
within the action statements, but a more detailed description
may be necessary if additional programmers are also involved
in implementing any scene.
An algorithm is a list of actions to perform a task or solve a problem.
In computing, a textual storyboard is an algorithm.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Textual Storyboard Example 1


Program the following actions in order:
Boy and girl sit on a park bench.
Boy stands up and walks away, leaving his mobile phone on the park
bench.
Girl turns to look at the phone.
Girl thinks, "Hey! That boy forgot his phone!"
Girl says out loud, "Hey! You forgot your phone!"
Boy stops and turns around.
Boy walks back to the park bench and says, "Oh! Thank you!"

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Textual Storyboard Example 2


This example shows how you can develop your storyboard by
first writing comments in the Code editor of your program.
Afterwards, you can start to develop the animation directly
from the storyboard.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Textual Storyboard Components


Component

Definition

Scene

The place (or "world" in Alice 3) Park, library, school,


where your story occurs.
home

Objects

Moving or non-moving
characters that you program to
move and act.

Animals, cars, people,


trees

Actions

Instructions for how each


object should act in the scene.

Walk 2 meters, turn left,


say "Hello!"

User Interactions

Ways in which the user viewing Keyboard commands or


the animation can manipulate
mouse clicks to make
objects move
the objects in the animation.

Design Specifications

How the objects and scenery


should look in the animation.
JF 2-5
Declare Procedures

Examples

Size, position, location,


color

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Flowcharting a Storyboard
Flowcharting a storyboard helps you organize the flow of the
animation actions and conditions.
True

Boy leaves
phone on
bench

False

Girl says "Hey you


forgot phone"

Girl does nothing

Boy stops, turns


around, comes back
to bench, says
"Thank you"

Boy keeps
walking
End

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Using Storyboards to Organize Your


Program
Textual storyboards can be used to generate program
comment statements and organize program development.
Storyboards can also help programmers identify repetitive
actions for one object, and identical actions that may be
performed by multiple objects.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Inherited Characteristics
Let's examine how a Dalmatian inherits its characteristics:
Characteristics of the Dog class (the parent class or
"superclass") include four legs, two eyes, fur, and the ability
to bark.
Characteristics of the Dalmatian breed class (the child class or
"subclass," which is a subset of the dog class) include white
fur, black spots, and other characteristics.
Dog Class (Superclass)
Dalmatian Class
(Subclass)
JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Class Inheritance
Just like animals in the real world, objects in the programming
world inherit the characteristics of their class, including all of
the class's methods (procedures and functions).
For example, all objects within the quadruped class in Alice
inherit the quadruped characteristics of four legs, a head, a
body, etc.
Within this quadruped superclass, subclasses exist for dogs,
cats, wolves, lions, cows, etc.
Each subclass adds characteristics that more specifically
identify the objects within it.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Identifying Repetitive Behaviors in Your


Storyboard
Understanding that subclasses belong to superclasses helps
you, as a programmer, identify repetitive behaviors in your
storyboard.
For example:
If you plan to program a dog, cat, and lion to walk, you should program
the repetitive behavior of walking at the superclass, or quadruped,
level.
The result is that all of the subclasses (dog, cat, lion) can use the
inherited characteristic of walking, and you do not have to program the
repetitive walking behavior for each object individually.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Inheritance
When a Dalmatian object is created, it inherits procedures,
functions, and properties from the quadruped class and the
Dalmatian subclass that you can view in the Code editor.

Inheritance means that each


subclass object inherits the
methods and properties of its
superclass.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Create Inherited Methods


In addition to the pre-defined methods, you can create your
own methods and have them display, or be available for, any
subclass object.
Inherited methods will always display at the top of the list of
pre-defined methods once they are created.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

myFirstMethod Tab
The myFirstMethod tab is displayed by default when the Code
editor is opened.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Class Hierarchy
Click the class hierarchy drop-down menu to the left of the
myFirstMethod tab (indicated by a down-pointing arrow) to
view the list of classes and subclasses in your animation.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

View the Class Methods


Select a superclass or subclass to view the procedures,
functions, and properties defined for the selected class.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Procedural Abstraction
Review the existing code or the textual storyboard to identify
and plan the methods that you need to declare in your
program.
Procedural abstraction may need to be implemented if an
object in Alice needs to perform an action, but there isn't an
inherited procedure that accomplishes that action.
Identify a repetitive behavior and create one method for it:
Simplifies the code, making it easier to read.
Allows many objects of a class to use the same method.
Allows subclasses of a superclass to use the method.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Procedural Abstraction Defined


An example of procedural abstraction is the removal of a
repetitive or lengthy programming statement from
myFirstMethod and the placing of it into its own method to
make the code easier to read, understand, and reuse by
multiple objects and multiple classes.
Procedural abstraction is the process of looking at programming code,
identifying repetitive programming statements, and extracting them
into their own methods, thus making the code easier to understand
and reuse.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Procedural Abstraction Example 1


One or more objects may perform the same repetitive
motions.
The animating of one swimming fish requires the writing of
many repetitive procedures which must then be repeated for
each fish in the school,
taking up a lot of space
in myFirstMethod.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Procedural Abstraction Example 2


Sometimes, a procedure needed to perform an action is not
available by default.
For example, a bird needs to fly, but a fly procedure is not
available for bird objects.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

When Procedural Abstraction Occurs


Procedural abstraction can occur before or after
programming statements are created.
However, by developing the storyboard first, the programmer
can more easily identify the procedures that will be needed
before the programming begins.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Examples of When to Declare a Procedure


Declare a procedure when:
Motions do not have a default procedure, such as a bird flying.
Motions need to be used by multiple objects or classes, such as all
quadrupeds hopping up and down.
Singular motions require many programming statements, such as a
person moving body parts to walk.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Declaring a Procedure Example 1


The bird flies by, turning its shoulders and moving forward
simultaneously. This repetitive motion can be extracted into
its own flying procedure.
Do together:

Do together:

Bird turns right shoulder backward


Bird turns left shoulder backward
Bird moves forward

Bird flies
Bird moves forward

Do together:
Bird turns right shoulder forward
Bird turns left shoulder forward
Bird moves forward
JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Declaring a Procedure Example 2


Each bunny moves up and down in order to simulate a
hopping motion.
This repetitive motion used by all bunny objects could be
extracted into its own hop procedure.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Steps to Declare a Procedure


From the class hierarchy, select the class that should inherit
the procedure.
All subclasses will then inherit the procedure as well. (These
are indented underneath their superclass.)
Click the Add Procedure... button.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Steps to Declare a Procedure


Specify a name for the procedure and then click OK.
A new tab with the name of the procedure will open.
Write the code for the procedure.
Add the new procedure to myFirstMethod right away so
that when you test the animation in myFirstMethod, you
are also testing the animation in the new procedure.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Steps to Add Procedure to myFirstMethod


Tab Before Programming
Click the myFirstMethod tab.
Select the instance for which you are coding the procedure
from the instance menu.
In the Procedures tab, locate the
declared procedure and drag it
into myFirstMethod.
Go back to the procedure by clicking the tab at the top of the
Code editor with the procedure's name.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

35

Steps to Add a Declared Procedure to Your


Code
Select the instance of the object to which you wish to add the
declared procedure.
Find the declared procedure listed under the Procedures tab
in the methods panel.
The declared procedures
are available in the
procedures tab for all
objects that inherit them.
Drag the declared
procedure to the code.
JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

36

Steps to Access and Edit Declared


Procedures
In the instance menu, select the instance where the
procedure was declared.
Click Edit to the left of the procedure name.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

37

Steps to Access and Edit Declared


Procedures
Create or edit the programming instructions for the
procedure.
Click the Run button to test the procedure and debug as
necessary.
When finished editing the procedure, click the
myFirstMethod tab to return.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

38

Identify Opportunities for Declared


Procedures
As you program, continually identify opportunities to declare
procedures using procedural abstraction techniques.
For example, in myFirstMethod, the fish bobs up and down
repeatedly.
A separate "bob" procedure should be declared as a result.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

39

Procedural Abstraction and Using the


Clipboard
After you have written many programming instructions in the
myFirstMethod tab, you may determine that the code would
serve your program better if it were in a declared procedure.
To save time, you can drag the programming instructions onto
the clipboard icon.
Then, after creating the declared procedure, you can drag the
programming instructions from the clipboard into the
declared procedure.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

40

Use Inherited Procedures


Procedures declared at the
superclass level are available
to the other objects in that
class.
For example, a "bipedWave"
procedure created to make a
playingCard wave his arms in
the air could be used to make
Alice wave her arms in the air
as well.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

41

Declare Procedure at Superclass Level


Declare the "bipedWave" procedure at the biped superclass
level so that the playingCards and Alice can both use the
procedure.
Any other bipeds that may be added later would also have
access to this procedure.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

42

this Object Identifier


When a declared procedure is created, the object identifier,
this, is used to indicate that the instance calling the
procedure is this.

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

43

this Object Identifier Example


If Alice is selected in the instance menu, then the bipedWave
procedure is added to myFirstMethod; this in the declared
procedure refers to Alice.

If the playingCard is selected in the instance menu, then the


bipedWave procedure is added to myFirstMethod, this in the
declared procedure now refers to the playingCard.
In essence, this always refers to the instance of the class that
is calling the procedure.
JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

44

Terminology
Key terms used in this lesson included:
Algorithm
Declared procedures
Inheritance
Procedural abstraction
Scenario
Storyboard

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

45

Summary
In this lesson, you should have learned how to:
Compare and define an animation and a scenario
Write a storyboard
Flowchart a storyboard
Describe inheritance and how traits are passed from
superclasses to subclasses

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

46

Summary
In this lesson, you should have learned how to:
Describe when to implement procedural abstraction
Demonstrate how to declare a procedure
Identify and use procedural abstraction techniques to simplify
animation development

JF 2-5
Declare Procedures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

47

Java Fundamentals

2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Define multiple control statements to control animation
timing
Create an animation that uses a control statement to control
animation timing
Recognize programming constructs to invoke simultaneous
movement

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Arguments
The arguments of a procedure may be edited or further
defined to control object movement and timing.
Examples of Alice 3 arguments include:

Object
Direction
Direction amount
Time duration

A computer program requires arguments to tell it how to implement


the procedure.

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Arguments Display
Below are examples of arguments in a procedure.

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Edit Arguments


Next to the argument's value, click the arrow to display the
menu of values.
Select a new value.
The menu indicates the current value, followed by pre-set
values to choose from, followed by additional menu options
to specify randomization, math calculations, or a custom
decimal number.

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Selecting a Placeholder Argument


When adding a procedure to the code, you are required to
select a value for each argument in the procedure.
Often times you may choose a pre-set value as a placeholder
(a temporary value) which is later changed during an edit
cycle.
Using a placeholder value is a common approach to creating
and refining animation performance.

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Simultaneous Movements
To create simultaneous movements for an object, use the Do
together control statement.
Control Statement
Do In Order

Do Together

Description
Default control statement in Code editor.
Executes procedures in sequential order.
Executes procedures simultaneously.
Used for simultaneous movements such as walking
and sitting motions.

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Simultaneous Movements Example 1


For example, a movement executed together could be as
simple as simultaneously raising both arms of a biped object
from a hanging position to a straight arm overhead position.

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Simultaneous Movements Example 2


Another example is a walking motion, which requires
simultaneous movement of the hips and shoulders.
To create the walking motion for a biped, use:
A series of move, roll, and turn procedures.
Do together control statements.

Different programming may be required for different objects


because no two objects walk the same way.

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Walking Textual Storyboard Example


Order of Instructions

Programming Instructions
Whole body moves forward
Left shoulder turns right
Right shoulder turns right

Do Together

Left hip turns forward


Right hip turns backward
Whole body moves forward
Left shoulder turns left
Do Together

Right shoulder turns left


Left hip turns backward
Right hip turns forward
JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Walking Motion Example


Examine this code for a simple walking motion.

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

When Procedures Offset Each Other


A common mistake is to include two procedures that cancel
each other in a Do together construct.
For example, if you include a move up 1 meter procedure,
followed by a move down 1 meter procedure in a Do
together, nothing will happen.
The procedures cancel each other out.

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

setVehicle Procedure
The setVehicle procedure employs the concept of a rider
object and a vehicle object.
The rider object is selected when the setVehicle procedure is
used to specify the vehicle for the rider.
Then, when the vehicle object is programmed to move, the
rider object will automatically move with it.
Examples:
Person rides a camel or horse.
Camera follows a helicopter to shoot the scene from the helicopter's
point of view.

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

setVehicle Procedure Example 1


The child is positioned on the camel in the Scene editor.
Then, the camel is set as the vehicle of the child in the Code
editor.
When the camel moves, the child stays on top and moves
with the camel.

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

setVehicle Procedure Example 2


The helicopter is set as the vehicle of the camera in the Code
editor.
When the helicopter moves, the camera films the scene from
the helicopter's perspective.

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Steps to Use setVehicle Procedure


Determine the vehicle object and the rider object.
In the Code editor, select the rider object from the Instance
menu.
From the Procedures tab, drag the setVehicle procedure into
the Code editor.
In the procedure, select the vehicle object from the menu.

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Steps to Stop setVehicle Procedure


If you want the rider object to get off the vehicle object, drag
another setVehicle procedure into the Code editor at the
point the rider should get off the vehicle.
Set the vehicle to this, which sets the vehicle of the rider back
to the scene.

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Terminology
Key terms used in this lesson included:
Arguments
Do together control statement
Do in order control statement

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Summary
In this lesson, you should have learned how to:
Define multiple control statements to control animation
timing
Create an animation that uses a control statement to control
animation timing
Recognize programming constructs to invoke simultaneous
movement

JF 2-6
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Java Fundamentals

2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Using functions to control movement based on a return value

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Functions
Functions:
Are used to ask questions about properties of an object.
Are similar to procedures except that they return a value of a particular
type.
Can be used to compute a value.

Functions answer questions about an object, such as its height, width,


depth, and even its distance to another object.

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Functions Precisely Answer Questions


Functions provide precise answers to questions, such as:
What is the distance between the Dalmatian and the bunny?
What is the height of the playingCard?
What is the width of the pocketWatch?

A boolean function returns either a true or false value.


For example, if the isFacing function is called to determine if
the Alice object is facing the bunny object, a true or false
value will be returned.

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Functions Tab
The Functions tab is in the methods panel.
Select the object from the Instance menu, and then view its
functions.

This is where you can find information on joints that are


specific to the type of object that you have added to your
animation
JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Functions Solve Distance Problems


Suppose we want to move the Dalmatian directly to the
bunny without having to manually determine, through trial
and error, the distance between the Dalmatian and the
Bunny.
We could guess the distance by specifying a placeholder
value and testing the movement until we get close to the
desired end result, but a more efficient way is to use a
function to determine the exact distance to move.

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Use getDistanceTo Function


Use the getDistanceTo function as part of a move procedure
to solve this distance problem.

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Use the getDistanceTo Function


Determine the moving object and target object.
In the Code editor, select the moving object from the Instance
menu.
Drag the move procedure into the Code editor.
Select the direction and a placeholder argument for distance
(the distance argument will be modified in the next step).

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Use the getDistanceTo Function


From the Functions tab, drag the getDistanceTo tile onto the
highlighted distance value.

Select the target object.

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Test the Function


In the example below, the Dalmatian moves to the center of
the Bunny at run-time.
This could be read out loud as "determine the distance from
the center of the Dalmatian to the center of the Bunny and
then move the Dalmatian forward that amount."

Click the Run button to test the programming statement.

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Test the Function


The Dalmatian moves to the middle of the Bunny.
This is because the getDistanceTo function calculates the
distance between the centers of both objects.
The function calculated the distance from the center of the
Dalmatian to the center of the bunny, and moved the object
using that value.

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Avoid Collisions
You can enhance function calls using the math operators (+)
addition, (-) subtraction, (*) multiplication, and (/) division.
For example, you can reduce the distance an object will move
to avoid a collision.

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Using Math Operators


A function determines the distance between the Dalmatian
and the Bunny.
To reduce the value returned by the getDistance function, the
subtraction operator subtracts a specified value.
The specified value is determined by calling the getWidth
function and dividing that value in half.
Dalmatian

X = Get distance from Dalmatian to Bunny

Z = X (Y / 2)

Bunny

Y = Get width of Bunny

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Examine the Math Calculation


Let's examine the math calculation Z = X - (Y / 2):

Z represents the total distance the Dalmatian will move.


X represents the distance between the Dalmatian and Bunny.
Y represents the width of the Bunny.
Y / 2 represents the width of the Bunny divided by 2.
( ) represent the order of precedence.

Dalmatian

X = Get distance from Dalmatian to Bunny

Bunny

Y = Get width of Bunny

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Math Operator Tip


Why did we divide the width of the Bunny in our calculation?
Because we want the animation to appear as though the
Dalmatian is moving to the very edge of the Bunny.
If we used the entire width of the Bunny, the Dalmatian
would stop further from the Bunny than desired.
Dalmatian

X = Get distance from Dalmatian to Bunny

Bunny

Y = Get width of Bunny

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Steps to Use Math Operator to Avoid


Collision
Click the function name between the two objects.
Select Math.
Select the getDistanceTo subtraction option.
Select a fixed distance amount.

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Steps to Use Math Operator to Avoid


Collision
Run the animation to test how the object moves at run-time.

Adjust the fixed value to get the desired result

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Understanding the Math Menus Example 1


The following image displays the math operators (+ - * / )
requiring one or two arguments.
Each option will provide one or two cascading menus to
specify the argument values.

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Understanding the Math Menus Example 2


The following image displays an (+) addition operator
requiring a single argument.
The following image displays math operators requiring two
arguments.

Remember, you can select placeholder values for the


arguments.
Placeholder values can always be edited.
JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Remove Object's Depth from Function


Another precise way to avoid collisions is to remove the
depth (length) of the moving object from the function.
In the example below, the Dalmatian will move the distance
to the Bunny, minus the depth of the Dalmatian.

Bunny

Dalmatian
Distance from Dalmatian to Bunny
Dalmatian depth

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Depth is Measured from Object's Center


When a distance value is calculated, it is measured from one
object's center to another object's center.
The same is true for math calculations.
When the depth of the Dalmatian is subtracted from the
Bunny, it is actually subtracted from the center of the Bunny.

Bunny

Dalmatian
Distance from Dalmatian to Bunny
Dalmatian depth
JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Steps to Remove Depth from Function


In the Functions tab, drag the moving object's getDepth
function onto the highlighted distance value.

Run the animation to test how the object moves at run-time.


Adjust with additional math calculations if necessary.

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Terminology
Key terms used in this lesson included:
Functions
Math operators

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Summary
In this lesson, you should have learned how to:
Use functions to control movement based on a return value

JF 2-7
Functions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Java Fundamentals

2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Use the IF control structure to effect execution of instructions
Use the WHILE control structure to create a conditional loop
for repetitive behavior

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Control Structures
Control structures are pre-defined statements that determine
the order in which programming instructions are executed.
You should be familiar with the Do together and Do in order
control structures from previous topics.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Control Structures Available in Alice 3


Available pre-defined control structures include:

Do in order
Count
If
For each in
While
Do together
Each in together

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Control Structures Display


You can drag a control structure to myFirstMethod before or
after creating the programming instructions that will be
included in the control structure.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Control Structures Example


For example, if you create a move and turn instruction for an
object, and later decide that the actions should execute
simultaneously, you can insert a Do together control structure
and reposition the move and turn instructions within the
control structure.
Or, you can anticipate that you are going to need a Do
together control structure, insert the control structure, and
then create and position the programming instructions within
the control structure.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Nesting Control Structures


Control structures may be nested, meaning that one structure
is contained within another.
For example, if a biped is going to wave their left hand and
then their right hand while it is moving forward, nested
control structures would be necessary.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Nesting Control Structures Code Example


Examine these
programming
instructions.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Conditional Execution Using Control


Structures
Conditional control structures allow you to control execution
based on a condition, or a decision being made.
Consider these examples:
If the current color of an object is blue, change the color to orange.
If the width to the rock is less than 1 meter, move forward 1/2 meter.
If the object opacity is 0, change the opacity to 1.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

IF Control Structure
The IF control structure requires a condition of true or false
when the structure is dragged into the program.
This initial condition is a placeholder. You will need to
establish the condition to be evaluated.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

IF Control Structure Parts


The IF control structure has two parts: the IF part, and the
ELSE part.
If the IF part is executed, the ELSE part is never executed.
If the ELSE part is executed, the IF part is never executed.
Both the IF part and the ELSE part of an IF statement can
contain another nested IF control structure.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

WHILE Control Structure


The WHILE statement executes instructions repeatedly in a
loop while a condition is true.
This conditional execution is also known as "repetition."
The WHILE condition:
Acts like a gatekeeper to an event.
Must be true to allow the programming instructions within the loop to
execute.
Exits the loop when the condition becomes false.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

WHILE Control Structure and Repetitive


Execution
After all of the programming instructions within a loop are
executed, the WHILE condition is evaluated again for
repetitive execution.
If the condition is still true, execution will repeat.
If the condition is false, the loop will be skipped and
execution will continue with the next programming statement
following the WHILE control structure.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Interpret an IF Control Structure


An IF control structure is a decision based on a condition.
Example condition: If it rains today I will wear a raincoat.
Otherwise, I will wear a sweater.
IF control structures can be interpreted using a process flow.
A process flow is a graphical representation of a process model.
Process flows use shapes to represent the actions in the model.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

IF Control Structure Process Flow


If it rains today, then I will wear a raincoat. Otherwise, I will
wear a sweater.
True

If it rains
today,
then

False

Do this: Wear
sweater

Do this: Wear
raincoat

End

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

IF Control Structure Process Flow Example


If the cat walks into the dog, then the cat says "Excuse me!"
Otherwise, the cat continues walking.
True

If cat
collides
with dog

Do this: Cat
says, "Excuse
me!"

False
Do this: Cat
continues to
walk

End

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Steps to Program an IF Control Structure


Insert the initial motions that happen before the IF control
structure is executed.
Drag and drop the IF control structure into the Code editor
and select the true condition as a placeholder during setup.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Steps to Program an IF Control Structure


Replace the true condition with a condition to evaluate, such
as a function.
Insert the procedures that will execute if the condition is true
(IF) and those that will execute if the condition is false (ELSE).
Run the animation to test the conditional behavior. Debug as
necessary.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

IF Control Structure Example


If the cat collides with the dog, then the cat moves backward
and says "Excuse me!
Otherwise, the cat continues to move forward.
The isCollidingWith function was dragged onto the true
condition placeholder.
This function tells us if one object is colliding with another.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Conditional Execution
The use of conditional control structures allows two types of
loops:
Conditional loop: Stops when a condition is true.
Example: The propeller of a helicopter turns while the helicopter is moving
or flying. If the helicopter stops, then the propeller stops turning.

Infinite loop: Never stops.


The hour and minute hands on a clock continue rolling.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

WHILE Control Structure


The WHILE control structure performs conditional loops.
While a condition is true, the programming instructions
within the loop are executed.
Once the condition is no longer true, program execution will
skip the WHILE condition and continue with the programming
instruction that follows the WHILE loop.
The WHILE control structure will perform instructions while a
condition is true; otherwise it will bypass the instructions.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

WHILE Control Structure Process Flow


The Queen moves forward, unless she collides with the
Playing Card.
If the Queen collides with the Playing Card, she stops and
turns to face the camera.
True

Queen moves
forward

While the
Queen is
collisionfree

False
Queen stops
and turns
around

End

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Steps to Program a WHILE Control


Structure
Drag and drop the WHILE control structure into the Code
editor and select the true condition as a placeholder.
Replace the true condition placeholder with the condition to
evaluate.
Insert procedures that will be executed while the condition is
true.
Insert the procedures that are executed after the while loop
stops executing.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

WHILE Control Structure Example Code


While the Queen is not colliding with the Playing Card, the
Queen moves forward repeatedly.
If the Queen does collide with the Playing Card, the WHILE
loop stops and the program continues with the next
instruction:
She stops and turns to face the camera.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Steps to Test a WHILE Control Structure


Position objects such that the WHILE condition will evaluate
to true.
Observe that all programming instructions within the WHILE
loop execute.
Ensure that the WHILE loop execution stops when the while
condition is no longer true.

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Terminology
Key terms used in this lesson included:
IF control structure
Process flow
WHILE control structure

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Summary
In this lesson, you should have learned how to:
Use the IF control structure to effect execution of instructions
Use the WHILE control structure to create a conditional loop
for repetitive behavior

JF 2-8
IF and WHILE Control Structures

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Java Fundamentals

2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Create an expression to perform a math operation
Interpret a math expression

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Using Expressions
Expressions are a combination of values that, when arranged
correctly, result in a final value.
Expressions are typically used in Alice 3 to solve timing and
distance problems in your programs.
Example: 2 + 2 = 4
Two values (2, 2) and the operator (+) result in the final value (4).

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Expressions in Alice 3
Expressions are created in Alice 3 using the following built-in
math operators:

Add (+)
Subtract (-)
Multiply (*)
Divide (/)

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Location of Math Operators


Math operators are available in the cascading menus where
you select the argument values for:
Amount and Duration
getDistance functions

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

View Expressions in a Distance Argument


Select the Math option to view the available math operators
in a procedure's distance argument.
Select from two different sets of math expressions:
The first set lets you specify the value of one operator
The second set lets you specify the values of both operators

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

getDistanceTo Function Display


Select the Math option to view the available math operators
for the getDistanceTo function's argument.

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Distance Problem
The problem: A PlayingCard object moves to the center of the
bookcase, rather than near it.
This is because the getDistanceTo function calculates the
distance from the center of the person object to the center of
the target object (bookcase).
We need to reduce the distance the PlayingCard object
moves so it does not collide with the bookcase.
A math calculation is used to reduce the distance the
PlayingCard object moves.

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Create an Expression


Summarize the timing or distance problem in your program.
Consider the expression that will solve the problem.
Code the expression.
Test and debug the expression until the animation works as
intended.

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Steps to Move an Object the Distance to


Another Object
Drag the move procedure for an object into the Code editor.
Select forward and a distance placeholder value.
From the Functions tab, drag the getDistanceTo function onto
the distance argument placeholder.
From the cascading menu, select the target object to which
the object should move.

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Steps to Modify the Distance Using a Math


Operator
From the getDistanceTo tile, click the outer-most arrow to
open the menu of distance values, and then select the Math
option.

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Steps to Modify the Distance Using a Math


Operator
Select getDistanceTo - ???
Select a default value to reduce the distance by, or select
Custom DecimalNumber to enter a value.

Test and debug the expression as necessary.

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Editing the Expression


During the debugging process, you may need to adjust the
value of the expression.
Click the arrow next to the value, and select a new default
value or use the Custom DecimalNumber... menu to select a
more defined value.

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Expression Example
This expression reduces the distance that the Playing Card
travels so that it does not collide with the bookcase.
This was tested and debugged several times until the correct
expression was achieved.
With a value of 0.25 the Playing card was still too close.
With a value of 1.0 the distance is correct.

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Subtract Depth from the Expression


Subtracting the depth of the target object from the
expression is a more precise way to ensure that the moving
object lands directly near the target object without going
through its center.

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Steps to Subtract Depth from Expression


Select the target object in the instance menu.
From the Functions tab, drag the getDepth tile onto the
existing distance value in the expression.

Test and debug the animation, and adjust the expression as


necessary.

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Interpret an Expression
To understand a programming statement that includes an
expression, you often need to interpret the expression.
To interpret an expression you can:
Read it from left to right.
Recognize the instances specified in the expression and
describe what each one does.

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Building the Example Expression


1. Add a move procedure from the marchHare and use a
placeholder value.
2. Drag the getDistanceTo function from the marchHare and
choose the teacup as the target object.
3. Click on the outside arrow of the expression
4. Choose math from the list and choose the subtract option

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Building the Example Expression


5. Replace the placeholder value with the getWidth function
from the teacup class
6. Click on the inner arrow after getWidth and choose Math,
then the division operator and choose 2 as the value
7. This completes the expression that should look like this:

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Expression Example
Examine the visual associated with this expression.
The hares are moving towards the teacup.
Do you think they will go inside?

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Interpretation of an Expression
This expression tells us the following:
The marchHare moves forward towards the teacup.
The distance between the marchHare and the teacup is determined by
the getDistanceTo function.
The distance traveled is reduced by half the width of the cave.
The width of the teacup is determined by the getWidth function.

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Formulating the Expression


To interpret an expression, it is helpful to draw a picture or
write the values you know before formulating the expression.
Example:
Z = X (a / b)

Z = Distance moved
X = Distance from marchHare to teacup
a = Teacup width
b=2

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Expression Example Answer


You were asked if you thought the marchHares would go into
the teacup?
The Answer is: No, they stop outside the teacup.
This is because we used the expression to manipulate the
distance between the objects.

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Terminology
Key terms used in this lesson included:
Expression
Math operator

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Summary
In this lesson, you should have learned how to:
Create an expression to perform a math operation
Interpret a math expression

JF 2-9
Expressions

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Java Fundamentals

2-10
Variables

0.88 meter height

White color

1.0 opacity

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Understand variables
Understand how variables are used in programming
Viewing Alice code as Java Code on the side

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Variables
At times, programmers need to store information, and then
use that information in animations or in games.
For example:
The number of times a procedure should be executed.
An object's properties, such as size and color.
A variable is a place in memory where data of a specific type can be
stored for later retrieval and use by your program. Each variable is
given a unique name to make it easy to find and reference. Once a
variable is declared it can be used to store and retrieve data.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Variables Example
Below are the variables and their values for a Dalmatian
instance.

0.88 meter height

0.34 meter width

1.0 opacity

White color

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Variables for Data Storage


A variable is like a container that stores a specific type of data
for later retrieval and use by your program.
Declare a variable by naming it and selecting the type of data
to store in it. Then, specify a default value for the variable.
Boolean values
(true or false)

Numbers (1, 0.254)

TextString
("Hello World!")

List of objects

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Object Properties
Object properties are variables that store information about
the object, such as color, width, height, and depth.

Width Variable

Width

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Variable Data Types in Alice 3


Data Type
Decimal Number
Whole Number
Boolean
Classes

Description
Perform arithmetic and set the value of a procedure's arguments.
Examples: 0.1, 2.25, 98.6.
Perform arithmetic and set the value of a procedure's arguments.
Examples: 1, 459, 30.
One of two values: true or false.
Usually is the result of tests that compare one thing to another.
The classes of objects that are available in your animation.
Examples: Biped, Scene, Quadruped.

TextString

A String of characters such as "hello" and "goodbye".

Other

Sounds, colors, shapes, and other special values.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Declaring Variables
To declare (or "create") a variable is to give a variable a name
and to define the type of data the variable will contain.
Variables are declared in the Code editor.
They are useful because they allow you to:
Assign the same value to multiple procedures, such as a distance to
move.
Simultaneously update the value of all arguments in a program that
reference the variable.
Pass information from one procedure to another.
Simplify programming statements using many functions and math
expressions.
JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Initializing Variables
To initialize a variable is to assign it a value. Variables are
initialized in the Code editor at the same time that they are
declared; this is its initial (first assigned) value.
Variable values can be changed as often as you like.
The word "initialize" means "assign a value to".

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Changing an Initialized Value


Remember, the initial value you specify for the variable can
be considered a placeholder value, and changed at a later
time.
You can change the initialized value of a variable using the
drop-down list.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Changing an Initialized Value


The new value of all arguments using the variable will change
when the initialized value is changed.
If one of the default values listed on the drop-down is not
what you need, use the Custom options menu to specify
another value.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Steps to Declare a Variable


Drag the variable tile into the Code editor.
Select the value type and name the variable.
Initialize the variable (set the first value that the variable will
hold) and click OK.
Note that the preview of the variable, above the thin line,
displays the variable settings.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Variable Example
The "superSpins" variable is declared and initialized to a
whole number with an initial value of 3.
Use a turn procedure to spin the character

This variable is dragged into the distance argument of the


turn procedure.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Variable Example
Each character spins three times.

If the initialized value of "superSpins" is changed to 4, all of


the characters will spin based on the value of the variable,
which is now 4.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Using Variables in Procedures


To use a variable that has been declared in a procedure, drag
the variable name tile onto the procedure's argument value.
The argument is replaced with the variable's initialized value.
Alice 3 helps you visualize the locations you can place a
variable by darkening the screen and highlighting the values
that can be replaced by the variable.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Using Variables in Procedures


Be aware that a variable must be declared and initialized
before it can be referenced by any other statement in your
code.
If you try to reference a variable before it exists, your
program will encounter an error at run-time.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Using Variables in Procedures


Caution: Alice highlights all arguments that might potentially
reference the selected variable, including those arguments
that precede the variable's existence.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Using Variables in Math Calculations


Note that variables can also be used in math calculations.
You can drag a declared variable onto any value within a math
expression.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Steps to Randomize an Initialized Value


Click the down arrow next to the initialized value.
Select Random from the drop-down list.
Choose either the option to randomize using a predefined
range or the option to randomize based on values you
establish.
If you choose the option to randomize based on values you
establish, select the starting and ending values for the range
using the cascading menus.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Steps to Randomize an Initialized Value


Remember, argument values can always be changed.
Randomization of variable values can add value to an
animation or game by creating random behavior.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Randomize an Initialized Value Display


Below shows how to randomize an initialized value.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Viewing Alice Code as Java


To see the code that has been produced in a more traditional
Java code environment Alice has a Java on the Side option.
Use the Window menu option, then preferences and Java
Code to enable the window.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Viewing Alice Code as Java


This allows you to see traditional programming structures
such as semi-colons(;) to finish statements and curly brackets
as begin({) and (}) end statements.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Viewing Alice Code as Java


Changes made in the Alice code are reflected in the java
code.

You cannot change the java code directly it is just a


representation of the Alice code.
JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Viewing Alice Code as Java


To turn off the Java Code on the side option and return to
only the Alice interface go to the window menu, preferences
and then un-tick the Java Code on the side option.

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Terminology
Key terms used in this lesson included:
Variable
Object properties
Declaring variables
Initializing variables
Java Code on the side

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Summary
In this lesson, you should have learned how to:
Understand variables
Understand how variables are used in programming
Viewing Alice code as Java Code on the side

JF 2-10
Variables

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Java Fundamentals

2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Create an opening sequence
Use keyboard controls to manipulate an animation
Save your Class file
Using the starter tab
Add an existing class file to an animation

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Event Handling
When an animation is playing, a computer program is
running. Many computer programs request user interaction.
These interactive programs allow a user to influence the
order of actions that occur in the program.
To program this type of interactivity into an animation, you
create event listeners that look for and respond to the
interactivity (the user input events) of the user.
This is often referred to as event handling.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

What Is an Event?
An event is any action initiated by the user that is designed to
influence the program's execution during play.
Events may include:

Pressing any key on the keyboard


Clicking a mouse button
Moving a joystick
Touching the screen (on touch-enabled devices)

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

What Happens When an Event Occurs?


Typically, an event triggers (fires, or sets in motion) the
execution of a procedure or function.
For example, when a user presses an up arrow key on the
keyboard (event), it triggers a method that makes the object
in the animation move up (event handling method).

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Keyboard Controls
Inserting keyboard controls into a program allows the user to
control one or more objects while the animation is running.
The user can press a key on the keyboard, or click the mouse,
to control the next programming action.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Keyboard Controls
With keyboard controls, you can:
Create scenes where the user controls an object that interacts with
other objects.
Create animations that execute conditionally, based on a key press or
mouse click.
Create games where the user is required to control an object to win the
game.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Keyboard Controls Example


In Alice 3, you can assign procedures to keys on your
keyboard.
When the animation viewer clicks a certain keyboard key, the
procedure assigned to the keyboard key is executed.
For example, clicking the right-arrow key on the keyboard
turns the teapot to the right.
In programming, keystrokes and mouse clicks are events. Coding
events to handle each procedure is referred to as event handling.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Event Listeners
Event listeners are procedures in the Scene class that listen
for keyboard input while the animation is running.
Keyboard keys can be programmed to:
Move an object up or down when certain keys are pressed.
Move an object forward, backward, left, and right using the arrow keys.
Make an object perform an action, such as speak or disappear.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Types of Event Listeners


There are four types of event listeners available in Alice 3:

Scene Activation/Time
Keyboard
Mouse
Position/Orientation

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Steps to Access Event Listeners


In the Code editor, click the Scene tab.
Click the button next to initializeEventListeners and choose
Edit.
This opens the initializeEventListeners tab if it is not already
open.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Event Listeners Tab


The initializeEventListeners tab is where you can add an event
listener to your code.

The sceneActivated listener is where you can create an


animation that will play before the myFirstMethod begins.
This can be used as an opening sequence to your code.
JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Scene Activation Listener


You can create your own procedure or use one of the built in
procedures to create an opening sequence.
This procedure named "appear" turns Alice around and
makes her visible in our scene.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Scene Activation Listener


To enable the procedure, drag it from the Alice procedure list
and place it before the myFirstMethod call in the
sceneActivated listener.

Test your opening sequence!


JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Keyboard Listeners
Keyboard listeners:
Are found in the Add Event Listener drop-down menu.
Listen for, and react to, a keyboard keystroke that you specify.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Types of Keyboard Listeners


Data Type

Description

addKeyPressListener()

This listener lets you program procedures for the


keyboard key(s) you specify.

addArrowKeyPressListener()

This listener lets you program procedures for the


arrow key(s) you specify.

addNumberKeyPressListener()

This listener lets you program procedures for the


number key(s) you specify.

addObjectMoverFor(???)

This listener lets you program the user-defined


movement for a specified object.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Program Keyboard Event Listeners


For example, we will program keyboard event listeners to
command the teapot to move up and down using the B and C
keys, and move left, right, forward and backward using the
arrow keys.
We are in wonderland after all!

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Steps to Add Keyboard Event Listener


Select the Add Event Listener drop-down list.
Select Keyboard.
Select addKeyPressListener.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Steps to Program the IF Control Structure


Drag the IF control structure into addKeyPressListener.
Select the true condition.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Steps to Select the Keyboard Key to


Activate an Object's Motion
Drag the isKey: ??? tile onto the true condition.
A key menu appears.
From the drop-down menu, select the keyboard key that you
want to use to control the motion.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Steps to Program Motions Activated by Key


Press
From the Instance drop-down menu, select the object
controlled by the keyboard key.
Drag the procedure that should be activated by the keyboard
key into the IF control structure and select the arguments.
You could drag multiple procedures and control structures
into the IF control structure.
For example, when the B key is pressed, the teapot moves
and then turns.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Program Additional Listener Actions


To program the keyPressListener to listen for more than one
keyboard key, add additional IF control structures to the
listener structure.
There are two ways to do this:
Add a series of IF control structures one after another and always leave
the ELSE condition empty.
Nest additional IF control structures in the ELSE condition.

Both methods execute in the same manner.


The following steps use the second method, nesting IF control
structures in the ELSE condition, to save display space.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Steps to Program Additional Listener


Actions
Drag an IF control structure into the ELSE condition of an
existing IF control structure and select the true condition.
Drag the isKey ??? variable onto the true argument.
Specify the keyboard key to listen for.
Specify the programming statements to execute.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Completed Programming Instruction


Example
Below is an example of a teapot programmed to move up and
down using the B and C keyboard keys.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Steps to Move Objects Using Arrow Keys


Select the Add Event Listener drop-down menu.
Select Keyboard.
Select addObjectMoverFor.
Select the entity, or object, to control.

Creates the following line of code

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Steps to Test Event Listeners


Run the animation.
Click inside the animation window with your cursor.
Use the keyboard keys (specified in addKeyPressListener) to
make the object perform the procedure (move up and down).
Use the arrow keys on your keyboard to move the object
forward, backward, right, and left.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Using an Existing Class in Another


Animation
It can be useful to transfer a class from one animation to
another.
If you wanted to create multiple animations featuring Alice
then you could use your existing Alice class file with all of its
associated procedures.
This would cut down on your work as you have already coded
the actions for Alice.
This would cut down on your testing because you have
already tested that the code works in the original animation.
You can use the class and its procedures as a basis for your
new animation adding additional procedures if required.
JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Saving a Class File in Alice 3


Using the class list button, choose Alice from the list and then
click on the Alice class.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Saving a Class File in Alice 3


Click on the Save to Class File button.

Save the file in the MyClasses folder for easy access when
adding it to other animations and name the class with an
appropriate name.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Using the Starter Tab to Create a World


Alice 3 has pre-built worlds that can be used to quickly create
a full and interesting animation.
Use the starters tab from the new project interface to choose
your world.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Adding a Class File in Alice 3


Create a new project in Alice and go to the scene editor to
access the gallery
Choose the My Classes tab from the gallery

This gives you access to the MyClasses folder where your


classes should be saved

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Adding a Class File in Alice 3


Add the class as you would any other class from the gallery.

When you click OK you are presented with a list of the


procedures associated with the class file.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Adding a Class File in Alice 3


Placing the cursor over the green cross expands the code for
the procedure.

Clicking finish will add the Alice object into your new
animation.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Adding a Class File in Alice 3


You can now use the Alice character and her procedures in
your new animation.
You can add the appear method to the new sceneActivated
listener so that Alice appears in a consistent way across all of
your animations.

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

35

Terminology
Key terms used in this lesson included:
Event
Event handling
Event listeners
Keyboard controls
Keyboard listeners
Class file

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

36

Summary
In this lesson, you should have learned how to:
Create an opening Sequence
Use keyboard controls to manipulate an animation
Save your Class file
Using the starter tab
Add an existing class file to an animation

JF 2-11
Keyboard Controls

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

37

Java Fundamentals

2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Use functional decomposition to write a scenario and
storyboard
Complete an animation
Test an animation
Reposition objects at run-time
Upload your animation
Plan the presentation of a completed animation project

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Animations
An animation is a sequence of actions that simulate
movement.
Use Alice 3 to construct the scene and write the sequence of
actions for your animation, and Alice 3 will render the
animation for you.
Rendering is a process where the software program converts your
code into the animation that you see. Alice 3 renders the animation
based on the instructions provided by the programmer.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Animations Require Planning


Animations can be complex to plan and develop.
To simplify and organize this complex task, you can:
Use a methodical process to identify and solve the problems that arise
along the way.
Break down the development into manageable steps.
Functional decomposition is the methodical process of identifying a
complex problem and breaking it down into smaller steps that are
easier to manage.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Functional Decomposition Example


Examine this high-level process:
Consider a math concept that requires many steps.
Identify the high-level steps for the math concept.
Further refine and define the low-level tasks needed for each high-level
step.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Animation Development Process


The process to develop an animation is similar to the
problem-solving process.
Compare the two processes below.
Problem-Solving Process
Step 1:
Identify the
Problem

Step 2:
Develop a
Solution

Step 3:
Implement the
Solution

Step 4:
Test and Revise
the Solution

Animation Development Process


Step 1:
Define the
Scenario

Step 2:
Design a
Storyboard

JF 2-12
Develop a Complete Animation

Step 3:
Program the
Animation

Step 4:
Run the
Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Step 1: Define the Scenario


Professional animators begin by developing a scenarioor
storythat gives the animation a purpose.
Examples:

A story that presents a conflict and resolution.


A lesson that teaches a math concept.
A simulation that demonstrates a process.
A game that entertains or trains.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Scenario and Animation Examples


Scenario Type

Scenario

Animation

Problem and a solution.

A cat needs help to get


down from a tree.

A firefighter climbs up
the tree to save the cat.

Teach a concept.

Memorizing chemistry
symbols is difficult.

A timed game matches


chemistry symbols with
their definitions.

Simulate or demonstrate
a process.

A car has a flat tire.

A demonstration shows
how to change a tire on
a virtual car.

Play a game.

An airplane must avoid


objects in its path as it
flies through the sky.

An interactive game
maneuvers an airplane
around objects in the
sky.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Step 2: Design a Storyboard


Two types of storyboards are often used to plan an
animation:
Visual: A series of illustrated images that represent the main scenes of
the animation.
Textual: A detailed, ordered list of actions that each object performs
within each scene of the animation.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Storyboard Formats
Develop your visual and textual storyboards using a variety of
formats.
Examples:
Draw them on paper with a pencil.
Create them using digital tools such as a word processor, drawing
software, or presentation program.
Write a textual storyboard within Alice 3 in the Code editor using
comments to organize the steps in your program.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Visual Storyboards
The visual storyboard helps a reader understand:

The scene components.


How the initial scene will be set up.
The moving and non-moving objects in a scene.
The actions that will take place.
The user interactions that occur during the animation execution.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Visual Storyboard Example

Boy and girl sit on a park


bench. The boy walks
away, leaving his phone
behind.

Girl notices the mobile


phone. She thinks, "Hey!
That boy forgot his
phone!"

JF 2-12
Develop a Complete Animation

Girl says out loud, "Hey!


You forgot your phone!"
Boy turns around and
walks back to bench. He
says, "Oh! thank you!"

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Textual Storyboards
A textual storyboard helps the reader understand the actions
that will take place during the animation.
The moving and non-moving objects can be easily identified
within the action statements, but a more detailed description
may be necessary if multiple programmers are involved in
implementing any scene.
In computing, a textual storyboard is called an algorithm: a list of
actions to perform a task or solve a problem.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Textual Storyboard Example 1


Program the following actions in order:

Boy and girl sit on a park bench.


Boy stands up and walks away, leaving his phone on the park bench.
Girl turns to look at the phone.
Girl thinks, "Hey! That boy forgot his phone!"
Girl says out loud, "Hey! You forgot your phone!"
Boy stops and turns around.
Boy walks back to the park bench and says, "Oh! Thank you!"

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Textual Storyboard Example 2


This example shows how you can develop your storyboard by
first writing comments in the Code editor of your program.
Afterwards, you can start to develop the animation directly
from the storyboard.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Storyboard Components
Textual storyboards should contain the components listed
in the table below
Component

Definition

Examples

Scene

The place (or "world" in Alice 3)


where your story occurs.

Park, library, school,


home

Objects

Moving or non-moving characters


that you program to move and act.

Animals, cars, people,


trees

Actions

Instructions for how each object


should act in the scene.

Walk 2 meters, turn left,


say "Hello!"

User
Interactions

Ways in which the user viewing the


animation can manipulate the
objects in the animation.

Keyboard commands or
mouse clicks to make
objects move

Design
Specifications

How the objects and scenery


should look in the animation.

Size, position, location,


color

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Storyboard Process Flow


Flowcharting a storyboard helps you organize the flow of
actions and conditions within an animation.
True

Boy
leaves
phone
on bench

False

Girl says, "Hey you


forgot phone"

Girl does nothing

Boy stops, turns


around, comes back
to bench, says
"Thank you"

Boy keeps walking

End
JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

How Storyboards are Helpful


There are several ways that storyboards aid in program
development:
Textual storyboards can be used to generate program comment
statements and organize program development.
Storyboards can also help programmers identify repetitive actions, or
actions that may be performed by more than one object.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Step 3: Program the Animation


After completing the storyboard, the next step is to program
the animation in Alice 3.
As you program the animation, refer to your storyboard for
the animation's design specifications.
The code written in Alice 3 provides the instructions for the
animation's look at run-time.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Animation Checklist
During the animation development process, use this checklist
to ensure that your animation meets all animation principles.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Create a Complete Animation


Creating a complete animation requires a thorough
understanding and application of all of the components that
you have learned so far.
Completed scene of multiple objects
from multiple classes, including props
and shapes

Vehicle riding with the setVehicle


procedure

Declared procedures

Functions

Movement procedures

IF and WHILE control structures

Object rotation and object sub-part


rotation procedures

Random numbers

Simultaneous movement with the Do


Together control structure

Math expressions

Variables

Keyboard controls
JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Step 4: Run the Animation


Run the animation to test that it functions properly and
executes the actions planned in the storyboard.
This process is often referred to as testing and debugging the
software.
Programs can be tested by entering an unintended value in the
argument field of a method in an effort to try and "break" the code.
When something is broken or doesn't work as you intended in a
software program, it is often referred to as a "bug". Debugging is the
process of finding and eliminating bugs in a software program.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Debugging Tasks
Test and debug the animation frequently as it is being
developed.
Use some of the following debugging techniques:
Adjust the direction, distance, and duration that objects move.
Adjust math calculations that help refine the distance or duration that
objects move.
Refine instructions in the code that do not work as intended.
Resolve errors created by the programmer.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Test Elements of Your Animation


Test every element to prove that it works without error.
Math expressions calculate as expected.
Objects move with smooth timing.
Control structures operate as expected.
Event listeners trigger the correct responses.
Insure that your code includes comments that clearly identify the
purpose or the functionality of blocks of statements in your program.
Referring to the comments will help you test and debug your program.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

User Input to Reposition Objects at RunTime


To create an interactive program, a Listener object must be
added to the scene.
The addDefaultModelManipulation procedure creates a
Listener object that targets a mouse-click on any object in the
scene and responds by allowing the user to drag that object
around the scene while the animation is running.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Steps to Add the


addDefaultModelManipulation Procedure
Go to the Scene tab.
Click the edit button next to initializeEventListeners.
Drag the addDefaultModelManipulation procedure (Scene
class) into the initalizeEventListeners Code editor.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Using the addDefaultModelManipulation


Procedure
This procedure allows you to reposition objects at run-time:
Click and drag the object with your cursor to move it around the
scene.
Press the Control (Ctrl) key, and then click and drag the object with
your cursor to turn it right and left.
Press the Shift key, and then click and drag the object to move it up
and down.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Uploading your animation


Once you have completed your animation Alice has the
facility to allow you to upload your file directly to YouTube.
All you need is a YouTube account and you can upload directly
from within Alice 3
To access the facility go to File, Upload to YouTube.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Uploading your animation


The interface requires you to record your animation into a
format (.webm) that can be uploaded to YouTube.
To do this press the record button.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Uploading your animation


Press the stop button when your animation is complete or
you have recorded the section that you want to upload.

Then press next.


JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Uploading your animation


You can review your video before logging into YouTube with
your account details and adding a title, description and any
additional tags that you want.
Then click the upload to YouTube button.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Exporting your animation


If you do not want to upload the video but you want to create
a local copy of the file then click the Export Video to File
button that will let you save the file locally.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Present Your Animation Project


It's time to present your complete animation project.
Here are some steps to follow when organizing your
animation project presentation:
Make sure your presentation is thoroughly tested and complete.
Plan to demonstrate how you used each of the concepts learned in this
course.
Find out how much time you will have for your presentation.
If it is a group presentation, plan who will do which parts of the
presentation.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Prepare a Presentation Outline


Create a presentation outline to plan your complete
animation project presentation.
The following slides show an example presentation outline.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

35

Presentation Outline: Section 1


Section 1: Introduction

Gain your listeners' attention.


Introduce the theme of the animation project.
Preview your animation.
Establish your credibility as a speaker.
Give the audience a reason to listen to the presentation.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

36

Presentation Outline: Section 2


Section 2: Presentation of animation project
Organize the presentation in a logical flow.
Show all capabilities of your animation project.
Demonstrate how each course concept was used in the animation
project.
Time visual aids to support the spoken presentation.
Include helpful transitions between ideas.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

37

Presentation Outline: Section 3


Section 3: Conclusion
Summarize the animation in a memorable way.
Motivate the audience to respond.
Provide closure.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

38

Practicing Your Presentation


When rehearsing your presentation:
Rehearse aloud.
Time your speech; if it is too long or short, revise it.
Rehearse standing up.
Rehearse in front of someone.
Tape-record or videotape your speech. If you do not have access to
recording equipment, practice in front of a mirror.
Rehearse using visual aids and technology.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

39

Group Presentations
If you will be making your presentation with a group, here are
some steps your group can follow to make sure all group
members have a part in preparing and delivering the
presentation.
Include all group members in all steps of the presentation
planning.
Divide presentation tasks equally among group members.
Practice the presentation as a group, and give one another
constructive feedback immediately following.

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

40

Terminology
Key terms used in this lesson included:
Algorithm
Animation checklist
Debugging
Comments
Functional decomposition
Rendering
Scenario
Textual storyboard
Visual storyboard
JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

41

Summary
In this lesson, you should have learned how to:
Use functional decomposition to write a scenario and
storyboard
Complete an animation
Test an animation
Reposition objects at run-time
Upload your animation
Plan the presentation of a completed animation project

JF 2-12
Develop a Complete Animation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

42

Java Fundamentals

2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Describe variables
Describe Java simple types
Define arithmetic operators
Describe relational and logical operators
Describe assignment operators

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Alice 3 Versus Java


Alice 3

Java

3D programming environment that uses


visual representations for the Java
programming language.

Programming language; syntax can be


edited using integrated development
environment (IDE).

Used to create animations or interactive


games while working with programming
constructs.

Used to create applications that run on


any platform, including the web, using
Java syntax.

Drag and drop interface designed to


reduce syntax errors and make learning
programming easier.

IDE helps you objects model real world


objects, allow for re-use and easier
maintenance.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Variables in Alice 3
Variables are declared (created) in your code.
A typical application uses various values which continuously
change while the program is running.
For example, in Alice 3, a car is programmed to roll over a
certain number of times.
The value entered by one user may be different from the
value entered by another user.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Variables Manage Values


Variables manage the values entered by different users in
Alice 3.
A variable is a place in memory where data of a specific type can be
stored for later retrieval and use by your program. Each variable is
given a unique name to make it easy to find.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Object Properties
Object properties are variables that store information about
the object, such as its color, height, and depth.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Declare Variables in Alice 3


Drag the Variable tile into the Code editor to declare a new
variable.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Declare Variables in Java


In Java, you declare variables that can then be referenced in
other parts of the program.
public class Print{
public static void main(String[] args){
//variable declaration section
i and j are variables
int i=1;
that are declared
int j;

here.

while(i<=7){
for(j=1; j<=i; j++)
System.out.println("*");
i=i+2;
System.out.println();
}

i and j are called in


the program body.

}
}

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Data Types in Alice 3


When you declare a variable in Alice, you must define the
data type.
A variable's data type defines the kind of values that a variable can
store.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Variable Data Types in Alice 3


Data Type
Decimal Number
Whole Number
Boolean
Object
Classes

Description
Perform arithmetic and set the value of a procedure's arguments.
Examples: 0.1, 2.25, 98.6.
Perform arithmetic and set the value of a procedure's arguments.
Examples: 1, 459, 30.
One of two values: true or false.
Usually is the result of tests that compare one thing to another.
Any object in Alice 3 like a cat, dog, person, etc.
The classes of objects in your animation.
Examples: Biped, Scene, Quadruped.

TextString

A String of characters such as "hello" and "goodbye".

Other

Sounds, colors, and other special values.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Data Types in Java Example


class PrintText{
public static void main(String[] args){
//variable declaration section
byte aByte = -10;
int aNumber = 10;
char aChar = 'b';
boolean isBoolean = true;

This code defines


variables using four
different Java types.
Variables are declared and
initialized.

//print variables alone


System.out.println(aByte);
System.out.println(aNumber);
Variables are printed.
//print variables with text
System.out.println("aChar = " + aChar);
System.out.println("The boolean var is:" + isBoolean);
}//end method main
}//end class PrintText

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Java Simple Types


In Java, there are eight basic data types, called "simple types"
or "primitives".
Data Type Size

Example Data Data Description

boolean

1 bit

True, false

byte

1 byte (8 bits)

12, 128

char

2 bytes

'A', '5', '#'

Store true/false flags

Store integers from -127 to 128

Store a single Unicode character

Store integers from


short

2 bytes

6, -14, 2345

JF 2-13
Java Variables and Data Types

-32,768 to 32,767

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Java Simple Types


Data Type Size

Example Data Data Description

int

6, -14, 2345

4 bytes

Store integers from -2,147,483,648 to


2,147,483,647
Store integers from

long

float

double

8 bytes

4 bytes

8 bytes

3459111, 2

-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807

3.145, .077

Store a positive or negative decimal


number from 1.4023x10-45 to
3.4028x10+38

.0000456, 3.7

Store a positive or negative decimal


number from 4.9406x10-324 to
1.7977x10308

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Arithmetic Operators in Alice 3


Use add (+), subtract (-), multiply (*), and divide (/) to create
expressions in:
Amount and Duration arguments
getDistance functions

The value of an arithmetic operator can be stored in a


variable.
Arithmetic operators perform basic mathematical operations. They
take two operands and return the result of the mathematical
calculation.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Arithmetic Operators in Distance Argument


Using the drop down arrow beside the argument value gives
you access to the math function.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Arithmetic Operators in Java


Arithmetic operators work the same in Alice and Java, but
they are accessed differently.
In Java, you include arithmetic operators directly in your
code.
class BasicOperators {
//using arithmetic operators
public static void main(String[] args) {
//variable declaration section
int a = 1 + 1;
int b = 3 * 3;
int c = 1 + 8 / 4;
int d = -2;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}//end method main
}//end class BasicOperators
JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Relational Operators
Relational operators include:
=

>

<

Expressions with relational operators produce true or false


values.
A relational operator is a lexical unit used to express a relation, such
as equality or greater than, between two expressions. Two suitable
expressions combined with a relational operator often form a
relational expression or condition in a programming language.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Relational Operators in Alice 3


The following example shows a relational operator used to
test the distance between the Cheshire cat and the
Dalmatian.
If the distance from the cat to the dog is less than the depth
of the dog, the cat says "Hello dog!".
If the distance is not less then the cat moves forward .25
meters.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Relational Operators in Java


Symbol

Operator Name

Example

==

Equal To

(A == B) is false

!=

Not Equal To

(A != B) is true

>

Greater Than

(A > B) is false

>=

Greater Than or Equal To

(A >= B) is false

<

Less Than

(A < B) is true

<=

Less Than or Equal To

(A <= B) is true

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Relational Operators in Java Example


Relational operators in Java and Alice work the same way.
Below is sample Java code containing relational operators.
class Test {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("a
System.out.println("a
System.out.println("a
System.out.println("a
System.out.println("b
System.out.println("b
}//end method main
}//end class Test

== b = " + (a == b) );
!= b = " + (a != b) );
> b = " + (a > b) );
< b = " + (a < b) );
>= a = " + (b >= a) );
<= a = " + (b <= a) );

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Logical Operators in Alice 3


There are variations of logical operators in Alice 3.
Logical operators are the boolean operators AND, OR and NOT.
Expressions written with logical operators result in true or false.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Logical Operators in Alice 3 Example


The example uses both a and b logical operators to combine
two conditions into a single condition.
Both of these conditions must be true for the overall
condition to be true.
Otherwise, it will be false.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Logical Operators in Java


Logical operators work the same in Alice 3 and Java, they are
just accessed differently.
In Java, the logical operators are typed using symbols.
Symbol

Operator Name

&&

Conditional AND or "Short-circuited Operators"

||

Conditional OR or "Short-circuited Operators"

NOT

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Logical Operators in Java Example


This example demonstrates the NOT operator.
class BoolNotDemo {
public static void main(String[] args){
//variable declaration section
int x = 2;
int y = 1;
boolean bl;
bl = !(x > y); // bl is false
System.out.println("x is not greater than y:"+bl);
bl = !(y > x); // bl is true
System.out.println("y is not greater than x:"+bl);
}//end method main
} //end class BoolNotDemo

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Assignment Operators in Alice 3


Assignment operators change the value of a variable.
In the Alice 3 interface, you assign values to properties and
variables.
The color, opacity, position, vehicle and size properties are
assigned values in the Object Properties.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Assignment Operators in Alice 3 Example


In this example, the local variable superSpins is assigned an
initial value of three.
The number of times the character spins is assigned to
superSpins.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Assignment Operators in Java


In Java, use the equal sign ("=") to assign one value to
another.
In this example, the value of y is 5 and the value of z is 25.
class AssignmentDemo{
public static void main(String[] args) {
//variable declaration section
int x=5;
int y=10;
int z=20;
y = x;
z = y + z;
System.out.println("The value of y is:"+ y);
System.out.println("The value of z is:"+ z);
}//end method main
}//end class AssignmentDemo
JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Handling Standard Operations in Java


Java provides a special syntax for handling standard
operations such as z = y + z;
Syntax is z += y;
This code saves a few keystrokes, but still assigns z the value
of y plus z.

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Assignment Syntax for Other Operations


Symbol

Example

Equivalent To

+=

x += y

x = x + y;

-=

x -= y

x = x - y;

*=

x *= y

x = x * y;

/=

x /= y

x = x / y;

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Assignment Syntax Code Example


class AssignmentDemo2{
public static void main(String[] args) {
//variable declaration section
int x=5;
int y=10;
x += y;
System.out.println("The += result is:"+ x);
x -= y;
System.out.println("The -= result is:"+ x);
x *= y;
System.out.println("The *= result is:"+ x);
x /= y;
System.out.println("The /= result is"+ x);
}//end method main
} //end AssignmentDemo2
JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Terminology
Key terms used in this lesson included:
Arithmetic operators
Assignment operators
Data type
Logical operators
Relational operators
Variable

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Summary
In this lesson, you should have learned how to:
Describe variables
Describe Java simple types
Define arithmetic operators
Describe relational and logical operators
Describe assignment operators

JF 2-13
Java Variables and Data Types

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Java Fundamentals

2-14
Java Methods and Classes

Cat myCat = new Cat("Garfield");


myCat.setAge(6);
System.out.println(myCat.getName() + " is " +
myCat.getAge());
Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Describe a method, class, and instance
Describe a scenario where an IF control structure would be
used
Describe a scenario where a WHILE control structure would
be used
Recognize the syntax for a method, class, function, and
procedure
Describe input and output

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Alice 3 Versus Java


Alice 3

Java

3D programming environment that


uses visual representations for the
Java programming language.

A programming language with


syntax that can be edited using
an integrated development
environment (IDE).

Used to create animations or


interactive games while working
with programming constructs.

Used to create applications that


run on any platform, including the
web, using Java syntax.

Drag and drop interface designed


to reduce syntax errors and make
it easier to learn how to program.

IDE helps you model real world


objects, allows for re-use as well
as easier maintenance.

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Procedures in Alice 3
In Alice 3, a procedure is a piece of code that sends a
message to an object asking it to perform an action.
A procedure does not return a value.
A set of procedures are available for each class.

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Methods Panel in Alice 3


The methods panel lists all of an object's procedures and
functions.
It contains all built-in and user-defined procedures and
functions available for each object in your animation.

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Declaring Procedures in Alice 3


You can declare (create) your own procedures in Alice 3.

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Methods in Java
Methods in Java are the same as procedures in Alice 3.
A method is a piece of code that sends a message to an
object asking it to perform an action. Methods:
Belong to a class.
Are referred to by name.
Can be called at any point in a program using the method's name.

When a method name is encountered in a program, it is


executed.

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Methods in Java Example


When the method is finished, execution returns to the area of
the program code from which it was called, and the program
continues on to the next line of code.
public static void main (String[] args)
{
statement;
method1();
Method 2
statement;
method2();

statement;

JF 2-14
Java Methods and Classes

Method 1

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Decisions for Each Method


There are three decisions to make for any method:
What the method should do.
What inputs the method needs.
What answer the method gives back.

Java syntax for a method:


[modifiers] dataType methodName(parameterList) {
<methodBody>
return result;
}

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Method Properties

Method Property

Description

modifiers

These are optional and can be public, private, protected, or


left blank.

dataType

Type of data, like int.

methodName

Name of your method.

parameterList

Comma-separated list of parameter names with their data


types; each parameter is listed with its data type first, then
its name.

methodBody

Set of statements that perform the task.

return

Keyword that sends the result value back to the code that
called the method.

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

findMax() Method
public class TestFindMax {
/** Main method */
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = findMax(i, j);
System.out.println("The maximum between " + i + " and " + j +
" is " + k);
}//end method main
/** Return the max between two numbers */
public static int findMax(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
findMax Method
result = num2;
//endif
return result;
}//end method findMax
JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Classes in Alice 3
A Dalmatian is a dog. When a Dalmatian object is added to a
scene, it has the properties of the Dalmatian class: four legs,
two ears, a white and black spotted coat, and the ability to
walk.
A class is a specification, such as a blueprint or pattern, of how to
construct an object.

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Classes in Java
The first group:
Optional; refers to the visibility from other objects.
public means visible everywhere.
The default is package or visible within the current package only.
["public"] ["abstract"|"final"]"class" Class_name
["extends" object_name] ["implements" interface_name]
"{"
// properties declarations
// behavior declarations
"}"

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Classes in Java
The second group:
Optional; defines whether the class can be inherited or extended by
other classes.
Abstract classes must be extended and final classes can never be
extended by inheritance.
The default indicates that the class may or may not be extended at the
programmers discretion.
["public"] ["abstract"|"final"]"class" Class_name
["extends" object_name] ["implements" interface_name]
"{"
// properties declarations
// behavior declarations
"}"
JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Classes in Java
Class_name is the name of the class.
The third option of extends is related to inheritance.
The fourth option of implements is related to interfaces.
["public"] ["abstract"|"final"]"class" Class_name
["extends" object_name] ["implements" interface_name]
"{"
// properties declarations
// behavior declarations
"}"

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Code for Creating Cat Class in Java


class Cat{
int catAge;
String catName;
public Cat(String name){
catName = name;
}//end of constructor
public void setAge(int age){
catAge = age;
}//end method setAge
public int getAge(){
return catAge;
}//end method getAge
public static void main(String []args){
Cat myCat = new Cat("Garfield");
myCat.setAge(6);
System.out.println("Cat age: " + myCat.getAge());
}//end method man
}//end class Cat
JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Instances in Alice 3
When you add an object to a scene, this creates an instance
of the class.
An object is an instance of a class.

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Instances in Java
In the main method, the myCat instance of the cat class is
created.
class Cat{
int catAge;
String catName;

public static void main(String []args){


Cat myCat = new Cat("Garfield");
myCat.setAge(6);
System.out.println("Cat age: " + myCat.getAge());
}//end method man
}//end class Cat

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Create Instance of a Class


An instance of a class is created using the new operator,
followed by the class name.
class Cat{
int catAge;
String catName;

public static void main(String []args){


Cat myCat = new Cat("Garfield");
Create new instance
myCat.setAge(6);
System.out.println("Cat age: " + myCat.getAge());
}//end method man
}//end class Cat

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Control Structures
Control structures allow you to change the order of how the
statements in your programs are executed.
Both Alice and Java allow for these types of control
structures.
Type

Description

Example

Decision
Control
Structures

Allow you to select specific sections of code


to be executed.

if then else

Repetition
Control
Structures

Allow you to execute specific sections of code


a number of times.

while loop

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

if Control Structure
if control structures are statements that allow you to select
and execute specific blocks of code while skipping other
sections.
These structures have the following form.
if (boolean_expression) {
doSomething();
}
else {
doSomethingElse();
}//endif

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

if Control Structure Example


For example:
If a student receives a score of 90% or greater on their test, then give
them an "A".
If a student receives a score that is greater than or equal to 80% and
less than 90%, then give them a "B".
If a student receives a score that is greater than or equal to 65% and
less than 80%, then give them a "C".
If a student receives less than 65%, then give them an "F".

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

if Control Structure Example Code


public class Grade {
public static void main( String[] args ){
//variable declaration section
double grade = 89.0;
if( grade >= 90 ){
System.out.println( "A" );
}
else if( (grade < 90) && (grade >= 80)){
System.out.println("B" );
}
else if( (grade < 80) && (grade >= 65)){
System.out.println("C" );
}
else{
System.out.println("F");
}//endif
}//end method main
}//end class Grade
JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

while Control Structure


A while control structure, or while loop, is a Java statement
or block of statements that allows you to execute specific
blocks of code repeatedly as long as some condition is
satisfied.
The condition is tested before each loop.
while loop format:
while( boolean_expression ){
statement1;
statement2;
. . .
}

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

while Control Structure Example


class WhileDemo {
public static void main(String[] args){
//variable declaration section
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}//end while
}//end method main
}//end class WhileDemo

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Input and Output


Java programs work on many platforms.
They can be simple programs that run from the command
line, or they can have complex graphical user interfaces.
When learning to program, you will create programs that use
the command line for its input and output exclusively.
With more experience, you can build graphical user interfaces
and learn about the libraries required to build them.

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Input and Output Code


Print to the screen example.
System.out.println("Hello World!");

System.out.println() is a piece of code that is automatically


available to each and every Java program.

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Input and Output Code Example


User input example using the java.util.Scanner package.
import java.util.Scanner;
public class ReadString {
public static void main (String[] args) {
System.out.print("Enter your name: ");
Scanner in = new Scanner(System.in);
String userName = null;
userName = in.nextLine();
System.out.println("Thanks for the name, " + userName);
}//end method main
}//end class ReadString

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Terminology
Key terms used in this lesson included:
Class
Control structure
IF control structure
Instance
Method
WHILE control structure

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Summary
In this lesson, you should have learned how to:
Describe a method, class, and instance
Describe a scenario where an IF control structure would be
used
Describe a scenario where a WHILE control structure would
be used
Recognize the syntax for a method, class, function, and
procedure
Describe input and output

JF 2-14
Java Methods and Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Java Fundamentals

3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Download and install Greenfoot
Describe the components of the Greenfoot interactive
development environment
Create an instance of a class
Describe classes and subclasses
Recognize Java syntax used to correctly create a subclass

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Launch Greenfoot
To launch Greenfoot:
Double-click the Greenfoot icon on your desktop.
Select the Greenfoot program from your list of computer programs.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Greenfoot Textbook Scenarios


To become familiar with Greenfoot, download and run the
scenarios created by the authors of the Greenfoot textbook.
A scenario is a game or simulation implemented in Greenfoot.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Download the Greenfoot Textbook


Scenarios
Go to the Greenfoot textbook webpage:
http://www.greenfoot.org/book

Click the Book Scenarios link.


Save the zip file to a folder on your computer.
Extract the zip files to a folder on your computer.
Name this folder "Greenfoot Scenarios".
If your computer does not have zip file extraction software,
download free, open source software at 7zip.com.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Open a Scenario in Greenfoot


From the Scenario menu, select Open.
From the Greenfoot scenarios folder you created on your
computer, select the leaves-and-wombats scenario from the
chapter01 folder.
The scenario will open in a new window.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Execution Controls
Execution controls to run a scenario include:
Act: Runs all actions in the scenario once.
Run/pause: Runs all actions in the scenario repeatedly until Pause is
clicked.
Reset: Pauses the scenario or resets the scenario back to its starting
position.
Speed: Runs actions faster or slower.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Inherited Characteristics
In nature, a bee inherits some characteristics that are
common to all bees: six legs and two wings.
The bee may also inherit the characteristics of its breed that
gives it a specific color, shape and size.
In Greenfoot, a class, such as the Bee class, defines the
characteristics of all bee objects that act in the scenario, such
as how they look and ways they can act.
A class contains the specifications that define the appearance and
movement of an object. The class provides instructions to Greenfoot
for how to create and display instances when they are added to your
scenario.
JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Classes in Greenfoot
The class tells your scenario how its objects should look and
act when the scenario is run.
When you add a class to your scenario, it appears in the class
hierarchy (to the right of the world).
You can add as many instances of the class as you wish to the
scenario.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Superclass Types
Two types of superclasses appear in the Greenfoot class
hierarchy:
World:
Holds the subclasses that provide the background image for the scenario's
world.
Defines the size and resolution of the world.

Actor:
Holds the subclasses that produce the
instances that act in the scenario.

The overarching class of a group of classes is called a


superclass. In this example - World and Actor

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Subclasses
Subclasses are a specialization of a class.
For example, the Bee class is a subclass of the Actor
superclass. This subclass:
Inherits all of the properties of the Actor superclass, such as a predefined set of actions that Actor subclasses can perform.
Has properties specific to its subclass, such as the image that gives bee
objects their appearance.
Can receive new properties that the programmer creates specifically
for the subclass, such as images or actions.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Subclass Properties
A subclass has an "is-a" relationship to a superclass (Bee is a
subclass of the Actor superclass).
Properties can be modified (such as the class's name, image
to display, or actions to perform).
An arrow in the class hierarchy shows the subclass's
relationship to the superclass.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Steps to Create a New Subclass


Right click on the World or Actor superclass.
Select New subclass...
Name the class.
Select a class image from the menu for the subclass's
instances to display, then click OK.
The subclass will appear in the class hierarchy.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Steps to Create a New Subclass with an


Image Imported From Your Computer
Right click on the World or Actor superclass.
Select New Subclass...
In the New Class window, click the Import From File... button.
Select the image file to import from your computer.
Name the new subclass, then click OK.
The subclass with the new image
appears in the class hierarchy.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Steps to Create a New Subclass with an


Image Drawn in a Paint Program
Right click on the Actor superclass.
Select New Subclass...
In the New Class window, click the editor icon.
In the drop-down list that appears, select Create New Image.
Enter the name of the image file and dimensions. Click OK.
Draw the image in your computer's paint program, then save
it to your computer.
Create a new subclass, and import the image file. The new
subclass will be added to the scenario.
JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Compilation
Once a new subclass is created and displayed in the class
hierarchy, it has stripes across it.
Stripes indicate that compilation is required.
Compilation is required:
When the class's source code has been modified.
When a subclass or superclass is created or modified.
Compilation translates the source code into machine code that the
computer can understand. The striped appearance ensures that you
added the source code or class correctly before you proceed.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Compiling a Greenfoot Scenario


Click Compile.
Once compiled, the
stripes disappear.
You may then continue
programming or run
the scenario.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Save Multiple Versions of Scenarios


Save the scenario frequently as you work.
Each time you close Greenfoot, it saves your current work.
Save multiple versions of scenarios:
To return to an earlier version of a scenario.
To have multiple scenarios to work from.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Steps to Save a Scenario


In the Scenario menu, select Save As...
Save a copy to a folder on your computer.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Instances of a Class
The Bee class has characteristics such as movement, color,
and size.
A Bee that flies in a field, or rests in a flower, is a physical
object that is a unique instance of the Bee class.
An instance holds the characteristics of the class, but can be
manipulated and changed.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Greenfoot Instances
One or many instances of a class can be added to the
scenario.
Actor instances move and act in your scenario.
World instances provide the background for your scenario.

Instances can perform the behaviors written by the


programmer in the class's source code.
Instances are the objects from a class that act
in your scenario.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Steps to Add an Instance to a Scenario


Right click on the class.
Click the new [class name] option.
Drag the instance into the scenario with your cursor.
Program the instance to act by writing source code in the
class's Code editor.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Source Code
DNA gives humans certain characteristics, such as
appearance, mobility, and communication.
Like DNA, source code is written to tell the class how its
instances could act in the scenario.
Source code defines what all instances of each class are capable of
doing. The behavior of each instance is determined by the source
code of its class.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Steps to View a Class's Source Code


Right click on a class in the class menu.
Select Open Editor.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Code Editor
The Code editor displays the class's source code.
This is where instructions are programmed for how instances
of the class can act in the scenario.

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Terminology
Key terms used in this lesson included:
Class
Compilation
Instance
Source code
Subclass
Superclass

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Summary
In this lesson, you should have learned how to:
Download and install Greenfoot
Describe the components of the Greenfoot interactive
development environment
Create an instance of a class
Describe classes and subclasses
Recognize Java syntax used to correctly create a subclass

JF 3-1
Getting Started with Greenfoot

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Java Fundamentals

3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Define parameters and how they are used in methods
Understand inheritance
Describe properties of an object
Examine the purpose of a variable
Discuss programming concepts and define terminology

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Methods Example
In order to complete a task, such as math homework, there
are several subtasks:
Student completes the math homework.
Student goes to school.
Student submits the homework to their teacher.

Because of learned experiences in school, combined with preprogrammed abilities (such as thinking), the student is
capable of completing this task.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Methods
In programming, each object has a set of operations (or tasks)
it can perform.
Programmers write a program to tell an object how and when
to perform tasks, such as:
Command an object to perform an action.
Ask an object a question to learn more about what it does.
Methods are a set of operations or tasks that instances of a class can
perform. When a method is invoked, it will perform the operation or
task specified in the source code.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Inheritance
Greenfoot objects inherit the methods and properties of their
class and superclass.
For example, an Alligator instance would inherit the methods
of the Actor superclass and Alligator class.
Inheritance means that each subclass inherits its methods from its
superclass.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

View Inherited Methods in Object Menu


The object menu displays all of the methods that the instance
inherits from its class and superclass.
Right click on the instance to display the menu.
Inherited From Actor displays a list of the methods that the class
inherits from the Actor superclass.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to View Inherited Methods in the


Code Editor
Right click on a class (this example is the Spider).
Click Open Editor.
In the Code editor, select Documentation from the dropdown menu at the top right.
Scroll down to the Method Summary.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Method Summary
The method summary displays the class's inherited methods.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Method Components
A method has several components that describe the
operations or tasks it performs.
Return type: Specifies the type of data that the method returns.
Method name: Describes what the method does.
Parameter list: Information that goes into the method call.

Examples of methods:
void move(3)
int getX()

A method call commands the instance to perform an operation or


task in Greenfoot. Read the method to understand what operation or
task is to be performed.
JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Method Signature
The method signature describes the intentions of the
method.
It includes the following components:
Method name
Parameter list
void move(int)

Method
name

Parameter List
()

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Return Types
The return type is the word at the beginning of the method
that indicates what type of information a method call will
return.
There are two types of return types:
Void: No data return - Issues a command to the object.
Non-void: Returns Data - Asks the object a question.
void move(int)

Return
type

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Methods with Void Return Types


Methods with void return types issue a command that carries
out an action.
Includes the word "void".
Does not return information about the object.
Is used to make the object do something.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Invoking Methods with Void Return Types


You will invoke methods with void return types:
To precisely position objects in your initial scenario (the starting point
of the game).
To command objects to perform actions in your game.
Example of selecting
The move method

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Ask Objects Questions


As a programmer, you will ask objects questions by invoking
methods with non-void return types to learn what an object
can do, or has done in the past.
For example, in school, teachers ask students questions to
see if the students comprehend the material they learned in
class that day.
Students respond with answers to let the teachers know how
much they learned.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Methods with Non-void Return Types


Methods with non-void return types ask the object a
question.
The method signature does not include the word "void".
The method returns information about the object, but does not change
or move it.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Examples of Non-Void Return Types


Integer (displayed as int)
Refers to whole numbers
Asks the object: How many?

Boolean
Returns a true or false value.
Types of questions it may ask an object:
Are you touching another object?
Are you at the edge of the world?

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Method Parameters
Parameters provide methods with additional data to make an
object perform a task, when information is required to invoke
the method.
Parameters are defined by two components:
Parameter type
Parameter name
Parameters are used to command objects to move, or to tell objects
what type of response is expected when we ask an object a question.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Examples of Method Parameters


Integer (int): Enter or display numerical values.
Boolean: Display true or false values.
String : Enter or display text values.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Method Parameter Lists


Method parameter lists indicate whether the method
requires additional information to be invoked, and what type
of information.
Parameter lists display as data within parentheses.
They typically have two states:
Empty: No data expected to invoke the method (getRotation() method).
Non-empty: Have data and expect one or more parameters to invoke the
method
i.e. turn(int) method

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Object Properties
Object properties describe the instance's appearance and
abilities, such as:
Size
Color
Range of movements

Properties can be viewed and modified in the class's source


code.
Each time you create a new instance of an Actor such as Bee
it has its own properties.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Variables
A variable, or field, allows the instance to store information to
use immediately or later.
For example, object properties are variables that store
information about the instance, such as its position in the
world.
Instance variables are the memory that belong to the instance of the
class. That memory can be saved and accessed later as long as the
instance exists.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

View Instance Variables


Right click on an actor instance, then click Inspect to view the
instance's variables in the object inspector.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Programming Syntax
The source code specifies all of the properties and
characteristics of a class and its objects.
Write source code (also known as syntax) in the class's Code
editor to command objects in your scenario to act.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Display Class Source Code


From the world, right-click on a class and select Open Editor
to display the Code editor.
The source code displayed defines what objects in the class
can do.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Act Method
Whenever the Act or Run execution controls are clicked in the
environment, the object will repeatedly do what is
programmed in the act method.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Body of Act Method


The curly brackets and content within them are the body of
the method.
Here you can write code to instruct instances of the class to
act when the Act or Run buttons are clicked.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Act Method Example


Call the move and turn methods in the Act method to make
instances of the class move and turn.
Methods must be written correctly with no typos, missing
characters, or incorrect capitalization, or the source code
wont compile.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Invoke Methods in Act Method


To invoke methods in the Act method, write them in
sequence as follows:
Name of the method in lowercase characters.
Parentheses, with parameter list if required.
Semicolon, to end the statement.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Debugging Process in Greenfoot


Incorrectly written or missing characters in your source code
will trigger error messages.
When the Compile button is clicked, the compiler checks for
syntax errors in the source code.
If an error is found, an error message is displayed and must
be corrected by the programmer before the program will
work.
Greenfoot provides these error messages so its easier to correct
mistakes and learn from them.
Debugging is the process of finding and removing bugsor errorsin
a computer program.
JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Syntax Error Example


The move method is missing a semicolon.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Error Message Example


After the Compile button is clicked, an error message appears
at the bottom of the screen and the incorrect code is
highlighted.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Error Explanations
Click the question mark (?) to display a more detailed error
message that attempts to explain the error.
Not all error messages will be easy to understand.

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Terminology
Key terms used in this lesson included:
Debug
Inheritance
Instance variable
Method
Method call
Parameter
Return type
Method signature
Variable
JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Summary
In this lesson, you should have learned how to:
Define parameters and how they are used in methods
Understand inheritance
Describe properties of an object
Examine the purpose of a variable
Discuss programming concepts and define terminology

JF 3-2
Methods, Variables, and Parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

35

Java Fundamentals

3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Demonstrate source code changes to invoke methods
programmatically
Demonstrate source code changes to write an if decision
statement
Describe a method to display object orientation

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Source Code
Source code is the blueprint or map that defines how your
objects and program function.
It commands the objects in your scenario to move and
interact.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Code Editor
Source code is managed in the Code editor.
To view the Code editor, right click on any class in the
environment, then select Open editor from the menu.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Functions of the Code Editor


In the Code editor, you can:

Write source code to program instances of the class to act.


Modify source code to change an instance's behavior.
Review the class's inherited methods and properties.
Review methods created specifically for the class by the programmer
who wrote the source code.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Components of Source Code

Class Description

act() Method

Method Signature

Method Body

Comments

Documentation

Class Definition

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Class Description
The class description is a
set of comments that can
be modified to describe
the class.
This includes:
A description of what the
class does.
The name of the person who
authored the code.
The date the source code
was last modified.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Class Definition Components


The class definition includes:
Java keywords or reserved words.
The name of the class as defined by the programmer.
The name of the superclass that the subclass extends from.
Class name (Bee)
public class Bee extends Actor

Java keywords or
reserved words
(public, class)

Java keywords or
reserved words
(extends)

JF 3-3
Source Code and Documentation

Superclass

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Class Definition Example

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

act() Method
The act() method is the part of the class definition that tells
objects which methods to perform when the Act or Run
execution controls are clicked in the environment.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Defining Classes
The class definition defines:
Variables (or fields) that store data persistently within an instance.
Constructors that initially set up an instance.
Methods that provide the behaviors for an instance.

Use a consistent format when you define a class.


For example, define variables first, constructors second, and methods
third.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Method Signature
The method signature describes what the method does.
The signature contains a method name and parameter list.
Method name

Parameter list ()

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Comments
Comments describe what the source code does.
Do not impact the functionality of the program.
Start with a forward slash and two asterisks /** or simply a double
forward slash.
End /** comments with */
Written in blue font (in Greenfoot).

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Documentation
Documentation describes the properties of the class.
To view, select Documentation from the drop-down menu at
the top right of the Code editor.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Invoke Methods Programmatically


Methods must be invoked to command instances to act in
your game.
Invoke methods programmatically by writing them in the
body of the act() method in the space between the curly
brackets.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Method Call Components


Method call components:
Return type
Data type of return value
Void return types do not require variables nor return data.

Method name
Parameter list to indicate the type of arguments to invoke, if required.
Semicolon to mark the end of the method call.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Invoking Methods Example 1


Each method is written in the space between the curly
brackets.
Method name

public void act()


{
move(10);
turn(50);
}

Parameters
Semicolon

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Invoking Methods Example 2


The first method call is written into the body of the act()
method, ending with a semicolon.
Each additional method call is typed directly underneath,
until all methods are entered in the space between the curly
brackets.
Parameter - 3

Semicolon marks end of


programming statement
Method name

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Methods that Instruct Objects to Perform


Actions
Method Name

Description

void move(int distance)

Assigns the object a number of steps to


move, or the command to simply move
when the Act or Run buttons are clicked.

void turn(int amount)

Assigns the object a number of degrees


to turn.

void act()

Gives the object the opportunity to


perform an action in the scenario.
Method calls are inserted into this
method.

void setLocation(int x, int y)

Assigns a new location for this object.

void setRotation(int rotation)

Sets a new rotation for this object.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Ways to View a Class's Inherited Methods


View the Greenfoot Class Documentation.
Open Greenfoot.
Select Help.
Select Greenfoot Class Documentation.

View the Java Library Documentation.


Open Greenfoot.
Select Help.
Select Java Library Documentation.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Sequential Tasks
A single task, such as going to school, requires multiple subtasks:

Wake up
Take a shower
Brush your teeth
Get dressed

Within a sub-task, there could be more sub-tasks (walking to


school requires the left leg and right legs to move forward, in
order).

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Sequential Methods
Sequential methods are multiple methods executed by
Greenfoot in the order in which they are written in the
program.
These methods make it possible for an object to perform
sequential tasks, such as run and then jump, or play a sound
after something explodes.
Objects can be programmed to perform sequential methods
whenever the Act button is clicked.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

if-then Relationships
Many things around us have a cause and effect relationship,
or "if-then" relationship.
If your cell phone rings, then you answer it. If it doesn't ring, then you
do not answer it.
If a flower starts to wilt, then you give it water. If the flower looks
healthy, then you do not give it water.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

if Decision Statements
An IF statement is written to tell your program to execute a
set of programming statements only if and when a certain
condition is true.
if (condition)
{
instruction;
instruction;

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

if Decision Statement Components


The if statement contains a condition, which is a true or false
expression, and one or more method calls that are executed if
the condition is met.

Condition
Method calls

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

if Decision Statement Example


In the following example:
The left and right arrow keys on the keyboard make the object turn left
and right.
If the condition is false, the method calls defined in the IF statement
are not executed.
The move method is executed regardless of the IF statement.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

isKeyDown Method
The isKeyDown method is a pre-existing Greenfoot method
that listens to determine if a keyboard key is pressed during
program execution.
This method is called in a class using dot notation.
When a method is not in the class or inherited by the class you are
programming, specify the class or object that has the method before
the method name, then a dot, then the method name. This technique
is called dot notation.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Object Orientation in the Real World


As we move about the world we live in, it's important for us
to know our orientation, or sense of direction.
When you drive a car, you always need to know if your car is in the
correct lane of the road.
When a plane flies through the air, it needs to know where it's located
relative to other planes, so a collision doesn't occur.
When you enter your location on a map in a cell phone, you receive
coordinates that tell you where you are, and the address.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Display an Object's Orientation


Methods can tell us how an object is positioned in the world,
relative to itself and other objects.
You can invoke a method:
With a specific data type, such as boolean, to ask the object a question
about it's orientation.
In the environment to learn how the object is oriented in the scenario.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Methods that Return Information About an


Object's Orientation
Method Name

Description

int getRotation()

Returns the current rotation of the object.

World getWorld()

Returns the world that the object is currently in.

int getX()

Returns the x-coordinate of the object's current location.

int getY()

Returns the y-coordinate of the object's current location.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Steps to Invoke a Method that Displays an


Object's Orientation
Right click on the instance in the world.
Select Inherited from Actor to view its methods.
Invoke (select) a method with a specific data type to ask the
object a question about its orientation.
The method result will display. Note the value returned, then
click Close.

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Terminology
Key terms used in this lesson included:
Class description
Comments
if decision statements
Invoking a method
Object oriented analysis
Sequential methods

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Summary
In this lesson, you should have learned how to:
Demonstrate source code changes to invoke methods
programmatically
Demonstrate source code changes to write an if decision
statement
Describe a method to display object orientation

JF 3-3
Source Code and Documentation

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Java Fundamentals

3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Demonstrate program testing strategies
Recognize phases for developing a software application

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Program Testing Strategies


A programmer tests a program many times during the course
of its development to ensure it works properly.
Program testing strategies:
Test frequently after each method, or a sequence of methods, are
written.
Compile the program to ensure it is error-free. If errors appear, correct
them.
Run the program to observe how the methods make the objects move.
Continue to add methods and adjust as necessary.

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Compilation and Debugging


Every character in source code counts. One missing or
incorrect character could cause your program to fail.
In Greenfoot, compilation highlights syntax errors and what is
required to correct them.
This helps you develop good programming techniques.
Bugs are errors in the code of a computer program. To debug a
program, the programmer compiles the program and reads any error
messages that Greenfoot provides. Then, the programmer corrects
those errors in the syntax and re-compiles the program. Testing will
then move onto the logic in the code.

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Debug Your Program


Click Compile to compile the code.
If there are no errors, the message "Class compiled no
syntax errors" displays.
If there are errors, the incorrect syntax is highlighted and a
message attempts to explain the error.
Click the question mark icon to display additional information
about the error.

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Keys to Recognizing Java Syntax Errors

Locate the beginning and end of a method.

Ensure all beginning { and ending } braces exist.

Ensure all open ( and closed ) parentheses exist.

Ensure all lines of code end with a semicolon.

Ensure class names are spelled and capitalized properly.

Review all dot notation (i.e., System.out.println).

Ensure similar-looking characters are correct (number 1 versus letter i).

Ensure all string quotes are double " not single '.

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Auto-Layout
A useful function within the Greenfoot code editor is the
Auto-Layout feature.
You will find this automatically structures your code and is a
great tool to find where your missing brackets are!

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Phases to Develop an Application


Analyze the problem to solve or task to perform.
Design the solution, which is commonly a game in Greenfoot.
Develop the game in Greenfoot.
Test the game to ensure it works and meets the requirements
of your analysis and design.
Developing a game in Greenfoot follows the same steps as
developing a software application.

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Analysis Phase
In the analysis phase, determine what problem the game will
solve, or the task it will perform, using object oriented
analysis.
In object oriented analysis, Java programmers analyze a problem and
then create objects to build a system, or more specifically, to solve the
problem.

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Analysis Phase Tasks


Identify a problem to solve.
Write a brief statement of scope that states the type of
solution (game) that will solve the problem.
Gather the target audience's requirements. These are the
people who most likely will play your game.
Identify and describe objects in the game.
Physical objects (car, person, tree).
Conceptual ("non-physical") objects (timer that counts down time
remaining in the game).
Attributes of all objects, such as color, size, name, and shape.
Operations that the objects perform (move, turn, eat other objects).
JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Analysis Example
Analysis Item

Description

Problem domain

I want to create a game to teach students to control


a Bee with the cursor keys.

Game player's requirements

It should be easy for kids of all ages to play. It


requires the player to have a keyboard.

Objects

1 Bee object that will catch flies.


Multiple Fly objects.
1 Spider object which will catch flies and the Bee.
1 World with a light colored background.

Objects operations

Bee: Move, turn, and catch flies.


Fly: Randomly move around the screen.
Life count: Count down by 1 from 3 every time the
Bee is caught by a Spider.
Background: Do nothing.

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Analysis Pre and Post Conditions


Capture information to support testing for:
Item to Test

Example

Pre- and post game


conditions.

Variable initialized values versus final values after


program execution.

Anticipated run times and


comparison run rates given a
set of conditions.

Run rates can vary based on computer memory


size variance.

Expected results for


statement execution counts.

A loop counter of three will produce three new


variables.

Numerical representations
and limitations.

An integer's maximum value.

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Design Phase
The solution you design will be in the form of a Greenfoot
game that your target audience can play.
Design your game in a textual storyboard that plans the
algorithms, or methods, that objects will perform in response
to keyboard commands or mouse clicks.

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Textual Storyboard Example


This textual storyboard on the next slide describes a simple
game where you control a Bee to try and catch Flies while
avoiding a Spider.
The spider will also catch flies.
You will gain points for every Fly caught and lose a life every
time a Spider catches the Bee.
The game ends when you run out of lives.

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Textual Storyboard Example


When the Run button is clicked, the bee will continually move
forward.
The player uses the arrow keys on the keyboard to control the
bee's left and right movements.
When the Bee is in the same square as a randomly moving
Fly, it is then caught and removed from the game and another
Fly is added.
A Spider will move randomly around the screen. If the spider
catches a Bee then the user loses a life. If it catches a fly then
its removed from the game.
Game ends when the user has no lives remaining.
JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Development Phase
After you finalize your storyboard, develop your game in
Greenfoot.
Refer to your storyboard to determine the methods you need
to program.

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Testing Phase
After you write a section of code, compile it, then test it by
clicking the Run button in the environment.
Observe the game then revise the code as necessary.
For quality assurance purposes:
Have other people test your game and give you feedback.
Seek people who fit the target audience for your game.

Write test plans that:


Examine pre and post conditions.
Compare run time rates and execution counts.
Thoroughly test numerical representations and limitations.
JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Testing Numerical Representations and


Limits Example 1
For example, a banking solution requires precise rounding of
numbers.
This program could produce incorrect results if the rounding of a
number was not set to two digits after a decimal point.
The addition of a 1/2 of a cent multiplied by a million customers could
produce an expensive programming error.

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Testing Numerical Representations and


Limits Example 2
For example, an IF construct in a program expects a positive
value of 5 through 9 to then add that value to another
variable.
The program incorrectly feeds the variable a value of 2.
This causes the IF construct to fail and the variable expecting a
conditional change will not get the expected amount so the operation
of the data structure will be different.
This is an example of where the program will execute the result of the
conditional construct, even if it is incorrect.

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Terminology
Key terms used in this lesson included:
Bugs
Documentation

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Summary
In this lesson, you should have learned how to:
Demonstrate program testing strategies
Recognize phases for developing a software application

JF 3-4
Developing and Testing an Application

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Java Fundamentals

3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Create randomized behaviors
Define comparison operators
Create if-else control statements
Create an instance of a class
Recognize and describe dot notation

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

getRandomNumber Method
The getRandomNumber method is a static method that
returns a random number between zero and a parameter
limit.
This method is used to eliminate predictability in your
program.
Method signature:
public static int getRandomNumber(int limit)

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Dot Notation
New subclasses that you create do not inherit the
getRandomNumber method.
This method must be called from the Greenfoot class using
dot notation.
Example :
Greenfoot.getRandomNumber(20);

When you want to use a method but it is not inherited by the class
you are programming, specify the class or object that has the method
before the method name, then a dot, then the method name. This
technique is called dot notation.
JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Dot Notation Format


The format for dot notation code includes:

Name of class or object to which the method belongs


Dot
Name of method to call
Parameter list
Semicolon

className.methodName (parameters);
objectName.methodName (parameters);

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Dot Notation Example


The getRandomNumber method shown below:
Calls a random number between 0 and up to, but not including 15.
Returns a random number between 0 and 14.
Greenfoot.getRandomNumber(15);

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Greenfoot API
Reference the Greenfoot Application Programmers' Interface
(API) to examine additional methods to call using dot
notation.
The Greenfoot Application Programmers' Interface lists all of the
classes and methods available in Greenfoot.

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to View Methods in Greenfoot Class


In the Greenfoot environment, select the Help menu.
Select Greenfoot Class Documentation.
Click the Greenfoot class.
Review the method signatures and descriptions.

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Greenfoot API Interface

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Comparison Operators
Use comparison operators to compare a randomized value to
another value in a control statement.
The example below determines if the random number is less
than 20.
If it is, then the object turns ten degrees.
if (Greenfoot.getRandomNumber(100) < 20)
{
turn(10);
}

Comparison operators are symbols that compare two values.

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Comparison Operator Symbols


Symbol

Description

<

Less than

>

Greater than

<=

Less than or equal

>=

Greater than or equal

==

Equal

!=

Not equal

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Gaming Problem Solved with Random


Behavior
Problem:
A Fly object should move randomly so it is more challenging for the
keyboard-controlled object, a Bee, to catch it.

Solution:
The Fly should turn a small amount as it moves.
To code this solution, turn the Fly a random number of degrees, up to
20 degrees, 10% of the time as it moves.
if (Greenfoot.getRandomNumber(100) < 10)
{
turn(Greenfoot.getRandomNumber(20));
}

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Random Behavior Format


The programming statement below includes:
IF control statement with the getRandomNumber method.
Parameter limit of 100.
Comparison operator <.
Number 10 to limit the range of values to return to 0-9.

Method body with statement to indicate that the object should turn up
to 20 degrees if the condition is true.
if (Greenfoot.getRandomNumber(100) < 10)
{
turn(Greenfoot.getRandomNumber(20));
}

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Random Behavior Format


The problem with the previous example is that the fly always
turns in a clockwise circle. We can change this by modifying
the parameter in the turn method as shown below.
This will then generate a random number between -45 and
+44.
Remember a negative turn value rotates counter clockwise.
if (Greenfoot.getRandomNumber(100) < 10)
{
turn(Greenfoot.getRandomNumber(90)-45);
}

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Conditional Behavior
Instances can be programmed to perform specific behaviors if
a condition is not met, using an if-else statement.
For example, if an instance is programmed to turn 6% of the
time, what does it do the other 94% of the time?
An if-else statement executes its first code segment if a condition is
true, and its second code segment if a condition is false, but not both.

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

if-else Statement Execution

True

Evaluate
the
Condition

False

Execute ELSE
Statement

Execute IF
Statement

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

if-else Statement Format

if (condition)
{
statements;
}
else
{
statements;
}

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

if-else Statement Example


If a random number between 0-6 is selected, turn 10 degrees.
Otherwise, turn 5 degrees.
if (Greenfoot.getRandomNumber(100) < 7)
{
turn(10);
}
else
{
turn(5);
}

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Automate Creation of Instances


Using the World subclass, actor instances can be programmed
to automatically appear in the world when a scenario is
initialized.
In Greenfoot, the default behavior for instances is as follows:
The World subclass instance is automatically added to the environment
after compilation or initialization of the scenario.
The Actor subclass instances must be manually added by the player.

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Automate Creation of Instances in a


Scenario
Problem:
When a Greenfoot scenario (such as leaves and wombats) is started,
the instances must be manually added by the player to play the game.

Solution:
Program instances to be automatically added to the world when the
scenario is initialized.

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

World Class Source Code


To understand how to automate creation of Actor instances,
you need to understand how the World class source code is
structured.
The World constructor is used to automate creation of Actor
instances when the scenario is initialized.
Class header

Comment

Constructor
JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Constructors
Constructors:
Define the instance's size and resolution.
Have no return type.
Have the same name as the name of the class. For example, a World
constructor is named World.
A constructor is a special kind of method that is automatically
executed when a new instance of the class is created.

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

World Constructor Example


The example constructor below constructs the World
superclass instance as follows:
Size: x = 600, y = 400.
Resolution: 1 pixel per cell.
Keyword super in the constructor's body calls the superclass World
constructor for each instance of the BeeWorld subclass.
public BeeWorld()
{
super(600, 400, 1);
}

Size

Resolution

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Automatically Create Actor Instances


This World constructor adds a new Bee object at specified X
and Y coordinates using the addObject method.
public BeeWorld()
{
super(560, 560, 1);
addObject (new Bee(), 150, 100);
}

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

addObject Method
The addObject method is a World class method that adds a
new object to the world at specific x and y coordinates.
It includes:
Keyword new to tell Greenfoot to create a new object of a specific
class.
Method parameters:
Named object from Actor class.
Integer value of X coordinate.
Integer value of Y coordinate.

Method definition:
void addObject(Actor object, int x, int y)

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

new Keyword
The new keyword creates new instances of existing classes.
It starts with the keyword new, followed by the constructor to
call.
The parameter list passes arguments (values) to the constructor that
are needed to initialize the object's instance variables.
The default constructor has an empty parameter list and sets the
object's instance variables to their default values.
new ConstructorName()

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Greenfoot World Coordinate System


0

Y
JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Add Objects Using World Constructor


Example

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Save the World


Greenfoot has an additional way to setup the initial
placement of Actors using "Save the World"
We can place our actors around the world manually in an
initial position.
Then select Controls -> Save the World

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Save the World


This creates a new method in your world called prepare() and
creates a call to this within the constructor.
The prepare method will create instances of the actor then
add them to the world at the location you placed them.
This is useful if you have lots of objects to place.

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Terminology
Key terms used in this lesson included:
Comparison operators
Constructor
Dot notation
new Keyword

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Summary
In this lesson, you should have learned how to:
Create randomized behaviors
Define comparison operators
Create if-else control statements
Create an instance of a class
Recognize and describe dot notation
Save the World feature

JF 3-5
Randomization and Constructors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Java Fundamentals

3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Describe effective placement of methods in a super or
subclass
Simplify programming by creating and calling defined
methods
Handling collisions

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Efficient Placement of Methods


At times, many lines of code are required to program a
behavior.
For example, you may want to program an instance to eat
other objects, or turn when it reaches the edge of the world.
Define new methods to save time and lines of code.
Define a new method for an action below the act method.
Call the new method in the act method or within another method.
Define the method in the superclass if you want its subclasses to
automatically inherit the method.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Defined Methods
Defined methods are new methods created by the
programmer.
These methods:
Can be executed immediately, or stored and called later.
Do not change the behavior of the class when stored.
Separate code into shorter methods, making it easier to read.
Defined methods create a new method that a class did not already
possess. These methods are written in the class's source code below
the act method.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Define a New Method


Select a name for the method.
Open the Code editor for the class that will use the method.
Add the code for the method definition below the act
method.
Call this new method from the act method, or store it for use
later.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Define a New Method


We could for example add our Bee movement code in act() to
a new method.
This helps keep the code in act to a minimum and keep its
actions clearer.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Turn at the Edge of the World


Problem:
Instances stop and are unable to move when they reach the edge of
the world.
Instances should turn and move when they reach the edge of the
world.

Solution:
Create a subclass of Actor that defines a method that can detect if the
object is at the edge of the world and to turn appropriately.
Call the new methods in the subclasses that should be able to turn and
move at the edge of the world.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Test if at edge of World


Greenfoot has a method in the Actor class called isAtEdge().
This returns true if the actor is at one of the edges.
We could use this to detect and then turn actors around
rather than them hover at one of the edges.
If our program required to know which edge an actor was at
we would have to either define a method to return the side
we are touching, or 4 separate methods, one for each side.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Test an Object's Position in the World


To test if an object is near the edge of the world, this
requires:
Boolean expressions to express if a condition is true or false.
Example We could rotate an instance by 180 degrees if its at the edge
of the world.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Logic Operators
Logic operators can be used to combine multiple boolean expressions
into one boolean expression.
Logic Operator

Means

Definition

Exclamation Mark (!)

NOT

Reverses the value of a boolean expression (if b


is true, !b is false. If b is false, !b is true).

AND

Combines two boolean values, and returns a


boolean value which is true if and only if both of its
operands are true.

OR

Combines two boolean variables or expressions


and returns a result that is true if either or both of
its operands are true.

Double ampersand
(&&)

Two lines (II)

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Create the Bug Superclass


Before creating the defined methods, create a new subclass
of the Actor class named Bug.
This class has no image and will not have instances that act in
the scenario, but will hold some defined methods that other
subclasses will inherit.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Create the Bug Subclasses


We could recreate our Spider and Fly by right clicking on Bug,
and selecting new Subclass.
But as we have previously created them we can modify our
Spider and Fly source code to extend from Bug rather than
Actor.
When you click compile Greenfoot will update the class
structure.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Define turnAtEdge Method in Superclass


Open the Code editor for the Bug class. Write the code for
the turnAtEdge method, below the act method.
Compile the code and then close the Code editor.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Call turnAtEdge Method in Subclass


Open the Code editor for the Fly subclass.
Add a call to the method turnAtEdge within the Act method.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Define atRightEdge Method in Bee class


Open the Code editor for the Bee class.
Write the code for the atRightEdge method, below the act
method.
Compile the code and then close the Code editor.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Define atBottomEdge Method in Bee Class


Open the Code editor for the Bee class.
Write the code for the atBottomEdge method, below the act
method.
Compile the code and then close the Code editor.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Methods in atRightEdge and atBottomEdge


The methods used in atRightEdge and atBottomEdge include:
getX: An Actor method that returns the x-coordinate of the actor's
current location.
getY: An Actor method that returns the y-coordinate of the actor's
current location.
getWorld: An Actor method that returns the world that this actor lives
in.
getHeight: A GreenfootImage class method that returns the height of
the image.
getWidth: A GreenfootImage class method that returns the width of
the image.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Call Method in Class


Open the Code editor for the Bee class.
Create an IF statement that calls the atRightEdge and
atLeftEdge method as a condition in act.
If the Bee is at the left it will re-appear on the right and vice
versa.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Call Method in Class


Compile the code and run the scenario to test it.
Complete the IF statement for the atTopEdge and
atBottomEdge.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Class Documentation
The Bug class documentation shows the new method after its
defined.
All subclasses of the Bug superclass inherit this method.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Collisions
Most game projects will usually have to detect when two
actors touch which is usually called a collision.
In GreenFoot there are multiple ways to detect this.
Some of these are

isTouching()
getOneIntersectingObject(Class)
getOneObjectAtOffset(Class)
getIntersectingObjects(Class)
getNeighbours(distance,diagonal)
getObjectsAtOffset(dx,dy,Class)

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Collisions
Method

When To Use

isTouching

When you simply want to detect a collision


with an object

getOneIntersectingObjec
t

When you want to return a reference to the


object you have collided with. This is
normally used if you wish to perform an
action on the collided object.

getOneObjectAtOffset

Same as getOneIntersectingObject except


that you can change where the collision will
be detected relative to the current object.
So you could have the collision detected
before it happens. i.e. to stop an actor
walking into a wall.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Defined Method to Remove Objects


You can write code in your game so a predator object is able
to eat prey objects.
Create a defined method in the act method of the Bee
superclass called catchFly to enable us to remove flies that we
catch.
To create this defined method we are going to use the
simplest collision detection isTouching.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Define catchFly Method


Define the catchFly Method in the Bee class.
This method detects a collision with a fly and then removes it.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Define catchFly Method - Alternative


Alternatively we could have used getOneIntersectingObject
and accessed a reference to the actor before deleting it.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Call catchFly in Act Method


Call the new catchFly method in the Bee's act method.
Run the scenario to test the code.

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Terminology
Key terms used in this lesson included:
Defined methods
Collisions

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Summary
In this lesson, you should have learned how to:
Describe effective placement of methods in a super or
subclass
Simplify programming by creating and calling defined
methods

JF 3-6
Defining Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Java Fundamentals

3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Write programming statements to include sound in a program
Write programming statements to include keyboard
movements in a program
Write programming statements to include mouse interaction
in a program
Write programming statements to retrieve information from
the user.

JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Keyboard Controls
Games are controlled by a human or computer player using a
remote control or keyboard controls.
To make a scenario behave like a true game, program
statements that include keyboard controls so the player can
control one or more objects in the game.

JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

The isKeyDown Method


The isKeyDown method checks if a key on the keyboard has
been pressed.

Located in the Greenfoot class.


Is a Static method (associated with a class).
Returns true or false value.
Expects a String argument in the parameter list.
Can be used as a condition in an IF statement.

Method signature:
public static boolean isKeyDown(String key)

JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

String Parameter in isKeyDown Method


A String is a piece of text (word or sentence) written in
double quotes.
For example:
"This is a String"
"A"
"name"

The String parameter in the isKeyDown method expects the


name of the key to press on the keyboard.
Find a key's name by looking at your keyboard.
Sometimes the name isn't evident (right cursor key is called "right").
JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Using the isKeyDown Method Example


This code in the act method uses the left and right keys on
the keyboard to allow the player to control the Bee object's
direction as it moves.

JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Include Sound in Your Game


Sounds can enhance your game.
Give feedback sounds to the player when they win, lose, or achieve
minor victories throughout the game.
Include background sounds in a game.

The playSound method is used to play sounds in a game.


Method is located in the Greenfoot class.
Parameter list expects the name of a sound file (as String) as an
argument.
The method does not return data.

JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Sound Example
The playSound method is called using dot notation in the
body of the catchFly method.
Whenever the Bee object catches a fly, it makes a sound.

JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Record Original Sounds


In the Controls menu in the environment, select Show Sound
Recorder.
Press Record, then talk into your computer's microphone to
record sound.
Press Stop Recording when finished.
Press Play to play back the sound.
Re-record if necessary.
Enter a file name, then click Save to save the file to your
scenario.
The file is now ready to reference in your code.
JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Greenfoot Sound Recorder Display

JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Using the Mouse


Greenfoot allows multiple input methods rather than just
using the keyboard.
There is also the ability to use controllers, mice and other
input devices.
You may wish to use a mouse within the scenario you are
building, rather than the keyboard.
The Greenfoot class has a number of methods that allow you
to get information on the mouse actions.
These include:
getMouseInfo(), mouseClicked(), mouseDraggedEnded(),
mouseDraged, mousePressed()
JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Using the Mouse Example


The scenario we are building does not use mouse controls,
but lets show an example.
If we had an actor called Spider and we wished to detect
when the mouse was clicked on an instance of it we would
do the following:
if (Greenfoot.mouseClicked(this)) {
//do something
}

JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Using the Mouse Example


If we wanted to detect if the mouse was clicked elsewhere
we would use the MouseInfo class.
Below we see code that would move the current instance to
the location where the mouse was clicked.
MouseInfo mouse = Greenfoot.getMouseInfo();
if(mouse!=null){
if (mouse.getButton() == 1) {
setLocation(mouse.getX(),mouse.getY());
}
}

JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Obtaining Keyboard Input From The User


There may be a point in your program that you wish to gain
input from the user.
i.e.
Asking for their name
Asking for a starting speed etc

From version 2.4.1 of Greenfoot this is now possible through


the Greenfoot method called ask
String Greenfoot.ask(String message)

JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Obtaining Keyboard Input From The User


The ask method will display the message as a prompt and
obtain the result as a string.
i.e. Let us ask the user their name and store it in the variable
name.
While Greenfoot is waiting for your response it will pause the
world and its actors.
String name = Greenfoot.ask("Please input your name: ");

Would produce

JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Terminology
Key terms used in this lesson included:
Keyboard control
Play Sounds
Mouse Interaction
Ask

JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Summary
In this lesson, you should have learned how to:
Write programming statements to include sound in a program
Write programming statements to include keyboard
movements in a program
Write programming statements to receive the mouse state.
Write programming statements to retrieve a response from
the user.

JF 3-7
Sound and Keyboard Control

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Java Fundamentals

3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Construct a world object using a constructor method
Create an object using a constructor
Write programming statements to use the new keyword
Define the purpose and syntax of a variable
Recognize the syntax to define and test variables
Write programming statements to switch between two
images
Write programming statements to end a game
JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Constructors
When a new World subclass is created and compiled,
Greenfoot executes a constructor that creates an instance of
it to display in the scenario.
Constructors set up the instance and establish an initial state,
such as the size and resolution of the instance.
Constructors have no return type.
Their name, immediately following the word "public," is the same as
the class in which they are defined.
Constructors are special methods that are executed automatically
whenever a new instance of the class is created.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Constructor Parameters
A constructor's parameters allow an instance's initial values
to be passed into the constructor.
These parameters:
Are only available to the instance created by the constructor.
Have a restricted scope limited to when the constructor is declared.
Have a restricted lifetime limited to the single execution of the
constructor.
Disappear once a constructor is finished executing.
Are valid variables as long as the instance exists.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Constructor Example
This constructor in the World subclass uses the super()
keyword to pass the world's height, width and resolution
values to the instance.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Parameters Example
To change the size of the game board, modify the arguments
in the parameter of the constructor.
This example makes the world square instead of rectangular
by changing the x coordinate limit to 400.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Automatically Create Actor Instances


Write code in the World constructor to automatically add
Actor instances to the game when the scenario is initialized.
This eliminates the need for the player to have to manually
add instances before the game starts.
For example, in a matching game, the cards should
automatically display in the scenario when the game starts.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Code to Automatically Create Instances


The code in the World constructor includes the following
components:
super() statement with the size of the world as arguments.
addObject() method with the following arguments:
Keyword new, followed by the class name, tells the constructor that a new
instance of that class should be added.
X and Y coordinates where the new instance should be positioned in the
world.
public BeeWorld()
{
super(560, 560, 1);
addObject (new Bee(), 150, 100);
}

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Greenfoot Actor Instances


Alternating between two images that look slightly different
gives an instance the appearance of movement.
Greenfoot Actor instances:
Receive and hold an image from their class.
The image was assigned to the class when the class was created.

Have the ability to hold multiple images.


Can be programmed to change the image they display at any time.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

GreenfootImage Class
The GreenfootImage class enables Greenfoot actors to
maintain their visible image by holding an object of type
GreenfootImage.
This class is used to help a class obtain and manipulate
different types of images.
Images that this class will use must pre-exist in the scenario's
Images folder.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Constructor to Obtain New Image Object


Create a constructor that retrieves a new image object from a
file when creating an instance of a class.
The example constructor below creates the new image and
attaches it to the Actor class.
Image File Name as
Arguments in Parameter
List

new Keyword
setImage(new GreenfootImage("bee.png"));

setImage Method

GreenfootImage Class

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Assigning a New Image to a Class


The statement below creates the new image object from the
named image file.
When inserted into the class's source code, this image object
is ready for the class to use.
The statement is executed as follows:
The GreenfootImage object is created first.
The setImage() method call is executed, passing the newly-created
image object as an argument to the parameter list.
setImage(new GreenfootImage("bee.png"));

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Assigning an Image Example


The setImage() method assigns the image in the file
"bee.png" to the Actor class.
Each time an instance of this class is added to the scenario, it
displays the "bee.png" image.
Image file name as
argument.

Creates the new


image.
setImage(new GreenfootImage("bee.png"));

Allows image object


to be used by Actor class.
Expects image
as parameter.

Image from
Greenfoot class.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Why Instances Hold Multiple Images


You may want an instance to hold and access multiple
images:
To appear to change color.
To appear to change from one type of object to another. For example,
magically change from a rabbit to a tortoise.
To appear to move:
To walk: Change from an object with left leg extended, to one with right leg
extended.
To flip cards: Change from a blank card to a non-blank card.
To fly: Change from outstretched wings to folded wings.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Accessing Multiple Images


For example, an instance could access two images, each with
a slightly different wing position, so the instance flaps its
wings as it moves.
To achieve this motion:
Create two images of the instance, each with slightly different wing
positions.
Store the two images in the instance, so they can be accessed
repeatedly as the object moves.
Code the class to alternate between the two images that are displayed.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Variables
Use class variables to store the two image objects.
This allows the class to easily access them for use within the
instances.
A variable is declared in a class. It is used to store information for later
use, or to pass information. It can store objects or values.
Object 1

Variable 1

Object 2

Variable 2

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Variable Format
A variable's format includes:
Data type: What type of data to store in the variable.
Variable name: A description of what the variable is used for so it can
be referred to later.
private variable-type

variable-name;

In this example, the variable name is image1 and the variable


type is GreenfootImage.
private GreenfootImage image1;

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Declaring Variables
Declare variables before the constructors and methods.
The format for declaring a variable includes:
Keyword private to indicate that the variable is only available within
the Actor class.
Class to which the image belongs.
Placeholder for the variable into which the image will be stored.
Variables

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Assignment Statements
An assignment is needed to store objects in a variable.
When an object is assigned to a variable, the variable
contains a reference to that object.
An assignment statement:
Stores the object or value into a variable.
Is written with an equals symbol.

Format:
variable = expression;

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Assignment Statement Components


An assignment statement includes:
Variable: Name of variable to store object or value.
Equals symbol, which is the assignment symbol.
Expression:
Name of object or value to assign.
An instruction that the object or value is new.
The class to which the image belongs.

Example:
image1 = new GreenfootImage("bee.png");
image2 = new GreenfootImage("bee2.png");

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Initializing Images or Values


Initializing is the process of establishing the instance and its
initial values.
When the class creates new instances, each instance contains
a reference to the images or values contained in the
variables.
Guidelines:
Signature does not include a return type.
Name of constructor is the same as the name of the class.
Constructor is automatically executed to pass the image or value on to
the instance when an instance of the class is created.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Actor Constructors Example


The following actor constructor tells Greenfoot to
automatically create a new Bee instance and initialize, or
assign, two variables to the instance.
The last line of the constructor, setImage(image1), indicates
that the first variable should display when the instance is
added to the scenario.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Test Values of Variables


Once the class has initialized the two variables with the
images, program the instance to automatically switch the
image it displays as it moves.
As these images alternate with each movement, it makes the
instance appear more animated.
It is possible to program the switch between images without
having to write many lines of code that associates each image
to every single movement.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Write Actions in Pseudocode


Identify the actions to program by writing them in
pseudocode.
Pseudocode expresses the tasks or operations for the
instances to perform in a mix of Java language and plain
English words.
This helps to better understand what behaviors the instances
should perform before writing the real code.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Pseudocode Example
image1 is displayed when the instance is created.
When Bee makes its next movement, image2 should be
displayed, and vice versa.
This is expressed as an if-else statement.
if (current image displayed is image1) then
use image2 now
else
use image1 now

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

'==' Operator
The programming statements that instruct the instance to
alternate between images contains:
if-else statement
'==' operator (two equals signs)

The '==' operator:


Is used in an if statement to test whether two values are equal.
Compares one value with another.
Returns a boolean (true or false) result.

Remember that '=' is the assignment symbol, not the symbol


to test whether two values are equal.
JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Components of if-else Statement


Components of the if-else statement:
Method getImage receives the instance's current image.
The '==' operator checks that the value the instance displayed is equal
to image1.
if equal, then display image2.
else, display image1.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

if-else Statement Example


The if-else statement below is written in the act method to
make the instance alternate the display of two images as it
moves forward.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

if-else Statement Example


We will also move the animation code away to its own
method to keep the code cleaner.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

End the Game


The Greenfoot class has a stop() method that you can use to
end your game at a point that you designate.
You may want to end the game when:
The player achieves a milestone.
Time runs out on the clock.
The instance touches a certain coordinate or object.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Example Bee Game


Example game:
The player decides how many times the Bee is caught by the Spider
object to end the game.
When the game ends, a sound plays, "Game Over".

Game specifications:
Create and initialize variables to store lives and score.
Provide a count of the total Flies eaten (score).
Enter the stop method to stop the game when the player's lives
reach 0.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Find Stop Method in Greenfoot API


Go to the Help menu and select Greenfoot Class
Documentation.
Find the stop() method in the Greenfoot API.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Write Stop Method in Source Code


At the point that the game should end, write the method as
follows into the source code.
Dot notation is used to call the method.
Greenfoot.stop();

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Assign Variables to Instances Example


Bee must catch a number of Fly objects to increase the score.
The Bee will also lose a life if caught by the spider.
The variables are defined before the constructors and
methods.
The Bee constructor assigns the variables to the instances it
produces.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

35

catchFly Defined Method Example


The catchFly() defined method is written below the act()
method to tell the Bee to catch fly objects.
We will add one to the score variable for every Fly that is
eaten.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

36

Assign Variables to Instances Example 2


If the Bee comes into contact with the spider, then it should
loose a life.
We will also re-position the Bee to the top left.
We will extend the Bee class by adding a new method
caughtBySpider() and adding a call to this in the act() method.
We will then test if the user has no more lives and stop the
game.

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

37

Showing Text
Sometimes we want to keep the user of an application
informed on particular aspects of their interaction such as
lives, score or cards left.
Greenfoot again has a number of ways to achieve this.
The simplest is by using the World method showText()

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

38

Update catchFly Method


We are going to add code to the method catchFly() to
increment the score field and then display the result to the
screen.
We have also moved the update score to its own method and
called it within catchFly().

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

39

Terminology
Key terms used in this lesson included:
Constructor
Defined variable
Pseudocode

JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

40

Summary
In this lesson, you should have learned how to:
Construct a world object using a constructor method
Create an object using a constructor
Write programming statements to use the new keyword
Define the purpose and syntax of a variable
Recognize the syntax to define and test variables
Write programming statements to switch between two
images
Write programming statements to end a game
JF 3-8
World, Animation, and Game End

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

41

Java Fundamentals

3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Define abstraction and provide an example of when it is used
Define casting

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Abstraction
You can program a new instance to perform a single, specific
task, such as play a sound when a specific keyboard key is
pressed, or display a set of questions and answers every time
a game is started.
To create programs on a larger scale, for example one that
creates 10 objects that each perform different actions, you
need to write programming statements that let you
repeatedly create objects that perform different tasks, by just
providing the specifics for the differences.

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Abstraction Example
For example, if you are going to create 10 objects
programmatically, all placed in different locations, it is
inefficient to write 10 lines of code for each object.
Instead, you abstract the code and write more generic
statements to handle the creation and positioning of the
objects.

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Abstraction Principle
Abstraction aims to reduce duplication of information in a
program by making use of abstractions.
The abstraction principle can be a general thought such as
"don't repeat yourself."
For example, you want to create a game board that has
blocks, trees, sticks, and widgets.
You do not need to write repetitive programming statements to add
each of these items.
Instead, you can abstract the procedure to simply add objects to a
game board in a specific location.

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Abstraction Pseudocode Example


For example, when you add a Fly to the World it will also have
a maximum speed that it can move and an initial direction.
Your code will add a Fly and specify the maximum speed it
can move and the starting direction.
Here is the pseudo code:
Create new Fly (4,90)
Create new Fly (2,120)
Create new Fly (3,270)

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Abstraction Pseudocode Example


Imagine the code needed for 300 Fly images.
To implement abstraction, create a method that creates a new object
that is positioned where needed and displays the appropriate image.
Call the method: newObject (image, position)

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Abstraction Techniques
Abstraction occurs many ways in programming.
One technique is to abstract programming code using variables and
parameters to pass different types of information to a statement.
Another technique is to identify similar programming statements in
different parts of a program that can be implemented in just one place
by abstracting out the varying parts.

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Abstraction Techniques Example


For example, in a game where you catch other objects you
could increase the score by a different value depending on
what object was caught.
You could use abstraction by having an event increase the
score by using a parameter rather than a set value.

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Constructor Using Variables


In this example, the Fly has a variable defined to store the
current speed.
The constructor randomly generates a number up to the
maximum speed passed in via the parameter.
We also setup the initial rotation of the Fly.

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Constructor Using Variables


The randomMovement() method that moved the fly at a
constant speed of one with move(1) is updated to use the
instance variable speed.
move(speed)

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Programming to Place Instances


After speed and direction variables are defined in a
constructor, write programming code to automatically add
instances of the class to the world.
The following programming statement added to the
BeeWorld class:
Creates a new instance of Fly each time BeeWorld is re-initialized, with
a specific speed and direction.
Places the instance in BeeWorld at the specific x and y coordinates.
addObject (new Fly(2, 90), 150, 150);

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Constructor Example
Examine the addObject() statements in the BeeWorld
constructor when adding a new Fly.

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Abstract Code to a Method


You can anticipate abstraction during the design phase of a
project, or you can examine programming code to identify
statements that would benefit from abstraction.
Often times you will recognize an opportunity to abstract
programming statements when writing lines of code that
appear repetitive.

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Abstract Code to a Method Example


Examine the code below and on the following slide.
import greenfoot.*;
public class BeeWorld extends World
{
/**
* Constructor for objects of class BeeWorld.
*
*/
public BeeWorld()
{
super(600, 400, 1);
addObject (new Fly(2, 90), 1, 200);
addObject (new Fly(1, 180), 200, 10);
addObject (new Fly(3, 270), 300, 50);
addObject (new Fly(2, 190), 150, 110);
addObject (new Fly(3, 290), 130, 120);
addObject (new Fly(2, 50), 5, 10);
addObject (new Fly(1, 0), 200, 10);
addObject (new Fly(2, 30), 300, 110);
addObject (new Fly(2, 190), 150, 110);
addObject (new Fly(3, 290), 130, 120);
}
}

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Abstract Code to a Method Example


import greenfoot.*;

// (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class BeeWorld extends World


{
int currentMaxSpeed = 2;
public BeeWorld()
{
super(600, 400, 1);

for (int i=0; i<10; i++) {


int direction = Greenfoot.getRandomNumber(360);
int xcoord = Greenfoot.getRandomNumber(600);
int ycoord = Greenfoot.getRandomNumber(400);
addObject (new Fly(currentMaxSpeed , direction),xcoord,ycoord);
}

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Simple Abstraction of Code


What if you had little knowledge of Greenfoot or
programming, and wanted to create a game to move a baby
around the screen?
You could simplify how to move an Actor object around the screen by
creating a simple set of movement methods: moveRight(), moveLeft(),
moveUp() and moveDown().
This provides a simpler abstraction than the standard Greenfoot API
with its built-in setLocation() and getX()/getY() methods.

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Create Baby Subclass


Create a subclass of the Actor class called Movement that
would allow the player to tell the Baby actor to move in a
desired direction.
Add the following code to Movement which will set the
amount of movement each time a move is required.
import greenfoot.*;
// An actor superclass that provides movement in four directions.
public class Movements extends Actor {
private static final int SPEED= 4;
}

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Create Movement Methods for Baby


Subclass
Then, add the following movement methods:
These methods simplify and abstract the Greenfoot API of
getX()/getY().
public void moveRight()
{
setLocation ( getX() + SPEED, getY() );
}
public void moveLeft()
{
setLocation ( getX() - SPEED, getY() );
}
public void moveUp()
{
setLocation ( getX(), getY() - SPEED);
}
public void moveDown()
{
setLocation ( getX(), getY() + SPEED);
}
JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Code the act() Method


Code the act() method of the Baby Actor class so that its
instances move when the arrow keys are pressed.
This abstraction hides and automates the more complex
code, only showing moveLeft(), moveRight(), etc.
public void act()
{
if (Greenfoot.isKeyDown("left") )
{
moveLeft();
}

if (Greenfoot.isKeyDown("right") )
{
moveRight();
}

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Accessing Methods in Other Classes


Sometimes we want to access methods and properties in
other classes.
During a collision we can gain a reference to the collided
object by using a method like getOneIntersectingObject().
We also have the option of calling the World method that
would return all objects and then locating the one we want.
But what happens if we want to access another actor or
method outside of a collision or we don't want to iterate
through all objects?

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Extending the BeeWorld Class


We could have kept the score in the BeeWorld class.
Then created methods to read and update the score.
This would then allow easy updating of score from any actor.

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Accessing Other Objects Methods


In the Bee class we could access the score method by using
the getWorld() method. You might try:
World myworld = getWorld();
myworld.updateScore();

But this will produce an error because getWorld() return type


is World and World does not contain a method for
updateScore().
Although our BeeWorld is a type of World, Java will still check
the methods of World and if the method is not there, an error
is produced.
For this example, we will use a cast.
JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Casting
Casting is when we want to tell the Java compiler that a class
we are accessing is really another, more specific type of class.
In our previous example we want to tell the compiler that the
World class is really a BeeWorld class.
To do this we cast it. So
World myworld = getWorld();
myworld.updateScore();

Becomes
BeeWorld myworld = (BeeWorld)getWorld();
myworld.updateScore();

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Accessing Other Actors


Accessing other actors outside of collisions can be done in a
similar manner to accessing methods.
Create a private field and a public method to return it.

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Accessing Other Actors


To gain access to this method we would do the following.
In this example the Spider would now move straight for the
Bee.

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Terminology
Key terms used in this lesson included:
Abstraction
Casting

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Summary
In this lesson, you should have learned how to:
Define abstraction and provide an example of when it is used
Define Casting

JF 3-9
Abstraction

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Java Fundamentals

3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Create a while loop in a constructor to build a world
Describe an infinite loop and how to prevent one from
occurring
Use an array to store multiple variables used to create a
world
Create an expression using logic operators
Describe the scope of a local variable in a method

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Using Loops
Writing programming statements in the World constructor is
an efficient way to create new instances with parameters
passed to them.
However, a more efficient way to create multiple instances is
to use a loop.
A loop is a statement that can execute a section of code multiple
times. There are several types of loops in Java programming.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

while Loop
The while loop executes a statement or set of statements a
number of times while a condition is true.
For example, with a while loop, you can:
Create 50 instances at once.
Execute a method 10,000 times.
Create an instance every time until the "s" key is pressed.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

while Loop Components


Components of a while loop:
Java keyword while
Condition in parentheses
One or more statements
while (condition)
{
statement;
statement;
}

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Control Execution of while Loop


Components to control how many times the while loop is
executed:
Loop variable: A counter that tells how many times to execute the loop
(often named i)
Control operators
Local variable

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Local Variables
A local variable is often used within loop constructs.
While it is similar to a field, it is different because:
It is declared inside the method body, not at the beginning of a class.
It cannot have a visibility modifier (public or private) in front of its
definition.
It exists only until the current method finishes running, and is then
erased from memory.
A local variable is a variable declared inside the body of the method
to temporarily store values, such as references to objects or integers.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Declare a Local Variable


To create a while loop, first declare the local variable and
assign it a value.
To declare a local variable:
Declare the variable type (integer or object reference).
Name the variable.
Initialize the variable to a number (usually zero).

Example:
int i = 0;

Variable Type
(Integer)

Variable Value (0)


Variable Name (i)

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Create the Condition


Beneath the initialized variable, create the condition that
specifies how many times the body of the loop should be
executed.
The loop will continue as long as this condition is true.
Use a control operator to stop the execution when it reaches
the number of executions you specified.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Create the Condition


Example:
Execute the body of the loop while the number of executions is less
than, but not equal to, 10.
When the loop has been executed 10 times (0-9), it stops.
int i = 0;
while (i < 10){
<code to repeat goes here>
}

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Insert the Statements to Execute


In brackets, insert the statements to execute.
Example:
Add 10 new Fly objects with a specific speed and direction.
int i = 0;
while (i < 10)
{
addObject (new Fly (2, 90),150, 100);
}

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Increment the Loop Variable


Increment the loop variable as follows:
Insert a statement at the end of the loop body to increase the loop
variable by 1 each time the loop is executed.
Use closed brackets to end the statement.

This will change the variable with each loop to ensure it does
not loop indefinitely.
int i = 0;
while (i < 10)
{
addObject (new Fly (2, 90),150, 100);
i = i + 1;
}

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

while Loop Example


When inserted into the BeeWorld constructor it creates 10
Flies when the world is initialized.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Object Placement and while Loops


In the previous example, when the constructor is executed,
all of the instances are placed at the same coordinates.
This causes them to sit on top of each other.
Create an expression that calculates the size of an instance,
and then places subsequent instances at different random
coordinates.
The max speed of the flies will be increased within the loop.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Calculate the Placement of Instances


To program instances to land at different coordinates, replace
the fixed x-coordinate for the object's width with an
expression that includes:
Variable i.
Random x and y coordinates.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Infinite Loops
If an end to the loop isn't established, the loop keeps
executing and never stops.
Infinite loops are a common problem in programming.
An infinite loop executes as follows:
The variable never changes.
The condition always remains true.
The loop continues looping forever.
An infinite loop is when the loop keeps executing and does not stop
because the end to the loop isn't established.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Animating Objects with a Keyboard Key


Another way to animate an object is to have the object
change the image it displays when a keyboard key is pressed.
Pseudocode for this action:
Switch between four images when a key is pressed.
When left key is pressed, show image1.
When right key is pressed, show image2
When Bee is not turning and current image is image1 then show
image2 else if not turning show image1.
Object needs to remember if the Bee is turning - or not.

Otherwise, it will rapidly switch the object it displays, and the keyboard key
will not be able to control it.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Keyboard Key Example


The Bee should lean to the left or right when turning.
Four images are saved in the scenario:
One with Bee leaning left, one leaning right, and the last two with the
normal flight animation.

Pseudocode for this action:


If Bee is turning then do not use wing movement animation.
If turn left show left image, and if turn right show right image.
Remember if Bee is currently turning.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Declare Class Variables


First, add new fields in the Bee class to store the left and right
turns, and a field to store the current turn state.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Initialize Variables
Then initialize our class variables in the constructor.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Set isTurning Variable


Next, in our handleMovement() method we wrote earlier we
will set the state of our isTurning variable to true if we are
turning, else we will set it to false.
We will also set the appropriate turn image.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Logic Operators
To test if Bee is turning when animating :
Multiple boolean expressions to express if one or both are true or false.
Logic operators to connect the boolean expressions.
For example, the statement, "When Bee is not turning and current
image is image1..." would be coded as:
if (getImage() ==

image1

&& !isTurning)

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Types of Logic Operators


Logic operators can be used to combine multiple boolean expressions
into one boolean expression.
Logic Operator

Means

Definition

Exclamation Mark
(!)

NOT

Reverses the value of a boolean expression (if b


is true, !b is false. If b is false, !b is true).

AND

Combines two boolean values, and returns a


boolean value which is true if and only if both of
its operands are true.

OR

Combines two boolean variables or expressions


and returns a result that is true if either or both of
its operands are true.

Double ampersand
(&&)

Two lines (II)

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Logic Operators Example


Logic operators set the image that appears if the Bee is
turning or not.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Arrays
When we created our basic animation we used two images to
simulate wings flapping.

Most animations will have multiple images, but this would


increase the number of conditions to test in our code.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Arrays
With only 4 images our code would look like this:

We could easily have 8 or more images!


JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Arrays
Using an array, you can hold and access multiple variables
from just one variable.
An array is an object that holds multiple variables. An index can be
used to access the variables.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

How Variables Hold Values


A simple String variable named "studentname" is a container
that holds a value: A single students name .
String studentname;

studentname container example:


Joe

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

How Arrays Hold Variables


An array object can hold many variables.
This array named studentnames can hold many variables.
String[] studentnames

String[ ]
0

"Joe"

"Debbie"

"Ermal"

"Besa"

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Variable Declaration for an Array


To declare an array object, write the variable declaration as
follows:
Element type:
String [ ] for an array of Strings.
int [ ] for an array of integers.

Square brackets [ ] to indicate that this variable is an array.


Variable assignment.
Expression that creates the array object and fills it with a number of
Strings or integers.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Array Example
In this array:
The studentnames String variable is created.
"Joe", "Debbie", "Ermal", and "Besa" are String objects that make up
the array object.
An array object is assigned to the variable studentnames.
String [] studentames;
studentnames = {"Joe", "Debbie", "Ermal", "Besa"};

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Accessing Elements in an Array


Use an index to access the elements in the array object.
To use an index:
Each element has an index, starting at position zero [0].
Each element's position increases by 1.
Elements are accessed using square brackets [ ] and an index to
specify which array element to access. An index is a position number
in the array object.
String[ ]
Index

Element

"Joe"

"Debbie"

"Ermal"

"Besa"

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Access Elements in an Array


To access an element in the array, attach the index for that
element in square brackets to the array name.
The statement studentnames[3] accesses the array element
at index 3the String "Besa".
This is the fourth element in the array.
String[ ]
Index

Element

"Joe"

"Debbie"

"Ermal"

"Besa"

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Array Animation
To better make an instance animate multiple images we could
declare an array.
The array includes all of the images to animate the Bee.
Declare a field in the Bee class for the array.
Iterate through the array.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

35

Create the Arrays


Create an array in the Bee class to store 4 images.
Create an integer variable to store current image index.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

36

Create the Arrays


Initialize the new image, the images array and the
currentimage variables in the constructor.

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

37

Create the Arrays


We could use our knowledge of the while loop to better code
the previous slide

Could be written as

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

38

Create the Arrays


Modify the animateBee() method

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

39

Terminology
Key terms used in this lesson included:
Array
Elements
Index
Infinite loop
Local variables
Logic operators
Loop

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

40

Summary
In this lesson, you should have learned how to:
Create a while loop in a constructor to build a world
Describe an infinite loop and how to prevent one from
occurring
Use an array to store multiple variables
Create an expression using logic operators
Describe the scope of a local variable in a method

JF 3-10
Loops, Variables, and Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

41

Java Fundamentals

4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Identify components of Eclipse
Identify components of a Java application
Compile an application
Test to ensure application is complete
Write the code for GalToLit.java

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Modify a program to execute error free
Modify a program to use a formula to convert units of
measure

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Eclipse Community and Requirements


Facts about Eclipse:
Eclipse was created by an Open Source community.
The Eclipse project is governed by the Eclipse Foundation, a non-profit
organization.
Eclipse requires an installed Java Runtime Environment (JRE).
Eclipse contains its own development tools, i.e., a Java compiler.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Java JRE and Java JDK


Differences between Java JRE and Java JDK:
Java Runtime Environment (JRE) contains only the necessary
functionality to start Java programs, such as Internet applications.
Java Development Kit (JDK) contains functionality to start Java
programs as well as develop them.
At a minimum, the Java JRE is required to run Eclipse.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Check for Java on Your Computer


To verify that Java is already installed on your computer:
Windows or Linux operating systems:
Enter java -version in a command window.

Mac operating system:


Use the Software Update option from the Apple menu.

This course assumes that you have Java and Eclipse installed
on your computer.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Steps to Launch Eclipse


On a computer with Windows double-click on the file
eclipse.exe. On a Linux or Mac computer double click on the
file eclipse.
When prompted, enter the pathname for the workspace into
which you will store your Java projects and click the OK
button. This can be your c:\ drive, or possibly a network drive.
Eclipse will start and display the Welcome page.
Close the Welcome page by clicking the X next to the
Welcome tab name.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Eclipse Welcome Page


There are valuable resources available from the Welcome
page.
You can return to the Welcome page by choosing Welcome
from the Help menu.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Eclipse Edit Area and Views


Eclipse provides an edit area and several views.
An editor is where you type in your Java source code.
Views are sub-windows that provide information about your
project.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Eclipse Edit Area Tabs


The edit area uses tabs when more than one file is open.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Eclipse Edit Area Windows


The edit area can have multiple windows occupy the space.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Additional Details on Edit Areas and Views


A combination of views and editors are referred to as a
perspective.
You can choose Open Perspective from the Window menu.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

The Workspace
All projects are developed and modified in a workspace.
A workspace is a collection of Projects.
In this course, you may use the same workspace for all
practice projects and packages.
A project is a way for programmers to organize Java files.
A package is how Java and Eclipse organize Java files that are
related.
Using packages will ensure that related files can find each
other.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Switching Workspaces
You can Switch Workspaces (from the File menu) to change to
a different physical location for your files.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

High-Level Steps to Create a Program in


Eclipse
Create a Project.
Create a Package (inside the src folder of the project).
Create Class(es) inside the package.
At least one of the classes must contain a main method. This class is
called the Driver class.

Compile the Java code. This creates a .class file.


Run the Java code from the Driver class.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Projects in Eclipse
In Eclipse:
All programs must reside inside a project for proper compilation.
You may have one or multiple class files in one project.
One of the classes must contain a main method.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Steps to Create a Project in Eclipse


Choose File New Java Project.
Enter a project name and click Finish.
All project values are set to default by clicking the Finish
button.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Project Display
The project is created and displayed as a folder.
It displays in the Package view to the left of the edit area.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Steps to Create a Package


Select the src folder in the Package view.
Right click the src folder and choose New Package.
A package, in Java, is a mechanism for organizing Java classes into
namespaces or containers. In Eclipse, packages are created inside
projects.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Naming Packages
Name this package the same name as the Project using lower
camel case.
Camel case is the practice of stringingCapitalizedWords together with
no spaces. Lower camel case does not capitalize the lead word.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Steps to Create a Class


1.

Right click on the project name to create a new class named StudyPage
in the studyTool package.

2.

Select the option to create the main method.


A class in Java is a construct that is used as a blueprint to create
objects. It can also be a construct in which objects are created.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Create a Class Display


The option is selected to create the main method.
A main method, in Java, is the
method inside a class that runs
when the class is compiled and
run. This class is referred to as
the Driver Class.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

New Class
Notice the following:
The StudyPage.java class appears in the studyTool package in the
Package Explorer View.
The StudyPage.java class is created with the main method.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Steps to Create and Run Java Code


To implement the main method and run the program, enter
the following information into the main class.
The method inside a class that runs when the class is
compiled and ran is the main method.
public class StudyTerm {
public static void main(String[] args) {
System.out.println("Enter a study term");
}
}

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Steps to Create and Run Java Code


Right click on StudyPage.java in the package view.
Choose Run As Java Application.
Save the class when prompted.
Note results display in the Console View.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Implementing the Main Class Code


Continue implementing the main class to accept a term,
prompt for a definition, accept a definition, and finally,
display the term and definition as shown below.
package studyTool;
import java.util.Scanner;
public class StudyPage {
public static void main(String[] args) {
Scanner scanterm = new Scanner(System.in);
String termvar;
System.out.println("Enter a study term");
termvar = scanterm.nextLine();
Scanner scandef = new Scanner(System.in);
String termdef;
System.out.println("Enter a definition");
termdef = scandef.nextLine();

System.out.println(termvar + ":

" + termdef);

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Implementing the Main Class Code


You may have to correct some syntax errors that are a result
of typing errors.
See if you can correct them without asking for assistance.
Pay particular attention to the ";" at the end of each line, and
that your "{" (left curly brace) has a matching "}" (right curly
brace.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Describe the StudyPage Class Code


See if you can describe how the code in the StudyPage class is
interpreted by Java.
Add comments to your code to describe what you think the
lines of code do.
Comments are ignored by the Java compiler.
To add a comment, type // in front of the comment.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Program to Convert Gallons to Liters


What is the formula to convert gallons to liters?
1 US gallon is equivalent to 3.78541178 Liters.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Pseudocode for Gallons to Liters


Conversion
What is the math calculation to complete the conversion?
Pseudocode would look like:
Use Scanner to read in the number of gallons.
Store the number of gallons in a variable.
Multiply that variable by 3.785 (variable*3.785) and store this new
value into a second variable (Hint: use double for the variables, not int).
Display the output.
Use the StudyPage program as a guide to create the program on your
own.

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Hints for Gallons to Liters Conversion


Hints:

an int variable type is used to store whole numbers


a double variable type is used to store decimal numbers
int numgallons = 0; //declare a variable for number of gallons
double converttoliters = numgallons * 3.785

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Terminology
Key terms used in this lesson included:
Camel case
Eclipse: edit and view areas, perspective, workspace
Java JRE vs. Java JDK
Java classes
Java packages
Java main methods

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Summary
In this lesson, you should have learned how to:
Identify components of Eclipse
Identify components of a Java application
Compile an application
Test to ensure application is complete
Write the code for GalToLit.java

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Summary
In this lesson, you should have learned how to:
Modify a program to execute error free
Modify a program to use a formula to convert units of
measure

JF 4-1
Getting Started with Eclipse

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

35

Java Fundamentals

4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Describe the general form of a Java program
Describe the difference between an Object class and a Driver
class
Access a minimum of two Java class APIs
Explain and give examples of Java keywords
Create an Object class
Create a Driver class

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

General Java Program Form


There are two general forms of Java classes:
Driver classes
Object classes

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Driver Classes
Driver classes:
Contain a main method.
A main method is necessary to run a Java program in Eclipse.
The main method may include:
Instances of objects from an object class
Variables
Loops, conditional statements (if-else)
Other programming logic

Can also contain other static methods.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Object Classes
Object classes:
Are classes that define objects to be used in a driver class.
Can be found in the Java API, or created by you.
Examples: String, BankAccount, Student, Rectangle

The Java API is a library of packages and object classes that are
already written and are available for use in your programs.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

The Java API


The Java API documentation is located here:
http://docs.oracle.com/javase/7/docs/api/
Details for class
selected from the list
of classes

Packages

Classes

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

The Java API: String Class


Scroll through the list of classes until you see String, then click
on the link. You should see the following:
Details for the
String class

Scroll down in this


list to String

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

The Java API: Examine String Class


Examine and discuss the constructors and methods.

Details for the


String class

Scroll down in this


list to String

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

The Java API: The String Class


We will use the String class in programs.
The constructor that is most common for this class is:
String(String original)

Common Methods include:


Method

Description

charAt(int index)

Returns the char value at the specified index.

length()

Returns the length of this string.

substring(int beginIndex)

Returns a new string that is a substring of this


string.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

A Simple Programmer-Created Object


Class: Student
A Java class is used to store or represent data for the object
that the class represents.
There are many classes already available from the Java API,
but you will want to create many more.
For example, we can create a model, or programmatic
representation, of a Student.
Information that we might need for a student includes
Student ID, Name, and GPA.
In this lesson, we will create a Object class called Student,
then a Driver class called StudentTester.
JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

A Simple Programmer-Created Object


Class: Student
All Java classes are created in a text file with the same name
as the class.
These files also have a .java extension.
In this lesson, we will create a Student class and a
StudentTester class in Eclipse.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Syntax to Create A Simple ProgrammerCreated Object Class


The following is example syntax to create a programmercreated object class.
The Java keywords are:
package (optional)
import (optional)
package
public class

<package_name>;
import <other_packages>;
public class ClassName
{
<variables (also known as fields)>;
<constructor method(s)>;
<other methods>;
}

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Key Terms
Term

Definition

package keyword

Defines where this class lives relative to other classes, and provides a
level of access control.
Use access modifiers (such as public and private) to control access.

import keyword

Defines other classes or groups of classes that you are using in your
class.
The import statement provides the compiler information that identifies
outside classes used within the current class.
Precedes the name of the class.

class keyword
class variables or
instance fields
(often shortened to
fields)

The name of the class and the file name must match when the class is
declared public (which is a good practice). However, the keyword
public in front of the class keyword is a modifier and is not required.

Variables, or the data associated with programs (such as integers,


strings, arrays, and references to other objects).

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Key Terms
Term

Definition

Constructors

Methods called during the creation (instantiation) of an object (a


representation in memory of a Java class.)

Methods

Methods that can be performed on an object. They are also referred to


as instance methods. Methods may return an object's variable values
(sometimes called functions) or they may change an object's variable
values.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Java Keywords
All Java programs use Java keywords.
Examples include the following words: class, public, String,
int, for, while, and double.
The font color for Keywords will change in the Eclipse editor.
List of Java keywords:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

A Java keyword is a word that has a special function in the Java


language, and cannot be used as names for classes, methods, or
variables.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Java Program Naming Conventions


Naming Conventions for a Java program:
The optional package name is defined before an import statement in
lower camel case.
The optional import statements are defined below the package name.
The class name is a noun labeled using upper camel case.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Camel Case
Camel case is the practice of stringing capitalized words
together with no spaces.
Lower camel case strings capitalized words together but the
lead word is not capitalized.
For example: thisIsLowerCamelCase.
Upper camel case strings capitalized words together, but the
lead word is capitalized.
For example: ThisIsUpperCamelCase.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Additional Naming Conventions for a Java


Program
Additional naming conventions for a Java program:
Variable names are short but meaningful in lower camel case.
Constant names are declared in uppercase letters with the final
modifier.
Constructors are named the same as the class name.
Methods are verbs named in lower camel case.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Naming Conventions Example


The guidelines for a programmer-created object class are
labeled in this example for Student.
Create this file in Eclipse. // is the symbol for comments.
package com.example.domain; // Package Declaration
import java.util.Scanner;// An Import Statement for other packages
public class Student // Class Declaration for this file
{
private int studentId;
// Variable Declarations for this class
private String name;
private String ssn;
private double gpa;
public final int SCHCODE = 34958// A Constant Declaration
public Student(){// A Constructor
}
public int getStudentId(){// An accessor Method
return studentId;
}
public void setStudentId(int x){ // A mutator Method
studentId = x;
}
}

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

A Simple Programmer-Created Object


Class: Student
The optional package keyword is used in Java to group classes
together.
A package is implemented as a folder. Like a folder, it provides a
namespace to a class.
It is recommended to always declare a package at the top of the class.
package com.example.domain;

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

A Simple Programmer-Created Object


Class: Student
In the example below, a Student class and a Teacher class
could be in a folder under the domain name for each
developer. If a company called Acme has developers named
Smith and Jones, the packages could be:
package com.acme.smith
package com.acme.jones

The path for Jones' file is shown below.


Namespace View for Jones:
com.acme.jones
Student
Teacher
JF 4-2
Object and Driver Classes

Folder View for Jones:


+com
|_+acme
|_+jones
|_+Student.java
|_+Teacher.java

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Import Keyword
The import keyword is used to identify packages or object
classes that you want to use in your class.
You can import a single class or an entire package.
You can include multiple import statements.
Import statements follow the package declaration and
precede the class declaration.
import java.util.Scanner;

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Import Statements
An import statement is not required, and by default, your
class always imports java.lang from the API.
http://docs.oracle.com/javase/7/docs/api/java/lang/Package.html

You do not need to import classes that are in the same


package as the import statement.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Import Statement Examples


Additional examples of import statements:
import java.util.Date;

// Import the individual class.

import java.util.*;

//Import the entire package.

import java.util.Date;
import java.util.Calendar;

//Import using multiple statements.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Variables for Student Class


In addition to the package statement and import statements,
the Student class will contain variables for student id, name,
social security number, grade point average, and school code.
This will require defining a class with class variables and a
constructor.
In addition, methods will be added that can access and
change the variables.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

The Student Class


package com.example.domain;

Access Modifier

public class Student


Class Declaration
{
private int studentId;
private String name;
Fields/Variables
private String ssn;
private double gpa;
public final int SCHCODE = 34958;
public Student(){
Constructor
}
public int getStudentId()
{
Methods
return studentId;
}
public void setStudentId(int x)
{
studentId = x;
Access Modifier
}
}

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Conventions for the Class Declaration


Class declaration conventions:
The name of the class must be the same as the name of the file that
was created in Eclipse.
The name must begin with a character, and may contain numbers, _ or
$.
Use upper camel case if the name is more than one word.
For a simple programmer-created object class, the access modifier
should be public (all access modifiers are either public, private, or
protected).
public class Student{}

JF 4-2
Object and Driver Classes

All code for this class must be enclosed in


a set of curly brackets { }.

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Conventions for the Class Variables


Class variables conventions:
Class variables should be declared with the private access modifier to
protect the data.
Class variables are named using lower camel case.
An exception is a constant (a value that does not change) that should
be named using upper case, and declared as public to allow driver
programs to access the value.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Class Variable Declaration Examples


Examples of declaring class variables:

private int length;


private int width;
private double area;
public final double SCALE = 0.25; //constant
private String name;

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Constructor Methods
A constructor method is unique in Java because:
The method creates an instance of the class.
Constructors always have the same name as the class and do not
declare a return type.
All code for this method must be
enclosed in a set of curly brackets { }.

public Student{}

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Constructor Methods
With constructor methods:
You can declare more than one constructor in a class declaration.
You do not have to declare a constructor, in fact, Java will provide a
default (blank) constructor for you.
If you declare one or more constructors, Java will not provide a default
constructor.
All code for this method must be
enclosed in a set of curly brackets { }.

public Student{}

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Constructors without Parameters


If you create a constructor without parameters (the
parenthesis is empty), you can leave the contents of the
constructor (between the { and }) blank.
This is called a default constructor, and is the same as the
Java-provided constructor if you do not declare one.
This constructor initializes the numeric class variables to zero,
and object variables (such as Strings) to null.
No parameters

public Student(){
}

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Constructors without Parameters


If you create a constructor without parameters (the
parenthesis is empty), you can also initialize the variables
between the { and }. This is also called a default constructor.
This constructor initializes the numeric class variables to zero,
and object variables (such as Strings) to null. It has the same
results as the previous slide, but the values are more evident.
public Student(){
studentid = 0;
name = "";
ssn = "";
gpa = 0.0;
}

JF 4-2
Object and Driver Classes

No parameters

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Constructors with Parameters


If you create a constructor with parameters (the parenthesis
is NOT empty), you would also initialize the variables
between the { and }.
This constructor will initialize the class variables with the
values that are sent in from the main driver class.
public Student(int x, String n, String s, double g){
studentid = x;
name = n;
ssn = s;
gpa = g;
}

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

35

Default Constructor Example


The constructor method in this example is a default
constructor that creates an instance of Student.
package com.example.domain;
public class Student
{
private int studentId;
private String name;
private String ssn;
private double gpa;
public final int SCHCODE = 34958;
public Student(){
}

public int getStudentId()


{
return studentId;
}

JF 4-2
Object and Driver Classes

Constructor

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

36

Default Constructor Example


The Student example on the previous slide illustrates a simple
no-argument constructor.
The value returned from the constructor is a reference to a
Java object of the type created.
Remember, constructors can also take parameters.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

37

Constructors
A constructor is a method that creates an object.
In Java, constructors are methods with the same name as
their class used to create an instance of an object.
Constructors are invoked using the new keyword.
Example of code that could be used in a Driver Class to create
an object from the Student constructor:
Student stu = new Student();

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

38

Main Method
To run a Java program you must define a main method in a
Driver Class.
The main method is automatically called when the class is
called.
Remember to name the file the same as the class.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

39

A Simple Programmer-Created Driver


Class: StudentTester
For examples in this course, we will often use the name of the
object class followed by the word "Tester."
Below is an example of a simple Java driver class named
StudentTester with a main method.
public class StudentTester
{
public static void main(String args[])
{
}
}

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

40

A Simple Programmer-Created Driver


Class: StudentTester Example 1
In this example, a statement is added to create a Student
object.
A Student is created and the class variables are initialized as
previously described under default constructors.
public class StudentTester
{
public static void main(String args[])
{
Student s1 = new Student();
}
}

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

41

A Simple Programmer-Created Driver


Class: StudentTester Example 2
In this example the statement to create an object of the
Student class is different.
This Student is created using parameters.
Can you guess this student's id? Name? SSN? GPA?
Add another student using the default constructor.
public class StudentTester
{
public static void main(String args[]
{
Student s1 = new Student(123, "Mary Smith", "999-99-9999", 3.4);
}
}
JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

42

Enhancing the Student Object Class


Most modern integrated development environments provide
an easy way to automatically generate the accessor (getter)
and mutator (setter) methods.
Another method that helpful during testing, creating and
modifying objects is the toString() method.
In the next few slides, we will develop new methods for the
Student object class and modify the StudentTester driver
class to test them.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

43

Accessor and Mutator Methods


It is common to create a set of methods that manipulate and
retrieve class data values:
Accessors (getters): Methods that return (get) the value of
each class variable.
Mutators (setters): Methods that change (set) the value of
each class variable.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

44

Accessor and Mutator Methods to Enhance


the Student Object Class
Examples (to follow):
Add the following Accessor methods:
getStudentID(), getName(), getSSN(), getGPA()

Add the following Mutator methods:


setStudentID(), setName(), setSSN(), setGPA()

Add a toString() method to the Student class that will allow us to see
the Student data as output.

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

45

Enhancing the Student Object Class


Add the getStudentID() method and the setStudentID()
method as shown below.
The object name of the class (this) is used to distinguish
between the class variable studentID and the parameter
studentID being passed in as an argument.
public int getStudentId()
{
return studentId;
}
public void setStudentId(int studentId)
{
this.studentId = studentId;
}

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

46

Additional Methods for the Student


Object Class
Now using the example from the previous slide, add the
following methods to the Student object class:
getName(), getSSN(), getGPA()
setName(), setSSN(), setGPA()

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

47

Add the toString() Method to the Student


Object Class
Now add the toString() method to the Student object class.
Note, any String object can be built by you to display the
information about each student:
public String toString()
{
String s1 = "";
s1 = "Student ID: " + getStudentID() +
"Student Name: " + getName() +
"Student SSN: " + getSSN() +
"Student GPA: " + getGPA();
return s1;
}

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

48

Creating the StudentTester Driver Class


Main Method
Now create a StudentTester Driver Class main Method as
follows:
public class StudentTester
{
public static void main(String args[]
{
Student s1 = new Student(123, "Mary Smith", "999-99-9999", 3.4);
System.out.println(s1);
Student s2 = new Student();
s2.setStudentID(124);
s2.setStudentName("John Jacoby");
s2.setSSN("123-45-6789");
s2.setGPA(4.0);
System.out.println(s2);
Student s3 = new Student();
System.out.println(s3);
}
}
JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

49

Code Blocks
A code block is defined by opening and closing "curly braces"
{ }. When examining code blocks, consider the following:
Every class declaration is enclosed in a code block.
Method declarations, including the main method, are enclosed in code
blocks.
Java fields and methods have block (or class) scope.
public class SayHello
{

public static void main(String args[]


{
System.out.println("Hello Lisa");
}

JF 4-2
Object and Driver Classes

// Begin class code block


// Begin method code block
// End method code block
// End class code block

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

50

Code Block Format


Code blocks begin with a { and end with a }.
Each time you begin a code block you must have an end.
For example: Every { MUST have a matching }.
Code blocks can be found in:

Classes
Methods
Conditionals (if statements, switch statements)
Loops

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

51

Terminology
Key terms used in this lesson included:
Access modifiers
Code blocks
Constants
Constructors
Driver class

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

52

Terminology
Key terms used in this lesson included:
import statements
Java API
Java comments
Java keywords
Lower camel case
Methods

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

53

Terminology
Key terms used in this lesson included:
Object class
Packages
Parameters
Programmer-created class
Upper camel case
Variables

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

54

Summary
In this lesson, you should have learned how to:
Describe the general form of a Java program
Describe the difference between an Object class and a Driver
class
Access a minimum of two Java class APIs
Explain and give examples of Java keywords
Create an Object class
Create a Driver class

JF 4-2
Object and Driver Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

55

Java Fundamentals

4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Use primitive data types in Java code
Specify literals for the primitive types and for Strings
Demonstrate how to initialize variables
Describe the scope rules of a method
Recognize when an expression requires a type conversion

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Overview
This lesson covers the following topics:
Apply casting in Java code
Use arithmetic operators
Use the assignment operator
Use a method from the Math class
Access a Math class method from the Java API

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Java Programming Types


In Java, data types:

Are used to define the kind of data that can be stored inside a variable.
Ensure that only correct data is stored.
Are either declared or inferred.
Can be created by the programmer.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Variables Must Have Data Types


All variables must have a data type for security reasons.
The program will not compile if the user attempts to store
data that is not the correct type.
Programs must adhere to type constraints to execute.
Incorrect types in expressions or data are flagged as errors at compile
time.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Primitive Data Types


Java has eight primitive data types that are used to store data
during a program's operation.
Primitive data types are a special group of data types that do
not use the keyword new when initialized.
Java creates them as automatic variables that are not
references, which are stored in memory with the name of the
variable.
The most common primitive types used in this course are int
(integers) and double (decimals).

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Primitive Data Types


Data Type

Size

Example Data

Data Description

boolean

1 bit

true, false

Stores true and false flags.

byte

1 byte
(8 bits)

12, 128

Stores integers from -128 to 127.

char

2 bytes

'A', '5', '#'

Stores a 16-bit Unicode character


from 0 to 65,535

short

2 bytes

6, -14, 2345

JF 4-3
Data Types and Operators

Stores integers from


-32,768 to 32,767.

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Primitive Data Types


Data Type
int

long

float

double

Size

Example Data

4 bytes

8 bytes

4 bytes

8 bytes

6, -14, 2345

Data Description
Stores integers from:
-2,147,483,648 to 2,147,483,647

3459111, 2

Stores integers from:


-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807

3.145, .077

Stores a positive or negative


decimal number from: 1.4023x10-45
to 3.4028x10+38

.0000456, 3.7

Stores a positive or negative


decimal number from: 4.9406x10-324
to 1.7977x10308

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Declaring Variables and Using Literals


The keyword new is not used when initializing a variable of a
primitive type. Instead, a literal value should be assigned to
each variable upon initialization.
A literal can be any number, text, or other information that
represents a value.
Examples of declaring a variable and assigning it a literal
value:
boolean result = true;
char capitalC = 'C';
byte b = 100;
short s = 10000;
int i = 100000;

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Declaring Variables and Using Literals


Example
The values of d1 and d2 are the same.
The initialization of d2 shows how scientific notation can be
used to set the value.
Total and ss_num are assigned the same value.
The initialization of ss_num shows that underscores can be
used to separate numbers for readability.
long total=999999999;
long ss_num = 999_99_9999;
double d1 = 123.4;
double d2 = 1.234e2;
float f1 = 123.4f;

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Numeric Literal Examples


0x and 0b are used to denote a literal hexadecimal value or a
literal binary value.
Literals will improve processing performance.
long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi = 3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_fff_fff_fffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Java SE 7 Binary Literals


In Java SE7 and later, binary literals can be expressed using
the binary system by adding the prefixes 0b or 0B to the
number.
Binary literals are Java int values. Java byte and short values
require a cast to prevent a precision loss error from the
compiler.
A cast signals a type conversion. If you cast one type as another type,
you are explicitly converting the item from it's original type to the type
that you specify. A cast does not round a decimal number, but
instead, will truncate it. An example of casting a double as an int is:
double x = 5.745
int y = (int)x; //y is now equal to 5

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Pupose of Java SE 7 Binary Literals


Binary Literals are used for:
Calculations
Comparisons
Low-level programming, such as:
Writing device drivers
Low-level graphics
Communications protocol packet assembly
Decoding

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Why Use Binary Literals?


Using Binary Literals to represent values for comparisons and
calculations is substantially faster than using values of the
actual data type.
Modern high-performance processors usually perform
calculations on integers as fast as using binary literals, so why
use literals?
It is still optimal to use literals for overall power and
performance because they use less resources.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Casting Example

// An 8-bit 'byte' value:


byte aByte = (byte)0b00100001;
// A 16-bit 'short' value:
short aShort = (short)0b1010_0001_0100_0101;

This is an example of
casting. In this example,
the binary
value is cast to a byte
type.

// Some 32-bit 'int' values:


int anInt1=0b1010_0001_0100_0101_1010_0001_0100_0101;
int anInt2=0b101;
int anInt3=0B101;
//The B can be upper or lower case

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Rules for Variable Names


You must follow the following rules when choosing the name
for a variable:

Do not use a Java keyword or reserved word.


Do not use a space in the variable name.
Use a combination of letters or a combination of letters and numbers.
Cannot start with a number.
The only symbols allowed are the underscore ( _ ) and the dollar sign
($).

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Conventions for Variable Names


While conventions are not rules, most Java programmers
follow these conventions:
Use full words instead of cryptic abbreviations.
Do not use single letter variables. If all of the variables are single letter,
the code may look very confusing.
An exception to this convention is for loop control variables, which are often
letters i, j, or k

If a variable name consists of one word, spell that word in all lowercase
letters.
If a variable name consists of more than one word, use
lowerCamelCase.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Additional Naming Conventions for


Variable Names
Additional naming conventions:
If a variable will be a constant value, use all capital letters and separate
words with the underscore.
Use names that express the purpose of the variable.
In the example below, PI is a good choice for naming this number
because it allows you to recall what the variable is.
int PI = 3.14159;

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Variable Scope
Scope is used to describe the block of code where a variable
exists in a program.
It is possible for multiple variables with the same name to
exist in a Java program.
In most cases, the innermost variable has precedence.

A variable exists only inside the code block in which it is


declared.
Once the final brace of the block } is reached:
The variable goes out of scope.
It is no longer recognized as a declared variable.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Variable Scope Example 1


In the following example, name will not print out because it
stops existing once the brace marked Point B is reached.
public void someMethod()
{
if(gameOver && score>highScore)
{
String name;
//Point A
System.out.println("Please enter your name:");
name=reader.next();
}
//Point B

System.out.println("Thank you " + name + ", ");


System.out.println("your high score has been saved.");

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Variable Scope Example 2


In this example, the variable name has been moved outside
of the if statement block to allow name to be used
throughout the method.
public void someMethod()
{
String name;
//Point A
if(gameOver && score>highScore)
{
System.out.println("Please enter your name:");
name=reader.next();
}
//Point B
System.out.println("Thank you " + name + ", ");
System.out.println("your high score has been saved.");
}

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Variable Scope Example 3


Java will allow a class variable and a method variable with the
same name to exist in a program. Can you predict what this
program will print?
public class Counting{
public static int counter=5;
public static void main(String[] args)
{
System.out.println("At the start of this program, counter is "+ counter);
count();
System.out.println("At the end of this program, counter is "+ counter);
}//end of main
public static void count()
{
int counter=10;
System.out.println("At the end of this method, counter is "+ counter);
}//end of count()
}//end of class
JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Variable Scope Example 3 Solution


Solution: 5, 10, 5
The program starts main() and prints the global class variable
counter.
The method count() is called and a new local variable counter
is created for that method call.
It is given a value of 10 and then prints.
When the brace at the end of count() is reached, the local
variable goes out of scope (ceases to exist).
The program returns to the main() method and prints the
global variable counter which has not changed it's value.
JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Arithmetic Operators
Java has several arithmetic operators to perform
math operations.
Symbol

Operator Description

Addition operator

Subtraction operator

Multiplication operator

Division operator (finds the quotient)

Modular operator (finds the remainder)

++

Increment operator (adds one). Is a unary operator.

--

Decrement operator (subtracts one). Is a unary


operator.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Arithmetic Operators Precedence


All math expressions are evaluated following the order of
precedence:
Expressions in parenthesis are handled first.
All multiplication, division, and modular operations are handled next,
working from left to right.
Finally, all addition and subtraction operations are handled, working
from left to right.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Increments and Decrements


Increments and decrements are handled first for preincrement notation and last for post-increment notation.
Increment in Java means to add one to the variable value.
Decrement in Java means to subtract one from the variable.
Pre-increment notation:
++x;
Post-increment notation:
x++;

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Increment and Decrement Precedence


Example
Pre-increment notation:
int x = 3;
++x;

//x is equal to 4

z = ++x;

//x is equal to 5, THEN z is equal to 5

Post-increment notation:
int x = 3;
x++;

//x is equal to 4

z = x++;

//z is equal to 4, THEN x is equal to 5

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Assignment Operator
Java uses the = (equal sign) as the assignment operator. The
evaluation of the expression on the right is assigned to the
memory location on the left.
int x = 4;
int y = 5;
int z = 10;
int total = 12;
X

Total

10

12

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Assignment Operator Example 1


When this line of code is executed, the value for total
changes. The boxes show what is in each memory location
for x, y, z, and total. Now the memory location total is
assigned the value of 4 + 5 * 10, which is 54.
int x = 4, y = 5, z = 10;
int total = x + y * z;
X

Total

10

54

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Assignment Operator Example 2


Think of the assignment operator like an arrow pointing to
the left. Everything on the right will go into the memory
location on the left. How will memory change when this code
is executed?
int x = 4, y = 5, z = 10;
int total = x + y * (z x);
X

Total

10

??

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Assignment Operator Example 2 Solution


The answer is that total will be assigned the value of the
expression. This means that the value of the expression will
be stored in the memory address associated with the variable
total.
int x = 4, y = 5, z = 10;
int total = x + y * (z x);
X

Total

10

34

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Truncation and Integer Division


Division of two integers will ALWAYS produce an integer.
For example, the formula for the volume of a cone from
Geometry is:
V = r2 h
If 1/3 is used in a Java expression, it is evaluated as 0 because of
integer division.
Integer division results are the quotient without decimals.
Truncation is the concept of removing the fractional or decimal part
of a number. For example: Truncating 7.8 would produce a result of 7,
and truncating -3.2 would produce a result of -3.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Truncation and Integer Division


Divisor

5
3

16
15
1

quotient
Quotient
dividend
Dividend

Remainder

Integer Division Examples:


16 / 3 = 5 (Truncation)
10 / 3 = 3 (Truncation)
16 % 3 = 1
12 % 3 = 0
11 % 3 = 2

To calculate a quotient without truncation (decimal results), convert


either the dividend or the divisor to a decimal.
For example: 11 / 5.0 = 2.2 and likewise, 11.0 / 5 = 2.2
JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Truncation and Integer Division Example 1


What prints when the code below is executed?
int x = 4, y = 5, z = 10;
int total = z / (x * y);
System.out.println("The total is " + total + ".");

The answer is 0. Why doesn't 0.5 display?


Since total is an integer, the system will store an integer value
as the result of the calculation.
The decimal portion of the answer is truncated rather than
rounded to produce the final integer answer of 0.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

35

Truncation and Integer Division Example 2


A programmer might write the following code to create a
program to calculate volume.
The Java program will incorrectly calculate the answer as 0.
Working from left to right, the program divides 1 by 3.
Java considers 1 and 3 to be literal integers and does integer
division where .33... is truncated to 0.
How would you correct this?
double height = 4, radius = 10, volume;
volume = 1 / 3 * 3.14 * radius * radius * height;
System.out.println("The volume is" + volume + ".");

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

36

Understanding Types and Conversions


There are a few ways to force a formula to not truncate a
value:
Move the fraction to the end so that Java will always use a double and
an integer and will implicitly convert the answer to a double, not
truncate.
double volume = 3.14 * radius * radius * height * 1 / 3;

Make one of the literal integers into a literal double so that Java will
always use a double and an integer and will implicitly convert the
answer to a double, not truncate.
double volume = 1 / 3.0 * 3.14 * radius * radius * height;

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

37

Implicit Type Conversions


In the previous example, Java did implicit type conversions.
This happens whenever a smaller data type (like int) is placed
into a larger type (like double).
Java realizes the types are different and converts to the larger
size automatically for you.
However, Java will not convert from a larger (like double) to a
smaller (like int) size automatically.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

38

Using Type Casting


Using the random method from the Math library, we can
generate a random number from 1 to 10.
The random method generates a double between 0 and (not
including) 1.
Values such as 0, 0.4567 or 0.901306 might be generated.
int number;
number = Math.random() * 10;
System.out.println("The random number is " + number + ".");

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

39

Using Type Casting


Multiplying these values by 10 and then truncating the extra
would yield values 0, 4 or 9.
However, Java will not let this program compile in its current
state.
Data is lost by going from a larger value (double) to a smaller
value (int).
Thus, type casting is required for this type conversion.
int number;
number = Math.random() * 10;
System.out.println("The random number is " + number + ".");

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

40

Type Casting Operator


To cast a double value to an int, use (int) in front of the value.
To get the double result from our formula to go into the
integer container, use the type casting operator (int) in front
of the value.
Casting to the int data type will truncate the value.
Thus, casting the double literal 4.567 to an int will result in 4,
and 9.01306 will result in 9.
int number;
number = (int)(Math.random() * 10);
System.out.println("The random number is " + number + ".");

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

41

Converting Data Types


You can convert a data type (primitive or reference) to
another data type by simply placing the name of the data
type in parenthesis in front of the value or variable, as shown
in the example below.
int number;
Object o;
char firstInitial = 'A';
number = (int)firstInitial;
o = (Object)firstInitial;

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

42

Converting String Data Types


Note that casting will not work in all situations.
For example, casting a char to a String results in a compiler
error.
In situations such as this, you would need to resort to making
the type conversion in another way.
There are methods in the java.lang library to convert
characters to strings.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

43

Using Type Conversions


Using type conversions is another option to fixing the
truncation issue with the volume formula shown previously.
Use type casting to make one of the literal integers a double.
double volume = (double) 1 / 3 * 3.14 * radius * radius * height;

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

44

Understanding Types and Conversions


When Java is converting from a smaller primitive type to a
larger primitive type, the conversion is implicit.

double

Implicit
conversion

double

d1

JF 4-3
Data Types and Operators

int

5;

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

45

Understanding Types and Conversions


However, when Java converts from a larger primitive type to a
smaller primitive type, the conversion must be explicit via
type casting.
Java will not implicitly cast a larger type to a smaller type
because of loss of precision.

int

Explicit
conversion
required

JF 4-3
Data Types and Operators

double

int x

(int)12.95;

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

46

Searching Through the Java API


Examples and exercises in this course will require the use of
the methods in the Java Math and String classes.
You can find a description of all Java methods in the online
Java API.
Understanding how to navigate this vast library of standard
methods and classes will aid you in writing Java programs and
reusing code blocks that have already been created by others.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

47

Why Use the Java API?


One major benefit to having access to the Java API is a
common concept for programmers called code reuse.
Rather than coding excess items, you may use the API to find
how to access existing code that does exactly what you want.
This will reduce spending time on reproducing already
existing code and make your programming much more
efficient.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

48

Review the Java API


Go back to the Java API by using a search engine to search for
it.
There are many editions.
Review the Standard Edition for Java 7:
http://docs.oracle.com/javase/7/docs/api/
Examine the Math class. See if you can find a value for PI and
a method for computing the square root of a number.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

49

Math Class and the Java API


The frames version of the API has windows for the packages,
classes, and specifications.
Packages
Detailed
Specifications

Classes

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

50

Math Class
Find the Math Class in the class frame window.

Scroll to see a
list of fields and methods
available in this class.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

51

PI Field
Scroll to find the PI field.
To use PI in a program, specify the class name (Math) and PI
separated by the dot operator.
For example, this field would yield a more accurate volume
calculation in our earlier example if it is used as follows:
double volume = (double) 1 / 3 * Math.PI * radius * radius * height;

PI field with a description

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

52

Calculating Square Roots


The method for calculating square roots:

To calculate the square root of 625, use the class name and
the method separated again by the dot operator.
double answer = Math.sqrt(625);

The sqrt method requires a double. Why does the literal


integer 625 not give an error?

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

53

Calculating Square Roots Solution


Question: The sqrt method requires a double.
Why does the literal integer 625 not give an error?
Solution: Implicit conversion.
The int 625 is implicitly converted to a double and thus no
error occurs.

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

54

Data Types and Operators Practice


On paper, evaluate the following Java statements and record
the result.
double x = 3.25;
double y = -4.5;
int m = 23;
int n = 9;
System.out.println(x + m * y - (y + n) * x);
System.out.println(m / n + m % n);
System.out.println(5 * x - n / 5);
System.out.println(Math.sqrt(Math.sqrt(n)));
System.out.println((int)x);
System.out.println(Math.round(y));
double x = 3.25;
double y = -4.5;
int m = 23;
int n = 9;
System.out.println((int)Math.round(x) + (int)Math.round(y));
System.out.println(m + n);
System.out.println(1-1-((1-(1-(1-n)))));

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

55

Terminology
Key terms used in this lesson included:
Arithmetic operator
Assignment operator
boolean
char
Conventions
Declaration
double

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

56

Terminology
Key terms used in this lesson included:
float
Initialization
int
Literals
long
Order of Operation
Primitive data types

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

57

Terminology
Key terms used in this lesson included:
Scope
Short
Truncation
Type casting
Type conversion
Variables

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

58

Summary
In this lesson, you should have learned how to:
Use primitive data types in Java code
Specify literals for the primitive types and for Strings
Demonstrate how to initialize variables
Describe the scope rules of a method
Recognize when an expression requires a type conversion

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

59

Summary
In this lesson, you should have learned how to:
Apply casting in Java code
Use arithmetic operators
Use the assignment operator
Use a method from the Math class
Access a Math class method from the Java API

JF 4-3
Data Types and Operators

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

60

Java Fundamentals

4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Instantiate (create) a String
Describe what happens when a String is modified
Use the + and += operators for concatenating Strings
Interpret escape sequences in String literals

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Overview
This lesson covers the following topics:
Recognize the difference between a String and a primitive
char data type
Test Strings with the compareTo() and equals() method
Describe why the == operator does not always work when
testing String equality
Use String methods length(), substring(), indexOf(), and
charAt()

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

What is a String?
A String is an object that contains a sequence of characters.
Declaring and instantiating a String is much like any other
object variable.
However, there are differences:
They can be instantiated (created) without using the new keyword.
They are immutable.
Once instantiated, they are final and cannot be changed.

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Modifying a String
Attempting to modify a String does not modify it, it creates a
new String object.
As a new programmer, you will not notice this difference.
However, it becomes important in real systems where
processing time is a key element in program design.

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

String Operations Example


public class StringOperations{
public static void main(String[] args){
String string1 = "Hello";
String string2="Lisa";
String string3="";
//empty String or null
string3="How are you ".concat(string2);
System.out.println("string3: "+ string3);
//get length
System.out.println("Length: "+ string1.length();
//get substring beginning with character 0, up to, but not
//including character 5
System.out.println("Sub: "+ string3.substring(0,5));
//uppercase
System.out.println("Upper: "+string3.toUpperCase());
}
}

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Class Template
Use the following class to insert examples from this section.
import java.util.Scanner;
public class StringPractice{
public static void main(String[] args){
//paste practice code here
}

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Instantiating a String
Strings are object reference types.
They can be instantiated in two ways:

The new operator


String literals
There is no difference between the Strings below.
Both methods of instantiation create identical objects.

String s1 = new String("abc"); // new operator


String s2 = "abc";
// String literals

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

String References
When you create a reference to an Object or String, the
object does not necessarily exist yet.
In the code below, since name is not initialized, the program
will not compile.
The variable name is a null pointer.
String name;
System.out.println("My name is " + name);

Name = null

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

String References
In this code, one String object exists and name is referencing
it. The reference name2 is null.
How will this line change memory?
String name,name2;
name = "Mya";

name2 = null
name = Mya

name2 = name;

name

name2

Mya

name

name2

Mya

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

String References
Executing this line of code changes the name2 reference.
name2 = name;

The reference name2 will now refer to the same object as


name.
String Object
Mya

name

JF 4-4
Strings

name2

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

String References
Executing these lines of code creates two instances of the
String Mya in memory.
String name, name2;
name = "Mya";
name2 = "Mya";

Here the JVM compiler decides to save space and stores only
one String Object that holds the String Mya.
String Object
name

JF 4-4
Strings

Mya

name2

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

String References
If we run a very similar program but ask the user to enter
Strings, we get a different result.
Scanner in= new Scanner(System.in);
String name, name2;
name=in.next();
name2=in.next();

If the user types Mya for both Strings, the compiler actually
creates two different String Objects.
String Object

String Object

Mya

Mya

name

JF 4-4
Strings

name2

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

String References
It is very difficult to predict when Java will create a new String
or use an existing object for a String that is identical to the
new String.

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

String Concatenation
Concatenate two strings together with the + and +=
operators.
Symbol + is used to concatenate two strings together.
Symbol += is used to concatenate two strings together and
assign it to itself all in one operation.
String
String
String
String
String

s1
s2
s3
s4
s1

= "This is a ";
= "string";
= s1 + s2;
= "This is a " + s2;
+= s2;

To concatenate means to link items together in a chain or series.


String concatenation is the linking together of two or more strings.
JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Manipulation of Strings
Each time a String is changed, a new String is created in a new
memory location and the reference is moved to the new
location.
Some Strings will point to the same reference object in
memory.
Making a modification to one String that is pointing to the
shared reference will not make a modification to the others.
The one that you modify points to the new memory address
that holds the new/modified string and the others still point
to the original one.

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

String Concatenation Example


What will be the output of s1, s2, s3, and s4 at the end of
these statements?
String s1 = "This is a ";
String s2 = "string";
String s3 = s1 + s2;
String s4 = "This is a " + s2;
String s1 += s2;
System.out.println("s1: " + s1);
System.out.println("s2: " + s2);
System.out.println("s3: " + s3);
System.out.println("s4: " + s4);

Enter these statements in a Java program and check the


results. Did you guess correctly?
JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Escape Sequences
Escape sequences in string literals allow the user to add
characters that would be misinterpreted by the compiler.
For example, to include a double-quote in your String, the
compiler would interpret the double-quote as the beginning
or ending of your String rather than including it.
Use the escape sequence \" to include a double-quote.
String s1 = "This is an example of an escape.
\n And now we're on a new line. \n \t This is a tab."
String s2 = "\"This is a quote \"";
System.out.println(s1);
System.out.println(s2);

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Common Escape Sequences in Java


Here is a list of a few common escape sequences in Java.
Escape Sequence

Representation

Alternate Octal
Escape
Representation

\"

Double quote

\u0022

\'

Single quote

\u0027

\\

Backslash

\u005c

\t

Horizontal tab

\u0009

\n

Line feed

\u000a

\b

Backspace

\u0008

\r

Carriage return

\u000d

\f

Form feed

\u000c

Octal Escape

Octal value

\u0000 to \u00ff

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

compareTo() Method
Methods to use when comparing Strings.
Method: s1.compareTo(s2)
Should be used when trying to find the lexicographical order of two
strings.
Returns an integer.
If s1 is less than s2, an int < 0 is returned.
If s1 is equal to s2, 0 is returned.
If s1 is larger than s2, an int > 0 is returned.

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

equals() Method
Methods to use when comparing Strings.

Method: s1.equals(s2)
Should be used when you only wish to find if the two strings are equal.
Returns a boolean value.
If true is returned, s1 is equal to s2.
If false is returned, s1 is not equal to s2.

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

compareTo() and equals() Methods


Example
What will this compareTo() method print?
String s1 = "abc";
String s2 = "cde";
System.out.println(s1.compareTo(s2));

What will this equals() method print?


String s1 = "abc";
String s2 = "ABC";
System.out.println(s1.equals(s2));

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

compareTo() and equals() Methods


Example Solution
This compareTo method prints an int less than 0.
String s1 = "abc";
String s2 = "cde";
System.out.println(s1.compareTo(s2));

This equals method prints false.


String s1 = "abc";
String s2 = "ABC";
System.out.println(s1.equals(s2));

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Comparing Strings with ==


Primitive variables can be compared with ==.
This method of comparison does not always work with Strings
and should be avoided unless trying to compare the memory
address location of two String objects.
== compares reference values, not values.
Will only be true if the two String objects are pointing to the
same reference object.
String
String
String
String

s1
s2
s3
s4

=
=
=
=

"This is a String.";
new String("This is a String.");
"String.";
"This is a " + s3;

System.out.println(s1 == s2);
System.out.println(s1 == s4);

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Comparing Strings with ==


Which will print true in the example below?
s1 and s2 will point to the same object. Java notices that they
are the same and makes the reference the same.
s5 will not point to the same object as s1. It is "built" from a
combination of two Strings, and therefore, a new object is
created.
String
String
String
String
String

s1
s2
s3
s4
s5

=
=
=
=
=

"This is a String.";
"This is a String.";
"This is ";
"a String.";
s3 + s4;

System.out.println(s1 == s2);
System.out.println(s1 == s5);

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Useful String Method: length()


Method: s1.length()
Returns the length, or the number of characters, in s1 as an
int.
String length is an accessor method called on a String object
that will return the length variable of the String.
String s1 = "This is a string.";
int n = s1.length();
//n is 17 because s1 has 17 characters

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Each String Character Has an Index


Since Strings are a representation of a sequence of
characters, each character of a String has an index.
An index is a position reference.
The first character of a String has an index of 0, the second
has an index of 1, and so on until the end of the String.

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Useful String Method: substring()


s2.substring(int beginIndex)
Returns part of the string s2 from the beginIndex to the end of the
String.

s2.substring(int beginIndex, int endIndex)


Returns part of the string s2 from the beginIndex to the endIndex but
does not include the character at endIndex.
What is displayed as a result of this code segment?
String s1 = "I eat apples";
String s2 = "Bananas are my favorite fruit";
System.out.println(s1.substring(6)+" "+s2.substring(8,23);

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Useful String Methods: indexOf and charAt


Method:

s3.indexOf(char c);

Returns the index value of the first occurrence of c in String s3.

Parameter does not need to be a character, it can also be a


String, for example: s3.indexOf("the");
Method:

s4.charAt(int index);

Returns the character of the String located at the index passed as the
parameter.
Index can be an integer from 0 to s4.length()-1.

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Using String Methods Example 1


Write the Java code that will take an email address as input in
the form of a String. This method will return the domain.
For example, if the user enters john@oracle.com, the method
returns oracle.com.
To solve this problem, first search for the '@' character in the
String. Then output the substring portion of the initial String
that comes after this position.
String domain="";
//no space between the " and "
int position=email.indexOf('@');
domain=email.substring(position+1);
System.out.println(domain);

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Terminology
Key terms used in this lesson included:
Concatenation
Escape sequences
Instantiate
Reference object
String object
String methods compareTo() and equals()

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Summary
In this lesson, you should have learned how to:
Instantiate (create) a String
Describe what happens when a String is modified
Use the + and += operators for concatenating Strings
Interpret escape sequences in String literals

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Summary
In this lesson, you should have learned how to:
Recognize the difference between a String and a primitive
char data type
Test Strings with the compareTo() and equals() method
Describe why the == operator does not always work when
testing String equality
Use String methods length(), substring(), indexOf(), and
charAt()

JF 4-4
Strings

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Java Fundamentals

5-1:
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Use Scanner for user input during program execution
Use if-else logic and statements
Apply switch logic and statements in Java code
Use break and default effectively in a switch statement
Use the ternary operator

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Prompting the User for Input: Scanner


Keyboard input using a Scanner requires the following import
statement:
import java.util.Scanner;

Prompting the user can be done with simple code that will
appear in the console screen where the user can then enter
their input.
System.out.println("Write instructions for user here.");

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Scanner
To read in the input that the user has entered, use the Java
object Scanner.
To initialize a Scanner, write:

Scanner in = new Scanner(System.in);

Scanner is commonly named "in"


which is short for "input"

JF 5-1
Scanner and Conditional Statements

System.in is used for the scanner to


read the users' input from the
console screen.

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Why Scanner?
Scanner makes it easy to read in the user's input because it
already has methods that do this very task.
The Scanner method next() reads in the user's input as a
String and returns that String. This line of code:
Creates a new string called input.
Scans in the string that the user has entered into the output
console using the scanner called in.
Sets input equal to the string that was read in by the scanner.
String input = in.next();
JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Scanner's nextInt() Method


The Scanner method nextInt() reads in the user's input as an
integer and returns that integer. This line of code creates a
new int, called answer.
import java.util.Scanner;
public class InputExample{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter your name:");
String name = in.next();
System.out.println("Enter a number:");
int answer = in.nextInt();
System.out.println(name + ", the number you entered is: " + answer);
}
}

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

More Useful Scanner Methods


Method

What It Does

When to Use

nextInt()

Similar to next(), this function


reads in the user's input and
returns it's integer value.

When you prompt the user for an


integer value and wish to read in
the user's input as an integer rather
than as a string.

hasNext()

Returns true if the scanner has


another input, and false
otherwise.

When you wish to know if there is


any more input for the scanner to
read in.

close()

Closes the scanner.

When you are done reading in


input, it is good practice to close
the scanner, especially when
reading input from the console
screen. This keeps the program
from running continuously. The
scanner may expect more input if it
is never closed.

hasNext() and close() are used for


reading files.

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Relational Operators
Java has six relational operators used to test primitive or
literal numerical values. Relational operators are used to
evaluate if-else and loop conditions.
Relational Operator

Definition

>

Greater than

>=

Greater than or equal to

==

Equal to

<

Less than

<=

Less than or equal to

!=

Not equal to

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Relational Operators Example


Values are tested on either side of the operator and a true or
false value is returned. This value can be stored or used as
part of a control structure to control program flow.
In this example, the variable madeHonorRoll is assigned a
true value when the expression grade >= 88 evaluates as true.
int grade = 99;
boolean madeHonorRoll = grade >= 88;
if(madeHonorRoll)
System.out.println("You made the Honor Roll.");

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Relational Operators Example


The same example can be evaluated with the use of the
boolean variable.
However, the expression grade >=88 evaluates as true or false
depending on the value assigned to grade.
Boolean values are necessary as a condition in an if-else
statement or loop.
int grade = 99;
if(grade >= 88)
System.out.println("You made the Honor Roll.");

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Logic Operators
Java has three logic operators used to combine boolean
expressions into complex tests.

Logic Operator

Meaning

&&

AND

||

OR

NOT

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Logic Operators Example 1


In this example, the phrase "You qualify for the scholarship"
will print if both conditions are true. For the message to print,
madeHonorRoll must be true and the numberDaysAbsent
must be equal to zero.
int numberDaysAbsent = 0;
int grade = 99;
boolean madeHonorRoll = grade >= 88;
if(madeHonorRoll && numberDaysAbsent==0)
System.out.println("You qualify for the scholarship.");

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Logic Operators Example 2


Describe the results for each of the following Java code
segments.
double grade=65;
int numDaysAbsent=2;
boolean madeHonorRoll = grade >= 88;
if(!madeHonorRoll && numDaysAbsent<3)
System.out.println("You qualify for free tutoring help.");

if(grade > 70 && numDaysAbsent < 5)


System.out.println("You may try out for the sports team.");

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Logic Operators Example 2 Solution


Results for each of the following Java code segments:
The phrase "You qualify for free tutoring help." prints to the
screen.
However the phrase "You may try out for the sports team."
does not print as the student's grade is not above 70.
double grade=65;
int numDaysAbsent=2;
boolean madeHonorRoll = grade >= 88;
if(!madeHonorRoll && numDaysAbsent<3)
System.out.println("You qualify for free tutoring help.");
if(grade > 70 && numDaysAbsent < 5)
System.out.println("You may try out for the sports team.");

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Syntax for if-else Statements


To build an if-else statement, remember the following rules:
An if-else statement needs a condition or method that is tested for
true/false. For example:
if(x==5)
if(y >- 17)
if(s1.equals(s2))

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Syntax for if-else Statements


Likewise, an optional else if statement can be tested, for
example:
else if(y==7)
else if(z != 2)

The optional else statement will take care of every other


possibility.

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

if-else Statements with the char Data Type


import java.util.Scanner;
public class Calculator{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int answer = 0;
System.out.println("Enter a number:");
int num1 = in.nextInt();
System.out.println("Enter another number:");
int num2 = in.nextInt();
System.out.println("Enter the operand:");
char input = in.next().charAt(0);
if( input == '*' )
answer = num1 * num2;
else if( input == '/' )
answer = num1 / num2;
else if( input == '%' )
answer = num1%num2;
else if( input == '+' )
answer = num1 + num2;
else if( input == '/' )
answer = num1 / num2;
else
System.out.println("Invalid Command");
System.out.println("The result is: " + answer);
}
JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

if-else Statements with the int Data Type


import java.util.Scanner;
public class ValueChecker{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int value = 0;
System.out.println("Enter a number:");
value = in.nextInt();
if( value == 7)
System.out.println("That's lucky!");
else if( value == 13)
System.out.println("That's unlucky!");
else
System.out.println("That is neither lucky nor unlucky!");
}
}

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

if-else Statements
with the String Data Type
import java.util.Scanner;
public class StringChecker{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String name = "";
System.out.println("Enter your name:");
name = in.next();
if( name.equals("Elvis"))
System.out.println("You are the king of rock and roll");
else if( name.equals("Michael Jackson"))
System.out.println("You are the king of pop!");
else
System.out.println("You are not the king");
}
}

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Switch Statement
Like the if-else example earlier, consider a program that takes
two integer inputs from a user and performs a specified
mathematical operation.
To support different operators a test is needed to see if the
input was any of the following:
* / + - %

How would you check to see what the user typed?

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Switch Statement Changes Program Flow


A switch statement is another way of changing program flow
depending on the input value.
See the next slide for an example.

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Switch Statement Changes Program Flow


import java.util.Scanner;
public class Calculator{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int answer = 0;
System.out.println("Enter a number:");
int num1 = in.nextInt();
System.out.println("Enter another number:");
int num2 = in.nextInt();
System.out.println("Enter the operand:");
char input = in.next().charAt(0);
switch (input){
case '*' :
answer = num1 * num2;
break;
case '/' :
answer = num1 / num2;
break;
case '%' :
answer = num1 % num2;
break;
case '+' :
answer = num1 + num2;
break;
case '-' :
answer = num1 - num2;
break;
default:
System.out.println("Invalid Command.");
}
}
}

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Switch Statement Keywords


A switch statement uses 3 keywords: switch, case, and
default.
switch: specifies which variable to test for value.
case: compares the value of the switch variable.
default: when the input does not match any of the cases, the compiler
chooses the default action (like else in a list of if statements).

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Additional Information about Switch


Statements
After each case, include the keyword break. If not included,
the code will "fall through" and execute each case until break
is encountered.
In Java SE 7 and later, you can use a String object in the switch
statement's expression.

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Switch Statement Example 1


This example shows how "fall through" behavior works. For
membership sales, the more memberships sold, the more
prizes a sales rep wins for those sales.
import java.util.Scanner;
public class SalesWinners {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("How many memberships did you sell?");
int sales = in.nextInt();
switch(sales){
case 6:
case 5:
case 4:
case 3:
case 2:
case 1:
break;
default:

System.out.println("You
System.out.println("You
System.out.println("You
System.out.println("You
System.out.println("You
System.out.println("You

win
win
win
win
win
win

$1000");
a Samsung Galaxy III-S");
Laptop");
iPod");
Stapler");
Staple Remover");

System.out.println("No Gift");

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Switch Statement Example 2


A 9th year student in high school is considered a freshman,
10th year students are sophomores, etc.
import java.util.Scanner;
public class ClassYear {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("What grade are you in?");
int grade = in.nextInt();
switch(grade){
case 9: System.out.println("You are a freshman");
break;
case 10: System.out.println("You are a sophomore");
break;
case 11: System.out.println("You are a junior");
break;
case 12: System.out.println("You are a senior");
break;
default: System.out.println("Invalid grade");
}
}
}

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Switch Statement Example 3


Given a month and year, the number of days in the month are
calculated. Encourage students to research "Leap Year" rules.
See the next slide for the example.

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Switch Statement Example 3


import java.util.Scanner;
public class LeapYearCalculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the month");
int month = in.nextInt();
System.out.println("Enter the year");
int year = in.nextInt();
switch(month){
case 4:
case 6:
case 9:
case 11: System.out.println("That month has 30 days");
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: System.out.println("That month has 31 days");
break;
case 2:

if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){


System.out.println("That month has 29 days");
}
else{
System.out.println("That month has 28 days");
}
break;
default:
System.out.println("Invalid Input");

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Ternary Operator
The ternary operator (?:) in Java is used to create a shorter
version of an if-else statement.
In the following example, there are three parameters using
this operator.
The first is the boolean test (c>9).
The second (6) is the value to return if the test is true.
The third (7) is the value to return if the test is false. It is
often used as part of an assignment.
int x = c > 9 ? 6 : 7;

//If c is greater than 9, x is 6; else x is 7

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Ternary Operator Example


Here, an if-else statement is used to check for String equality.
String s1 = "Hello";
String s2 = "Goodbye";
if(s1.equals(s2))
System.out.println("Yes");
else
System.out.println("No");

A similar result is achieved using the ternary operator.


String s1 = "Hello";
String s2 = "Goodbye";
String answer = s1.equals(s2) ? "Yes" : "No";
System.out.println(answer);

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Terminology
Key terms used in this lesson included:
if statements
If-else statements
Scanner
switch statements (case, switch, and default)
Ternary operators

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Summary
In this lesson, you should have learned how to:
Use Scanner for user input during program execution
Use if-else logic and statements
Apply switch logic and statements in Java code
Use break and default effectively in a switch statement
Use the ternary operator

JF 5-1
Scanner and Conditional Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Java Fundamentals

5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Create a while loop
Create a do-while loop
Create a for loop

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

What is a Loop?
Many everyday tasks involve doing an action,
and then repeating the same procedure or
action on a different object.
When folding clean clothes, there are three
basic steps:
Pick up the piece of clothing.
Fold it.
Put it away.

For each piece of clothing, these actions are


repeated. Each time you execute the action,
only your input (the specific piece of clothing)
is different.
JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Loops
In programming, there are times when you want to work with
multiple inputs, but you want to execute the same logic for
each input item.
A loop allows you to have a series of inputs with the same
code.
Loops will start at the beginning of a piece of code, execute
the logic you wish, and then return to the beginning of the
loop with new input, ready to execute the code once more.

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Why are Loops Useful?


Suppose you have a list of ten numbers and you want to find
the sum of those numbers. You could create a statement like
this:
sum = num1 + num2 + num3 + num4 + + num10;

While this is fairly simple code, using a loop will simplify the
code further.
loop (loop condition){
input currentNumber
sum = sum + currentNumber;
}end loop

JF 5-2
Control Statements

When the loop executes the first


time,
the input will accept a number,
and for
each time the loop runs, the sum
will increase by that number.

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Loop Control: Stopping the Loop


For code to enter a loop and execute the code inside, the
loop condition must be true.
To end the loop, the loop condition must be false.
When creating loops in Java, a condition must change from
true to false in order for code to exit the loop.

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Stopping Conditions
A loop needs a stopping condition, which could be specified
as:
A set number of times to run the code.
A boolean condition that is changed in the code to make the loop stop
executing.

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Types of Loops
Java has three basic types of loops that work with these two
types of stopping conditions:
while loops
for loops

Pre-test loops: The condition is


tested prior to execution of the
loop. If the condition is false, the
loop will stop, or may never
execute.

do-while loop
Post-test loop: The condition is
tested after the each execution of
the loop. If the condition is false,
the loop will still execute at least
once, but will stop at the end of
the loop.

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

The while Loop


The while loop is designed to loop while something remains
true.
Example condition:
While there are more numbers to enter.

Think of the example as a true/false condition, or boolean


condition:
If the condition "There are more numbers to enter" is true, continue to
accept input.
When the condition "There are more numbers to enter" is false, stop
accepting input.

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Infinite Loops
If you do not allow for a change in the condition, the loop will
run forever as an infinite loop.

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Java Syntax for while Loops


With a while loop, Java uses the syntax:
while(condition is true){
//logic
}

Similar to if statements, the while loop parameters can be


boolean types, or can produce a boolean value.
Conditional statements using (<, >, <=, >=, !=, ==) produce
boolean values.
Examples:
while (num1 < num2)
while (isTrue)
while (n !=0)
JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

While Loop Example


Implementation using a while loop is shown below.
This example adds a sequence of ten integers that are input
by the user.
Notice that the loop condition is
tested before each execution of
import java.util.Scanner;
the loop. This is a pre-test loop.
public class LoopPractice{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int numInputs = 0;
int sum = 0;
while(numInputs < 10){
//condition to be tested each time loop is executed
input = in.nextInt();
//user inputs a number
sum+=input;
//add user input to sum
numInputs++;
//statement that will change the loop condition
}
System.out.println("The sum of those ten numbers is: " + sum);
}
}
}
JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Using a while Loop with String Methods


A palindrome is a word spelled the same forward or
backward. Examples: deed, racecar, and level.
Write Java code that asks for a word and returns true if it is a
palindrome, and false if it is not.
This code should:
Calculate the length of the word.
Compare the first and last letters if they match.
Compare letters until the middle of the word is reached.

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Using a while Loop with String Methods


Example
Palindrome method code:
public class PalindromeTester{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter a word:");
String word = in.next();
int firstPosition = 0;
int lastPosition = word.length() - 1;
boolean isAPalindrome = true;
while(firstPosition < lastPosition){
if(word.charAt(firstPosition)!=word.charAt(lastPosition))
isAPalindrome = false;
firstPosition++;
lastPosition--;
}
if(isAPalindrome)
System.out.println("The word is a Palindrome");
else
System.out.println("The word is not a Palindrome");
}
}

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

The do-while Loop


The do-while loop:
Is a post-test loop.
Is a modified while loop that allows the program to run through the
loop once before testing the boolean condition.
Continues until the condition becomes false.

If you do not allow for a change in the condition, the loop will
run forever as an infinite loop.

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

The do-while Loop Insect Example


Consider the movement of a flying insect that lands on each
flower it sees.
To recreate this insect's movement in code, you could use a
do-while loop.

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Insect Action Pseudocode


Pseudocode for the movement of a flying insect that lands on
each flower it sees:

The insect is initially flying, before any condition is tested.


The insect continues to fly until it spots a flower.
The condition that will be tested is noFlowerSpotted.
When noFlowerSpotted is true, the insect will continue flying. When it
is false, the insect will stop going through the loop and land on the
flower.

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Java Syntax for do-while Loops


The do-while loop uses the same boolean logic that is used
for a regular while loop.
The do code block is run once, and the while condition is
tested at the end of each run of the code.
First, the do code block is executed.
Next, the condition is tested.
This repeats until the condition becomes false.

do-while loop syntax:


do{

//statements to repeat go here


} while(condition);

JF 5-2
Control Statements

Do not forget the semicolon or the


code will not compile.

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

The do-while Loop Insect Example Code


The insect flies until it finds a flower, then lands.
Step 1: The insect begins to fly before testing if it can see a
flower.
Step 2: Test if the insect sees a flower.
If the insect does not see a flower, repeat steps 1 and 2.
If the insect sees a flower, go to the final step.
do {

insect.fly();
} while(noFlowerFound)
insect.land();

JF 5-2
Control Statements

//Step 1
//Step 2
//Final Step

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

do-while Loop Example


Implementation using a do-while loop is shown below. This
example also a sequence of ten integers that are input by the
user. Can you see and explain the differences in this example
and the pre-test loop?
import java.util.Scanner;
Notice that the loop condition is
public class LoopPractice{
tested after each execution of the
public static void main(String[] args){
Scanner in = new Scanner(System.in);
loop. This is a post-test loop.
int numInputs = 0;
int sum = 0, input = 0;
do{
System.out.println("Enter a number");
input = in.nextInt();
//user inputs a number
sum+=input;
//add user input to sum
numInputs++;
//statement that will change the loop condition
} while(numInputs < 10);
System.out.println("The sum of those ten numbers is: " + sum);
}
}

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

do-while Loop Example


import java.util.Scanner;
public class LoopPractice2{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int repeat = 0;
do{
System.out.println("Enter a number");
input = in.nextInt();
//user inputs a number
sum+=input;
//add user input to sum
System.out.println("Do you want to enter another number?");
System.out.println("Enter 1 for yes or 2 for no:");
repeat = in.nextInt();
} while(repeat==1);
System.out.println("The sum of the numbers is: " + sum);
}
}

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

The for Loop


Recall the folding clothes example.
If we know how many pieces of clothing we have, we know
exactly when the condition "There are more clothes" will be
false.
for loops tell the loop when to stop by explicitly saying "Stop
when the loop has run once for every piece of clothing."
For example, if we have ten pieces of clothing, we can tell the
loop, "Run 10 times" since we know that after the tenth
execution, there will not be any more clothes.

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

for Loop Java Syntax


for loop syntax contains three parts:
Initializing the lcv (loop control variable).
Conditional statement, or stopping condition.
Updating the counter (going to the next value).
Think of i as a counter, starting at 0 and incrementing until i=timesToRun.

for loop syntax:

for loop naming conventions


typically will use i as the lcv
variable name.

for(int i=0; i < timesToRun; i++){


//logic
}

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

for Loop Explained


The for loop has the following components:
Initializing the counter variable (i).
Often, i is set to 0 (zero), thereby starting the count at 0.

Conditional statement, or stopping condition.


The loop will continue to execute while i < timesToRun, which means it
will run timesToRun times.

Updating the counter (going to the next value).


Every time the loop runs, i is incremented by one (the ++ operator adds
one to i).
for(int i=0; i < timesToRun; i++){
//statements to repeat
}

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

for Loop Example 1


Review the example code below to fold ten articles of
clothing.
Can you identify the three parts of the for loop in this
example?
for(int i = 0; i < numFolded; i++)
{
fold();
}
System.out.println("All Done!");

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

for Loop Example 2


This example is a sequence of ten integers that are input by
the user. Can you see and explain the differences in this
example and the post-test loop?
import java.util.Scanner;
public class LoopPractice{
The loop condition is
public static void main(String[] args){
tested before each
Scanner in = new Scanner(System.in);
execution of the loop. This
int numInputs = 10;
is a pre-test loop.
int sum = 0;
for(int i = 0; i < numInputs; i++){
input = in.nextInt();
//user inputs a number
sum+=input; //add user input to sum
}
System.out.println("The sum of those ten numbers is: " + sum);
}
}

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Which Loop Do I Use?


Loop Type Definition

When to Use

while

Pre-test loop that repeats


until a specified condition
is false.

Use when you are not certain the


number of times the loop should be
executed or even if it should at all.

do-while

Post-test loop that


executes the loop before
testing the condition, then
repeats until the condition
is false.

Use when you know that the code


must be executed at least once
and possibly more times depending
on the condition.

Loop that contains an


initialized counter, and
increments the counter
with each run through the
loop. Repeats until the
condition is false.

Use when you need to execute a


loop a specific number of times, or
when you need to increment
through a set of data. The counter
can also be used as an index for
accessing data one item at a time.

for

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Using break and continue


break and continue are both keywords in Java that aid in
controlling the flow of your program.
The keyword break is useful for instances where you wish to
exit a loop at a specified point that is different than the
condition statement.
Using break in a loop will cause code to exit the loop.

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Using break and continue


The keyword continue is useful for special cases where you
want to exclude code for a particular element in a list.
Using continue will cause the code to skip the rest of the code
in the loop and evaluate the condition statement (in a for
loop, the lcv will also increment).

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

break Example
This example will ask for to input a number ten times.
If the user enters the value 999, the loop will terminate
regardless of the value of i (the lcv).
import java.util.Scanner;
public class BreakExample{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int numInputs = 10, input = 0, sum = 0, stopLoop = 999;
for(int i = 0; i < numInputs; i++){
input = in.nextInt();
//user inputs a number
if(input==stopLoop)
//if the number is 999, exit the loop without adding to the sum
break;
else
sum+=input;
//if the number is not 999, add it to the sum
}
System.out.println("The sum of the numbers entered is: " + sum);
}
}

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

continue Example
Given a list of integers (you want to output a message for all
the odd numbers, and you want to skip over the even
numbers), this can be done using the following code.
import java.util.Scanner;
public class ContinueExample{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int numInputs = 10, input = 0;
for(int i = 0; i < numInputs; i++){
//user inputs a number
input = in.nextInt();
if(input % 2 == 0)
//if it's even
continue; //skip the remaining code in the loop, increment i, re-check the
System.out.println("That number was odd"); //output only if odd
}
}
}

JF 5-2
Control Statements

condition

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

if, do-while, and switch Example


import java.util.Scanner;
public class Section5Example{
public static void main(String[] args){
boolean quit = false;
int num1, num2, answer;
char operand = '';
Scanner in = new Scanner(System.in);
do {
System.out.println("Please enter a mathematical operand");
String input = in.next();
char operand = input.charAt(0);
/*changes the string into a char since
switch case uses chars*/
switch(operand) {
case '*':
answer = num1 * num2;
break;
case '+':
answer = num1 + num2;
break;
case '-':
answer = num1 num2;
case '/':
answer = num1 / num2;
default:
System.out.println("Invalid input.");
}
System.out.println("Quit? Y/N");
/* prompt the user if they'd like to quit.*/
if(in.next().equalsIgnorecase("Yes"))
quit=true;
} while(!quit);
}
}

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Terminology
Key terms used in this lesson included:
break
continue
do-while loop
for loop
while loop

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Summary
In this lesson, you should have learned how to:
Create a while loop
Create a do-while loop
Create a for loop

JF 5-2
Control Statements

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

35

Java Fundamentals

6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Write a single-dimensional array in a Java program using
primitive data types
Write a single-dimensional array in a Java program using
reference (Object) types
Write a 2-dimensional array in a Java program using primitive
data types
Write a 2-dimensional array in a Java program using reference
(Object) types
Declare an array, initialize an array, and traverse the array
JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Overview
This lesson covers the following topics:
Describe array initialization
Distinguish between the String method length() and an
array's length value
Rewrite a Java program to store integers into an array,
perform a mathematical calculation, and display the result
Use alternative array declaration syntax

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

What is an Array?
An array is a collection of values of the same data type stored
in a container object.
Can be any number of values.
Length of the array is set when the array is declared.
Size is fixed once the array is declared.

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Array Elements
Every value is called an element
Each element is accessed by an index.
Index must be an integer.
Index always starts at 0.

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Array Data Types


Arrays may contain any data type, such as:
Primitive
Pre-defined objects, such as Strings from the Java API
Programmer-Defined objects, such as instances of a class that
you create

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Declaring an Array
There are three parts to declaring an array:
Data type
Variable name
Array size

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Declaring an Array Examples


An array declaration can be done in one or two lines.
Both examples below are equivalent array declarations.
data_type[] variable_name;
variable_name = new data_type[size];
//declare an array using two lines of code
data_type[] variable_name = new data_type[size];
//declare an array using one line of code

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Declaring an Array Example


A friend brings you a bouquet of six different flowers.
You want to write a program to store each type of flower in
the bouquet.
The code segments below are identical ways to declare an
array of Strings called myBouquet.
The size is set to six elements so it may store each type of
flower in your bouquet.
String[] myBouquet;
myBouquet = new String[6];
String[] myBouquet = new String[6];

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

myBouquet Array Example Explained

String[] myBouquet;
myBouquet = new String[6];
String[] myBouquet = new String[6];

Data type stores


the types of
flowers as Strings.

Array name is
myBouquet.

JF 6-1
Arrays

The size of the


array is 6 elements,
one for each
flower.

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Identify Components of an Array


Declaration
Identify the three components of an array declaration for
each of these arrays of primitive data types.
int[] myArray;
myArray = new int[20];
char[] sentence = new char[100];
double[] teamPoints = new double[5];

Data Type
Name
Size

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Alternative Array Declaration Syntax


An alternative way to declare arrays is to place the brackets
used to declare an array on either side of the array identifier.
Syntax introduced:
int[] primeNumbers;
int[] evenNumbers;
double[][] prices;
String[] words;
Point[] coordinates;
Rectangle[][] blocks;

JF 6-1
Arrays

Alternate syntax:
int primeNumbers[];
int evenNumbers[];
double prices[][];
String words[];
Point coordinates[];
Rectangle blocks[][];

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Alternative Array Declaration Syntax


Either declaration will work.
The Alternate Syntax is similar to that used in the language of
C.
The syntax used to introduce arrays actually reads much
clearer.
The first line would read "Integer array primeNumbers."
Syntax introduced:
int[] primeNumbers;
int[] evenNumbers;
double[][] prices;
String[] words;
Point[] coordinates;
Rectangle[][] blocks;

JF 6-1
Arrays

Alternate syntax:
int primeNumbers[];
int evenNumbers[];
double prices[][];
String words[];
Point coordinates[];
Rectangle blocks[][];

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Initializing an Array
Once you declare an array, you must initialize it to set the
values for specified indexes.
There are three components to initializing an array:
Variable name
Index
Value

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Ways to Initialize an Array


An array can be initialized in two different ways:
Declare the array, then initialize each element.
Have declaration and initialization occur in the same step.

Example of declaring and initializing in two steps:


data_type[] variable_name = new data_type[size];
variable_name[index] = value; //repeat for each index

Example of declaring and initializing in one step:


data_type[] variable_name = {val1, val2, };

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Initializing an Array Example 1


Recall the declaration of the String array myBouquet.
Once the array is declared, the code below initializes the
elements and stores the flower types.
The index of an array begins at 0, so the first element will be
added to index 0.
String[] myBouquet = new String[6];
myBouquet[0] = "Rose";
myBouquet[1] = "Sunflower";
myBouquet[2] = "Daisy";
myBouquet[3] = "Dandelion";
myBouquet[4] = "Violet";
myBouquet[5] = "Lily";

Variable Name

Index
JF 6-1
Arrays

//previous declaration
//Store "Rose" as the first element
//Store "Sunflower" as the second
//and so on
//"Lily" is the last (sixth) element

Value

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Initialize an Array Example 1


The array of flower types will look like this:
Index:

Value:

Rose

Sunflower

Daisy

Dandelion

Violet

Lily

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Initialize an Array Example 2


The array myBouquet could also be declared and initialized
using the second notation as follows:
String[] myBouquet = {"Rose", "Sunflower", "Eucalyptus", "Dandelion", "Violet", "Lily"};

Notice that using this method does not specify size, but it is
assigned a size based on the number of elements in the list
between the {}.

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

First Notation versus Second Notation


It seems that the second notation is much shorter and easier
to code.
Why would you need the first notation?

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

First Notation versus Second Notation


Consider taking in five numbers from a user and storing them
in an array called myArray.
You would need to declare the array, then initialize the
elements one at a time as the user enters each number.
int[] myArray = new int[5]; //Declare the array of size 5
MyArray[0] = 7;
//The user entered 7
MyArray[1] = 24;
//The user entered 24
MyArray[2] = 352;
//The user entered 352
MyArray[3] = 2;
//The user entered 2
MyArray[4] = 37;
//The user entered 37

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

First Notation versus Second Notation


The second notation may be an easier way to initialize the
array if you already know the contents of the array when
declaring it.
int[] myArray = {7, 24, 352, 2, 37};

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Array Representation
When arrays are declared but not yet initialized, the elements
are given the default value associated with the data type.
For example, the default for numeric data types, such as int,
is 0. The default for Object types, such as String is "" (null).
When the array is declared, the representation in the table is
as follows.
int[] myArray = new int[5];

Index:

Value:

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Updated Array Representation


Once you begin to initialize elements, the array is updated.
The new representation in the table is as follows.
myArray[0] = 32;
myArray[3] = 27;

Index:

Value:

32

27

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Arrays Object Types


Arrays are not restricted to storing primitive data types.
They can store any object type, including types you define.
For example, if a Flower class existed:
The flowers could be stored in the array rather than storing
the flower type as a String.
Since we know what flowers to include, the second notation
can be used to initialize myBouquet of six Flowers.
Flower[] myBouquet = {new Flower("Rose"), new Flower("Sunflower"),
new Flower("Daisy"), new Flower("Dandelion"),
new Flower("Violet"), new Flower("Lily")};

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Accessing Array Length


With each declaration of an array, you must define a size, or
length, of the array.
The length is stored as an instance variable for that object
and can be accessed using the arrayName.length notation.
This technique is useful in the following example:

Establish an array with a size based on the user input.


Enter a segment of code where the user's input is no longer in scope.
You would need to access the instance variable length for that array.
In short, arr.length returns the length of the array, arr.

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Iterate Through an Array


To iterate through, or traverse, an array means to progress
through each element of the array by index number.
Iterating through an array is useful when:
You wish to access each element of an array in order.
You wish to initialize the elements of an array as all the same value.

Use .length when iterating rather than the integer value


entered when declaring the array.
This will assure that you do not receive an index out of
bounds error.
JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Iterate Through an Array Example


To initialize an array of integers called allTwos, so that each
element is 2, use a for loop as shown below.
The first line of code is the array declaration. It declares an
array called allTwos with a size of 10.
The for loop iterates through the indexes and for each index
in the array, the value at that index is set to 2.
int[] allTwos = new int[10];
for(int index = 0; index < allTwos.length; index++){
allTwos[index] = 2;
Note how the length of the
}

array is accessed to keep from


going out of bounds for the
array's index.

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

When Iteration is Helpful


In the flower example, iteration helps if you wish to print out
the flower types stored in the myBouquet array.
String[] myBouquet = {"Rose", "Sunflower", "Daisy", "Dandelion", "Violet", "Lily"};

Use a for loop to iterate through this array.


The initialized counter within the for loop can be used for
incrementing through the indexes, as shown below.
What displays as a result of this code?
//remember that the index range is 0 to 5 for an array of size 6
for(int index = 0; index < myBouquet.length; index++){
System.out.println(myBouquet[index]);

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

for-each Loop
Java offers a for-each loop, an alternative to using the
initialized counter to iterate through an array.
When used to access the elements of an array, the for- each
loop works the same way as the for loop, but is implemented
in a simpler way.
If we replace the for loop code from our previous example
with the following code, we get the same result.
//remember that the index range is 0 to 5 for an array //of size 6
for (String myFlower : myBouquet)
{
System.out.println(myFlower);
}

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

for-each Loop
The for-each loop accesses and (one-at-a-time) returns all
elements of an array.
Changes to the array elements cannot be made using a for each loop.If we replace the for loop code from our previous
example with the following code, we get the same result.
The example below will print the length of each string in the
array myBouquet.
//remember that the index range is 0 to 5 for an array //of size 6
for (String myFlower : myBouquet)
{
System.out.println(myFlower);
}

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

for-each Loop Example


Both implementations of the code below will display the
information about the array elements.
public class Bouquet {
public static void main(String[] args){
String[] myBouquet = {"Rose","Sunflower","Daisy",
"Dandelion","Violet", "Lily"};
//use a for loop to iterate through the array
for(int index = 0; index < myBouquet.length; index++){
System.out.println(myBouquet[index]);
}

//use a for each to iterate through the array


for (String myFlower : myBouquet){
System.out.println(myFlower);
}

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

What We Know About Arrays


What we know about arrays:
Arrays are an object type that can store any primitive or object type.
Therefore, arrays can store arrays.
The concept of storing an array of arrays is called a two-dimensional
array.

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Two-Dimensional Arrays
A two-dimensional array, called an "array of arrays," is an
array that stores other arrays.
The number of arrays contained within the array is defined
upon declaration.
The number of items in each internal array is also defined
upon declaration.

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Two-Dimensional Array Example


This example shows an array of two arrays with three
elements in each array.
A two-dimensional array can be visualized as a table with
rows and columns.
The example below has two rows and three columns.
int[][] nums = { {14,51,16}, {12,73,87} };

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

35

Declaring a Two-Dimensional Array


Components of two-dimensional arrays:
Data type
Variable name
Array size

To declare a two-dimensional array, use either of the syntax


examples below.
data_type[][] variable_name;
variable_name = new data_type[size1][size2];
//declare it using two lines of code
data_type[][] variable_name = new data_type[size1][size2];
//declare it using one line of code

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

36

Declaring a Two-Dimensional Array


Example 1
Identify the three components in the following primitive data
type examples.
int[][] myArray;
myArray = new int[2][3];
char[][] sentence = new char[10][10];

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

37

Declaring a Two-Dimensional Array


Example 1
When declaring a two-dimensional array:
The number in the first set of brackets [2] is the number of arrays the
container holds (rows).
The number in the second set of brackets [3] is the number of
elements in each of those arrays (columns).

Another way to declare myArray may look like this:


int[][] myArray = { {0,0,0}, {0,0,0} };

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

38

Declaring a Two-Dimensional Array


Example 2
Your friend brought you three of each type of flower, and
each of the three flowers are different colors.
A single-dimensional array makes it tedious to keep track of
this data.
A two-dimensional array allows you to store six arrays, one
for each flower type, and have each array store the colors of
each of the three flowers.
The following code declares an array that holds six arrays,
each of length three:
String[][] myBouquet = new String[6][3];

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

39

Initializing a Two-Dimensional Array


Two-dimensional arrays, just like single-dimension arrays, can
be initialized using two different methods.
Method 1: i is the index of the internal array (row) and j is the
index of the element within that array (column) that is being
initialized.
public class TwoDTester{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int[][] nums = new int[3][2];

for(int i = 0; i < nums.length; i++){


for(int j = 0; j < nums[i].length; j++){
System.out.println("Enter a value for row " + i + ", column " + j);
nums[i][j] = in.nextInt();
}
}

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

40

Initializing a Two-Dimensional Array


Method 2: Declares and initializes all arrays and all elements
within those arrays in the same line of code.
However, you must know the values that you want the array
to contain to initialize the array at the same time that it is
declared.
public class TwoDTester2{
public static void main(String[] args){
int[][] nums = {{2,3,7},{15, 98, 2}};
}
}

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

41

Initializing a Two-Dimensional Array


Example
Method 1:
int[][] myArray
MyArray[0][0] =
MyArray[0][1] =
MyArray[1][0] =
MyArray[1][1] =
MyArray[2][0] =
MyArray[2][1] =

= new int[3][2];
7;
24;
352;
2;
37;
65;

Index of internal array

Index of element within the internal array

Method 2:
int[][] myArray = new int[][] {{7, 24}, {352, 2}, {37, 65}};

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

42

Using Second Notation to Initialize the


Array
Since we already know the content of the arrays for our
bouquet, use the second notation to initialize the array.
Recall that the order is "Rose", "Sunflower", "Daisy",
"Dandelion", "Violet", then "Lily".
These flowers will represented by the indexes 0, 1, 2, 3, 4,
and 5.
String[][] myBouquet = {{"Red", "Peach", "Yellow"},
{"Yellow", "White", "Blue"},
{"Green", "Blue", "Purple"},
{"White", "White", "White"},
{"Purple", "Pink", "Violet"},
{"Pink", "Orange", "White"}};

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

43

Two-Dimensional Array Representation


The two-dimensional array is represented as follows.
Index

0 (Rose)

Red

Peach

Yellow

1 (Sunflower)

Yellow

White

Blue

2 (Daisy)

Green

Blue

Purple

3 (Dandelion)

White

White

White

4 (Violet)

Purple

Pink

Violet

5 (Lily)

Pink

Orange

White

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

44

Visualizing a Two-Dimensional Array


Lining up the values during initialization helps to keep track of
how data is organized in a two-dimensional array.
In the code examples below, notice how the second form is
easier to visualize.
String[][] myBouquet = {{"Red", "Peach", "Yellow"}, {"Yellow", "White",
"Blue"}, {"Green", "Blue", "Purple"}, {"White", "White", "White"}, {"Purple",
"Pink", "Violet"}, {"Pink", "Orange", "White"}};

String[][] myBouquet = {{"Red", "Peach", "Yellow"},


{"Yellow", "White", "Blue"},
{"Green", "Blue", "Purple"},
{"White", "White", "White"},
{"Purple", "Pink", "Violet"},
{"Pink", "Orange", "White"}};

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

45

Accessing Data in a Two-Dimensional Array


To access data in a two-dimensional array, you must know:
The index of the array to access.
The index of the content in that array to access.

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

46

Accessing Data in a Two-Dimensional Array


Example
For example, to access the color of the Rose in myBouquet,
use the index of the Rose array (0) and the index of the first
color (0).
//Previously initialized array
String[][] myBouquet = String[][] {{"Red", "Peach", "Yellow"},
{"Yellow", "White", "Blue"},
{"Green", "Blue", "Purple"},
{"White", "White", "White"},
{"Purple", "Pink", "Violet"},
{"Pink", "Orange", "White"}};
String rose1 = myBouquet[0][0]; //accesses first element of first array

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

47

Accessing Data in a Two-Dimensional Array


Example
Review the previous array initialization.
//Previously initialized array
String[][] myBouquet = String[][] {{"Red", "Peach", "Yellow"},
{"Yellow", "White", "Blue"},
{"Green", "Blue", "Purple"},
{"White", "White", "White"},
{"Purple", "Pink", "Violet"},
{"Pink", "Orange", "White"}};

What will display in the console screen after the following


code is executed?
System.out.println(myBouquet[0][1] + " Rose.";
System.out.println(myBouquet[5][2] + " Lilly.";

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

48

Accessing Data in a Two-Dimensional Array


Example Solution
What will display in the console screen after the following
code is executed?
System.out.println(myBouquet[0][1] + " Rose.";
System.out.println(myBouquet[5][2] + " Lilly.";

Solution:
Peach Rose
White Lilly

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

49

Accessing the Length of Two-Dimensional


Arrays
Length is an instance variable defined by the size of each
declared array.
Two-dimensional arrays have two different lengths:
Length of the outer array.
Length of the internal arrays.

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

50

Length of Outer and Inner Arrays


The length of the outer array, which is the length that
describes the number of arrays contained (rows), is accessed
like a typical array.
int numArrays = arrayName.length;

The length of the internal arrays, which is the length that


describes the number of elements each array contains
(columns), is accessed using the following notation.
Brackets [ ] tell the program that it is accessing the length of
the internal arrays, and row says which array.
int numElementsInEach = arrayName[row].length;

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

51

Length of Outer and Inner Arrays Example


Review this code.
String[] one = new String[7];
int[][] two = new int[5][3];
double[][] three = new double[3][2];
People[] four = new People[5];

Which of the following is not true? Can you identify which


one has improper syntax for accessing the length?
one.length == 7;
two.length == 3;
three.length == 3;
two[0].length == 3;
three[0].length == 2;
four[0].length == 5;

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

52

Length of Outer and Inner Arrays Example


Solution
Solution:

two.length == 3;

is FALSE

four[0].length == 5;

is not valid syntax

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

53

Two-Dimensional Arrays Object Types


Just like single-dimensional arrays, two-dimensional arrays
can store any type of object.

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

54

Two-Dimensional Arrays Object Types


How can we organize the students in a classroom into three
groups, with five students per group as an array?
Answer: Declare a two-dimensional array that holds three
arrays, one for each group. Each array stores five students.
A class called Student has been defined, which has a
constructor that takes in the student's first name.
The following code declares the array that stores the group of
students.
Student[][] groups = new Student[3][5];

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

55

Placing Students in the Two-Dimensional


Array
Given a String array containing names of the 15 students in
the groups, how could you perform the following tasks?
Iterate through the existing array.
Create a new student for each provided name.
Place each student into one of the three groups.

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

56

Placing Students in the Two-Dimensional


Array
You already know how to:
Iterate through the array using a for loop.
Create a new student for each name inside loop.
Place the students in the two-dimensional array using a nested for
loop.

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

57

Nested for Loops


A nested for loop:
Is a for loop inside a for loop.
Is can be used to iterate through two-dimensional arrays using the
outer for loop counter as the index for the arrays (rows) and the inner
for loop counter as the index for the elements of each array (columns).

Consider the following two-dimensional array declaration:


Student[][] groups = new Student[3][5];

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

58

Nested for Loops


To iterate through the array and initialize each student as
"Temp", use nested for loops as shown below.
for(int i = 0; i < groups.length; i++){
for(int j = 0; j < groups[i].length; j++){
groups[i][j] = new Student("Temp");
}
}

JF 6-1
Arrays

//i keeps track of the rows


//j keeps track of the columns

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

59

Complete Tasks Using Nested for Loops


How could we complete all three tasks?
Iterate through the existing array.
Create a new student for each provided name.
Place each student into one of the three groups.

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

60

Complete Tasks Using Nested for Loops


String[] studentNames;
//Assume studentNames is initialized with 15 names
Student[][] groups = new Student[3][5];//Declare your array
int x = 0;
for(int i = 0; i < groups.length; i++){
for(int j = 0; j < groups[i].length; j++){
String name = studentNames[x];
groups[i][j] = new Student(name);
x++;
}
}

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

61

Command Line Arguments


An array has always been a part of the main method.
The String array args is always a parameter for the main
method.
public static void main(String[] args)

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

62

Command Line Arguments:


Adding Extra Arguments
If you run a Java program from a command line environment,
you can type in extra arguments as follows:
java Test apples peaches pumpkin pie

The keyword java tells the command line environment to use


the JVM to run the program Test.
The array args gets populated with the Strings: apples,
peaches, pumpkin, and pie.
Using Eclipse, we avoid the command line environment.
However, we can use command line arguments in Eclipse.

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

63

Using Command Line Arguments in Eclipse


Access the arguments tab for your program by going to the
Run menu and choosing Open Run Dialog. Click the
Arguments tab and type in the Strings: Apples Peaches
Pumpkin Pie.

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

64

Using Command Line Arguments in Eclipse


Click Run for the program.
All of the Strings that were typed in the Arguments tab will
print to the console.
public class TestArgs {
public static void main(String[] args){
for(int i=0;i<args.length;i++){
System.out.println(args[i]);
}
}
}

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

65

Terminology
Key terms used in this lesson included:
Algorithm
Array
Array of arrays
Command-line argument
Index
Iterate

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

66

Terminology
Key terms used in this lesson included:
Nested for loop
Single-dimensional array
Traverse
Two-dimensional array

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

67

Summary
In this lesson, you should have learned how to:
Write a single-dimensional array in a Java program using
primitive data types
Write a single-dimensional array in a Java program using
reference (Object) types
Write a 2-dimensional array in a Java program using primitive
data types
Write a 2-dimensional array in a Java program using reference
(Object) types
Declare an array, initialize an array, and traverse the array
JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

68

Summary
In this lesson, you should have learned how to:
Describe array initialization
Distinguish between the String method length() and an
array's length value
Rewrite a Java program to store integers into an array,
perform a mathematical calculation, and display the result
Use alternative array declaration syntax

JF 6-1
Arrays

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

69

Java Fundamentals

6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Describe the different kinds of errors that can occur and how
they are handled in Java
Describe what exceptions are used for in Java
Determine what exceptions are thrown for any foundation
class
Write code to handle an exception thrown by the method of a
foundation class

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Types of Errors
An error indicates that a there is a problem with interpreting
your program.
There are three types of errors:
Syntax errors
Logic errors
Exceptions (run-time errors)

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Syntax Errors
An error can occur when a file is compiled. These errors are
coding or syntax errors, such as:
Missing semicolons
Spelling errors
Assigning a value to a variable that is not the correct type

It is common to go through several rounds of fixing syntax


errors before compiling the file is successful.

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Syntax Errors: Missing Semicolons and


Incorrect Symbols
Forgetting a semicolon at the end of a Java statement is a
syntax error.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert ";" to complete Statement
at ErrorIndicators.main(ErrorIndicators.java:8)

Using = instead of == to compare values in an if condition is a


syntax error.
if(x=y){

Incorrect

if(x==y){

Correct

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Syntax Errors: Misspelling Methods or


Variables
Misspelling a variable or method name is a syntax error.
Be sure to verify that you have spelled the variable or method
the same as you declared it.
To fix this error, check the spelling of:
The variable or method where it is declared.
Where you call the variable or method.
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
variableName cannot be resolved to a variable
at MisspellingVariables.main(MisspellingVariables.java:7)

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Logic Errors
Logic errors occur as a result of programmer logic that is
incorrect.
These errors do not produce a compile or runtime error.
For example, a loop runs too many times, or the program
produces incorrect output.

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Logic Errors
Placing a semicolon after an if condition or initializing a loop:
Interpreters read the semicolon as the end of the loop, which means
that everything after the semicolon will be treated as outside of the
loop.
for(int i = 0; i < 5; i++);
System.out.println(i);

JF 6-2
Handling Errors

This statement
will only execute
once. Why?

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Logic Error Examples


Using == to compare Strings or objects is a logic error unless
you are checking to see if they refer to the same object.
String s1 = "Hello";
String s2 = "Goodbye";
if(s1==s2)
System.out.println("They are equal");

The == will check to see if these Strings


are the same object. To check if the
contents of the Strings are equal, use
the equals() method from the String
class.

Because of the extra semicolon, "Hello" will always display,


even if x is less than 10.
if(x > 10);
System.out.println("Hello");

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Exceptions
Once a file compiles successfully, an error can occur when a
file is tested during runtime.
These runtime errors are called exceptions and should be
handled by the programmer using code in the program,
otherwise known as "throwing" the exception.

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Categories of Java Exceptions


Java exceptions fall into two categories:
Unchecked exceptions (errors in code).
Checked exceptions (errors that occur from outside the code), most of
which originate in programs with Input/Output (IO).

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Creating a Try/Catch Block


A try/catch block can handle checked and unchecked
exceptions. Below is an example of a try/catch block.
try{
}

...code that might cause an exception

catch (exception e){


...code to handle the exception
}

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Unchecked Exceptions
It is optional to handle unchecked exceptions in Java.
However, if the unchecked exception is not handled, and an
error occurs, the program will crash.
Common unchecked exceptions:
Index out of bounds exception
Null pointer exception

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Index Out of Bounds Exception


Call example[3] in the following initialized array.
int[] example = {1, 2, 3};

The following exception message would display, because


example[3] does not exist in the array.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at NullPointerTest.main(NullPointerTest.java:6)

The array starts at index 0 and ends at index 2. Calling index 3


means you are out of the bounds of the array.
example[0] = 1;
example[1] = 2;
example[2] = 3;

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Null Pointer Exception


The following code will throw a null pointer exception,
because the String objects in the array have not been
initialized.
String[] s1 = new String[5];
System.out.println(s1[0]);

To correct the problem, assign String values to the 5 Strings in


the array before trying to print out the values.

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

File Not Found Exception


A File Not Found exception is an I/O (Input/Output)
exception.
I/O exceptions are checked exceptions.
Most checked exceptions come from using I/O classes.

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Handling Checked Exceptions


Checked exceptions must be handled.
There are two ways to handle a checked exception:
Use a try/catch block, which will handle the exception "gracefully."
Use a "throws" statement in the method declaration, which is a risk.
A throws statement is when a programmer says that he/she will take
a chance that an exception will not be thrown.

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

I/O Exception
This code uses a try/catch block to handle an I/O exception.
try{
FileReader reader = new FileReader("test.txt");
}
catch(IOException e){
System.out.println("File not found");
}

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

File Not Found Exception


Use a "throws" statement to handle an I/O Exception.
The "throws" statement is used to warn that there may be an
exception thrown, however, the program will still crash if an
error occurs that throws an exception.
public static void main(String[] args) throws IOException{
}

FileReader reader = new FileReader("test.txt");

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Throwing Exceptions
So far you have seen exceptions handled by using a try/catch
block.
You can also handle exceptions by throwing them.
If you throw an exception, your interpreter will stop running
the program at that point, which indicates to the user that
they have reached the exception.
In code, an exception is thrown as follows:
throw new Exception("Array index" + i + " is out of bounds!");

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Catching Exceptions
To catch an exception means to handle it.
You may throw an exception for certain cases, such as going
out of bounds of an array, and catch the exception to
continue the program the way you wrote it to handle the
exception.
A try/catch block enables you to do this.

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Try/Catch Example
This is an example of handling an Index Out Of Bounds
exception with a try/catch block.
try{

//i is the index of an array with length 10


if(i > 9 || i < 0)
throw new Exception("Index " + i + " is out of bounds!");

}
catch(Exception e){
//This code will run only if the exception was thrown
if(i > 9)
i-=9;
else
i+=9;
}

//You may have additional code here that will run only if the exception was not thrown

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Throwing and Catching Exceptions Scenario


You are writing a program that moves a turtle to a part of the
ocean that the user specifies.
How would your program run if the user entered coordinates
that were not on the map of the ocean where the turtle can
move?
This exception would be out of the programmer's control.
Think about the throwing and catching an exception to solve
this problem.

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Terminology
Key terms used in this lesson included:
Catch
Checked exceptions
Error
Exception
Logic error

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Terminology
Key terms used in this lesson included:
Runtime error
Syntax error
Throw
Try/catch block
Unchecked exceptions

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Summary
In this lesson, you should have learned how to:
Describe the different kinds of errors that can occur and how
they are handled in Java
Describe what exceptions are used for in Java
Determine what exceptions are thrown for any foundation
class
Write code to handle an exception thrown by the method of a
foundation class

JF 6-2
Handling Errors

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Java Fundamentals

7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Recognize the correct general form of a class
Create an object of a class
Create methods that compile with no errors
Return a value from a method
Use parameters in a method
Create a driver class and add instances of Object classes

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Add a constructor to a class
Apply the new operator
Describe garbage collection and finalizers
Apply the this reference
Add a constructor to initialize a value

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Creating a Class Template


Programmers can create their own classes.
Classes are essentially a template or blueprint for all
instances of the class.
The class code also communicates to the compiler how to
define, create, and interact with objects of the class.
The code on the following slide starts to create the Class
Vehicle which will represent the basic outline for Vehicle
objects.

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Creating a Class Template Example


public class Vehicle {
// the Vehicle class has two fields
private String make;
private int milesPerGallon;

//constructor
public Vehicle(){
}
//mutator/setter method
public void setMake(String m){
make = m;
}
//mutator/setter method
public void setMilesPerGallon(int mpg){
milesPerGallon = mpg;
}
//accessor/getter method
public String getMake(){
return make;
}
//accessor/getter method
public int getMilesPerGallon(){
return milesPerGallon;
}

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Creating an Instance of a Class


Once you have created a class, you can create instances of
the class (objects) in a Driver Class or inside other Object
Classes.
Instances:

Inherit all attributes and methods defined in the class template.


Interact independently of one another.
Are reference objects.
Are created using the new operator.

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Instantiate an Instance
To instantiate an instance of a Vehicle called myCar, write:
public class VehicleTester{
public static void main(String[] args){
Vehicle myCar = new Vehicle();
}
}

In Java, instantiation is the creation of objects from a class.

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Constructors
Constructors are methods that
allow the user to create instances of
(instantiate) a class.
Good programming practice
dictates that classes should have a
default constructor.
Constructors which contain
parameters typically initialize the
private variables of the class to
values passed in by the user.
Constructors do not have a return
type (void or other).
JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Default Constructor
Good programming practice dictates that classes should have
a default constructor.
A default constructor:
Takes no parameters.
Typically initializes all private variables to base values.
public Vehicle() {
make = "";
milesPerGallon = 0;
}

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Constructor with Parameters


A constructor with parameters is used when you want to
initialize the private variables to values other than the default
values.
public Vehicle(String m, int mpg){
make=m;
milesPerGallon=mpg;
}

Parameters

Parameters are variables that are listed as part of a method (or


constructor) declaration. In the example above, String m and int mpg
are parameters. Values are given to the parameters when a call to the
method or constructor is made.

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Instantiate Vehicle Instance


To instantiate a Vehicle instance using the constructor with
parameters, use arguments:
Arguments
Vehicle myCar = new Vehicle("Toyota", 30);

To instantiate a Vehicle instance using the default constructor,


write:
Vehicle myCar = new Vehicle();

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Defining Methods
A method is a block of code which is referred to by name and
can be called at any point in a program simply by utilizing the
method's name. There are four main parts to defining your
own method:

Access Modifier (public, private, protected, default)


Return type
Method name
Parameter(s)

public returnType methodName(Parameter p, )


{
/*code that will execute with each call to the
method goes here*/
}

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Components of a Method
Method components include:
Return type:
This identifies what type of object, if any, will be returned when the method
is invoked (called).
If nothing will be returned, the return type is declared as void.

Method name:
Used to make a call to the method.

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Components of a Method
Parameter(s):
The programmer may choose to include parameters depending on the
purpose and function of the method.
Parameters can be of any primitive or type of object, but the
parameter type used when calling the method must match the
parameter type specified in the method definition.

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Method Components Example

Return type

Name of method

Parameters

public String getName(String firstName, String lastName)


{
return( firstName + " " + lastName );
}

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Class Methods
Every class will have a set of methods associated with it which
allow functionality for the class.
Accessor method
"getter"
Returns the value of a specific private variable.

Mutator method
"setter"
Changes or sets the value of a specific private variable.

Functional method
Returns or performs some sort of functionality for the class.
JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Accessor Methods
Accessor methods access and return the value of a specific
private variable of the class.
Non-void return type corresponds to the data type of the
variable you are accessing.
Include a return statement.
Usually have no parameters.
public String getMake(){
return make;
}
public int getMilesPerGallon(){
return milesPerGallon;
}
JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Mutator Methods
Mutator methods set or modify the value of a specified
private variable of the class.
Void return type.
Parameter with a type that corresponds to the type of the
variable being set.
public void setMake(String m){
make = m;
}
public void setMilesPerGallon(int mpg){
milesPerGallon = mpg;
}

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Functional Methods
Functional methods perform a functionality for the class.
Void or non-void return type.
Parameters are optional and used depending on what is
needed for the method's function.

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Functional Methods
Below is a functional method for the class Vehicle that
compares two vehicles and returns an int value for the
comparison.
//Compares the miles per gallon of each vehicle passed in, returns 0 if
they are the same, 1 if the first vehicle is larger than the second and -1
if the second vehicle is larger than the first*/
public int compareTo(Vehicle v1, Vehicle v2){
if(v1.getMilesPerGallon()= = v2.getMilesPerGallon())
return 0;
if(v1.getMilesPerGallon()> v2.getMilesPerGallon())
return 1;
return -1;
}

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Using Constructors and Methods in a


Driver class main method Example
For the following:
What functionality does each line have?
What will the final print statement print to the screen?
public class VehicleTester{
public static void main(String[] args){
Vehicle v;
v=new Vehicle();
v.setMake("Ford");
v.setMilesPerGallon(35);

System.out.print("My "+v.getMake() +
" gets " + v.getMilesPerGallon() + " mpg.");

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

this Reference
Within an instance method or a constructor, this is a
reference to the current object.
The reference to the object whose method or constructor is
being called.
Refer to any member of the current object by using this.
Most commonly used when a field is shadowed by a method
or constructor parameter of the same name.

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

this Reference Example


When a method argument "shadows" a field of the object,
the this reference is used to differentiate the local scope from
the class scope.
public class Point {
private int x;
Private int y;

//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Card Class Example


Consider a standard deck of playing cards.
To represent each card as an instance of a Card class, what
attributes would the class need to have?
Suit
Name
Points
public class Card {
private String suit;
private String name;
private int points;
}

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Reference Object Representation


When creating a new instance of an object, a reference is
made to the object in memory.
The reference points to the object.
All attribute variables are created and initialized based on the
constructor used.
Card c = new Card();

suit = null
name= null
points = 0

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Understanding Garbage Collection Example


Considering the code below, what will happen in memory
after the line c2 = c; ?
When executed, c2 = c; takes the reference c2 and makes it
reference the same object as c.
This effectively renders the original object c2 useless, and
garbage collection takes care of it by removing it from
memory.
Card c=new Card("Diamonds","Four", 4);
Card c2=new Card("Spades","Ace", 1);
c2 = c;

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Finalizers
A finalizer is code called by the garbage collector when it
determines no more references to the object exist.
All objects inherit a finalize() method from java.lang.Object.
This method takes no parameters and is written to perform
no action when called.

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Finalizers
Overriding the finalize() method in classes allows you to
modify what happens before garbage collection, such as:
Notifying the user about the garbage collection that is about to occur.
Cleaning up non-Java resources, such as closing a file.

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Finalize Method Example


This is an example of the finalize() method overridden in a
class. It closes all associated files and notifies the user that
the finalization occurs.
protected void finalize(){
try{
close(); //close all files
}
finally{
System.out.println("Finalization has occured");
}
}

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Terminology
Key terms used in this lesson included:
Accessor method
Class
Constructor
Finalizers
Garbage collection
Initialization
Instantiate
Method
JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Terminology
Key terms used in this lesson included:
Mutator method
new
Null
Object
Reference
this Reference

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Summary
In this lesson, you should have learned how to:
Recognize the correct general form of a class
Create an object of a class
Create methods that compile with no errors
Return a value from a method
Use parameters in a method
Create a driver class and add instances of Object classes

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Summary
In this lesson, you should have learned how to:
Add a constructor to a class
Apply the new operator
Describe garbage collection and finalizers
Apply the this reference
Add a constructor to initialize a value

JF 7-1
Classes, Objects, and Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Java Fundamentals

7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Use access modifiers
Pass objects to methods
Return objects from methods
Use variable argument methods
Overload constructors
Overload methods
Write a class with specified arrays, constructors, and methods

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Access Modifiers
Access modifiers specify accessibility to changing variables,
methods, and classes.
There are four access modifiers in Java:
Access Modifier

Description

public

Allows access from anywhere.

protected

Allows access only from inside the same class,


from a subclass, or from other classes of the
same package as the modifier.

private

Allows access only from inside the same class as


the modifier.

"default" (not specified/blank)

Allows access from only inside the same class, or


from other classes of the same package as the
modifier.

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

public Access Modifier


public access modifiers allow access from anywhere.
In Java, adding the keyword public as the variable, method, or
class is declared, makes the variable, method, or class
accessible from anywhere.

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Declaring as public
The code below shows how to declare a variable, method, or
class as public.
Variable:
public int milesRan = 2;//public access
int timePassed = 17;//access not specified

Method:
public int addMiles(int a, int b)
{
return a+b;
}

Class:
public class Jogging{
//class code here
}

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

protected and "default" Access Modifiers


A protected access modifier allows access from inside the
same package.
To declare a variable, method, or class as protected, write the
keyword protected rather than public.
A "default" access modifier allows access inside the class,
subclass, or other classes of the same package as the
modifier.
To declare a variable, method, or class as "default," you must
not include an access modifier.

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

private Access Modifier


A private access modifier:
Only allows access from inside the same class.
Is the most restrictive access modifier.
Is the opposite of the public access modifier.
private int bankAccountNumber;

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

When to Use public or private

Type
public

private

Definition

When to Use

Allows access from


anywhere.

When it does not matter that


anyone can access your code or
when you wish to share your
code with others.

Allows access only from


inside the same class.

When it is important that your


code is secure and cannot be
accessed from anywhere but
inside the class itself.

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objects as Parameters
A parameter is a variable in a method declaration that is
passed to the method.
public int method(int parameter1, int parameter2)

Parameter types are the type of parameters that can be


passed to a method. This includes:
Primitive types (such as int, double, char)
Objects
String
Array
public int method(int anInt, double aDouble, String aString, MyClassName anObjectOfMyClass)

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Objects as Parameters Example


An employer has an opening for a promotion for one of his
employees.
He wishes to create a method that will take in an employee as
a parameter and calculate and return the employee's rating
based on their qualifications for the new position.
public int promotion(Employee E){
int timeEmployed = E.getLengthOfEmployment();
//do some calculations to set a rating for E
return rating;
}

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Passing Objects as Parameters


Passing objects as parameters allows for much easier access
to the information that the object contains.
It also permits making changes to objects inside of the
method, and even allows for comparing two objects that
cannot use primitive comparing methods.

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Returning Objects
Writing a method that returns an object is very similar to
writing a method that returns a primitive type.
For example, the employer from the previous example just
learned that methods can return an object.
To make it easier to find the employee to promote, he can
write a method that takes in two employees.
The method returns the one that has a better rating.
This is easier than going through each employee, retrieving
each of their ratings, and then comparing them.

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Returning Objects Example


Employee identifies what is being returned.
To return an object, simply
write the object type here.

public Employee promotion(Employee A, Employee B){


//calculate to compare which employee is better
//if employee A is better
return A;
//if employee B is better
return B;
}

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Variable Argument Methods


A variable argument method:
Is a method written to handle a variable number of arguments.
Only works if you call the method with the same type of argument as
the method requires.

A variable argument method looks like this:


public int total(int ... nums){
int sum = 0;
for(int i = 0; i < nums.length; i++)
sum += nums[i];
return sum;
}

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Variable Argument Methods Example


For example, a method initialized with a variable argument of
integers cannot be called with any number of Strings, but can
only be called with any number of integers for the argument.
If another method is declared with a variable argument of
Strings, they must call that method with String(s) to meet the
arguments.

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Why not use Arrays in Variable Argument


Methods?
Why not just use an array?
In a program, you must know the number of elements in an
array to create one. If the number of elements changes, you
would need a different array for each different length.
Using a variable argument method allows for use of the
method without ever having to initialize an array.
It also allows for multiple uses with a variable number of
elements.

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Variable Argument Methods and Integers


Does a variable argument method only work with integers?
No, the variable argument works with any primitive type,
object, and even arrays.
You can have a variable argument of arrays.

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Employee Example
To determine employee promotions, the employer was
coding a method that compared two employees and returned
the best one.
Now that the employer has the method to compare the
employees, he needs a way to compare all the employees at
once instead of only comparing two at a time.
This is where variable arguments would help.

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Variable Argument Employee Example


Code
Code to compare all employees:
public Employee promotion(Employee ... employees){
Employee bestCandidate = employees[0];
//go through the list of employees and calculate
//which one is the best candidate

for(int i = 1; i < employees.length; i++){


//if there is a candidate better than the current best
if(employees[i].getRating > bestCandidate.getRating){
//update the bestCandidate to the better one
bestCandidate = employees[i];
}
}
//return the best candidate found for the promotion
return bestCandidate;

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Calling a Method with Variable Arguments


Calling a method with variable arguments is like calling any
other method.
However, it can be called with a different number of
arguments each time it is called.

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Calling a Method with Variable Arguments


The code below demonstrates this idea. Sam, Erica, Dominic,
Sandy, and Jake are employees.
The employer is looking to promote either Sam, Erica, or
Dominic to manager and Sandy or Jake to assistant manager.
//This compares Sam, Erica, and Dominic and assigns
//the best candidate of the 3 to newManager.
Employee newManager = promotion(sam, erica, dominic);
//This compares Sandy and Jake and assigns the better
//of the 2 to newAssistantManager
Employee newAssistantManager = promotion(sandy, jake);

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Overloading Constructors
Constructors assign initial
values to instance variables of
a class.
Constructors inside a class are
declared like methods.
Overloading a constructor
means having more than one
constructor with the same
name but different types
and/or numbers of arguments.

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Overloading Constructors Example 1


This example overloads the public constructor of a Dog class.
public class Dog{
public Dog(){...implementation...}
public Dog(int weight){...implementation...}
public Dog(String barkNoise){...implementation...}
public Dog(int weight, int loudness, String barkNoise){...implementation...}
}

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

How Overloading Constructors Works


Overloading constructors works as follows:
Java reads the constructor based on what arguments are passed into it.
Once it identifies the constructor name, it will compare the argument
types.
If the argument types do not match the first constructor of that name,
it will proceed to the second, third, and so on until it identifies a
constructor name and argument type match.
If it does not find a match, then the program will not compile.

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Overloading Constructors Example 2


public class Dog{
private int weight;
private int loudness;
private String barkNoise;

public Dog(){
weight = 12;
loudness = 4;
barkNoise = "Woof";
}
public Dog(int w, int l){
weight = w;
loudness = l;
barkNoise = "ARF!";
public Dog(int w, int l, String bark){
weight = w;
loudness = l;
barkNoise = bark;
}

JF 7-2
Parameters and Overloading Methods

This is a constructor that specifies


the dog's weight and
loudness in the arguments.

This is a constructor that specifies


the dog's weight, loudness, and bark
noise in the arguments.

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Overloading Constructors Example 2


Explained
Dog() is the default constructor.
A default constructor has no arguments.
If you initialized a Dog object using this constructor, it would
have a weight of 12, a loudness of 4, and a bark noise of
"woof".
The last two constructors in the Dog class allow the
assignment of instance variables to differ according to
specifications during initialization.

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Overloading Constructors Example 2


Explained
Although the default Dog constructor has code to initialize
the class variables, it is optional for a default constructor to
have code.
If the default constructor does not have code, the class
variables are initialized with:
null for objects
0 (zero) for primitive numeric types
false for boolean

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Overloading Constructors Example 2


Explained
If a constructor is not written for a class, the default
constructor (with no code) is supplied by the JVM.
If there is not a default constructor written, and there are
one or more other constructors, the JVM will not supply a
default constructor.

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Overloading Methods
Like overloading constructors, overloading a method occurs
when the type and/or number of parameters differ. Below is
an example of a situation where a method would need to be
overloaded. Create the Dog class, then create an instance of
Dog in a Driver Class. Call (use) both bark() methods.
public class Dog{
private int weight;
private int loudness;
private String barkNoise;
public void bark(String b){
System.out.println(b);

public void bark(){


System.out.println("Woof");
}

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Terminology
Key terms used in this lesson included:
Access modifier
Constructor
Default constructor
Overloading
Private access modifier
Public access modifier
Variable argument method

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Summary
In this lesson, you should have learned how to:
Use access modifiers
Pass objects to methods
Return objects from methods
Use variable argument methods
Overload constructors
Overload methods
Write a class with specified arrays, constructors, and methods

JF 7-2
Parameters and Overloading Methods

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Java Fundamentals

7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Create static variables
Use static variables
Create static methods
Use static methods
Create static classes
Use static classes

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Static Modifier
Using instance variables, each instance of a class created with
the keyword new creates a copy of all instance variables in
that class.
For example, in the Employee class below, a unique copy of
lastname and firstname is created for each new Employee
object that is created in a Driver Class.
public class Employee{
private String lastname;
private String firstname;
...more code
}
//create two Employees in a main method:
Employee e1 = new Employee("Smith", "Mary");
Employee e2 = new Employee("Jones", "Sally");

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Static Keyword
Static is a keyword in Java that modifies the association of an
item to a class.
Contents of a class that are identified as static are shared
across all instances of the class.
This means all instances of the class share one copy of the
static items, and each have their own unique copies of
instance items, or non-static items.

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Static Example
Consider initializing a static String with the value "Oracle"
called myCompany that represents the employer's company.
Each instance of Employee would still have their unique
instance variables, but would share the static variable.
e2

e1

Instance Variable

Static Variable

Instance Variable

Mary Smith

Oracle

Sally Jones

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Static Variables
Static variables
Are also known as class variables.
Are declared with the static keyword.
Have only one copy in memory, as opposed to instance
variables, which hold one copy per instance.
Are shared by object instances.
Hold the same value for all class instances.

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Static Variables
Public access for static variables:
If public, they can be modified directly by other classes.
Consider making the variable a constant by using the keyword final to
prevent modifications.
Example:
public static final int MODEL_NUM = 883;

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Programming Practices and Static Variables


Good programming practice initializes static variables with
values, rather than relying on the default null and 0 values.
The values initially assigned can be changed as long as the
class is active in JVM memory.
Garbage collection removes it from memory and the initial
values assigned will return the next time you use it.

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Declaring a Static Variable


To declare a static variable, include the keyword static as
shown below.
Can be public, protected, default, or private.
Should have assigned values, but automatically are assigned
null values for class instances: an empty string or 0 for
primitive numbers.
Should act as constants with the final keyword when they use
a public, protected, or default access.
public class Nesting {
// Declare public static variable.
public static final int MODEL_NUM = 883;
...
}

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Changes to a Static Variable


Static variables that are not final can be read or assigned new
values by using the optional keyword this in instance
methods.
Changes by instance methods are changed for all instances.
A change to a static variable may indicate that the class
should be limited to only one object.
This is known as the Singleton pattern.
...
private static String myCompany = "Oracle";
public void setMyCompany(String s) {
this.mycompany = s;
}
...
JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Static Variable Example


Create a class called Turtle that contains a variable named
food. This variable is static since all of our turtles eat the
same food.
The Turtle class will have one more variable named age.
Since each turtle is a different age, it is best to make this
variable a private instance variable rather than a static one.
public class Turtle {
public static String food = "Turtle Food";
private int age;

public Turtle(int age){


this.age = age;
}

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Accessing Static Variables


Instance variables require an instance of the class to exist
before access is possible.
public class Turtle {
public static String food = "Turtle Feed";
private int age;
...
}

You can access static variables without creating an instance of


the class.
In a main method, this statement would print out the variable
food without any instance reference.
System.out.println("I feed " + Turtle.food + " to all of my turtles!");

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Notation to Access Static Variables


Generally, static variables are accessed by the notation:
ClassName.variableName;

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Static Modifier and Methods


Static or class methods exist once and are shared by all class
instances.
May be used by other class methods or instance methods
based on their access modifier.
Cannot access non-static, or instance, variables. Static
methods can only access static variables.
Cannot access non-static, or instance, methods. Static
methods can only access other static methods.
Can be redefined in subclasses.
Can be public, protected, default, or private.
JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Static Modifier and Methods


There are differences between calling an instance method
versus a class (static) method.
For example, you must first create an instance and then use a
dot notation to call an instance method; whereas, the class
name, a dot notation, and static method name calls a static
method.

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Static Modifier and Methods


The static method provides a wrapper to construct an
instance of a class.
When the class has a private access constructor, a static
method is one of two approaches to creating an instance of
the class.

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Turtle Class Example


The Turtle class has a static variable that identifies the
number of tanks we have available (numTanks) and an
instance variable (tankNum) that tells us which tank the
Turtle is in.
public class Turtle {
public static String food = "Turtle Feed";
tankNum variable
public int age;
public int tankNum;
public static int numTanks = 3;
numTanks variable
public Turtle(int age){
this.age = age;
tankNum = (int)((Math.random()*numTanks)+1);
}
public void swim(){//implementation}
public int getAge(){return age;}
public int getTankOfResidence(){return tankNum;}
public static String fishTank() {return "I have " + numTanks + " fish tanks.";
}
}

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Static Methods in Turtle Class Example


Review the methods in the Turtle class.
public class Turtle {
public static String food = "Turtle Feed";
public int age;
swim() is a instance method.
public int tankNum;
public static int numTanks = 3;
Although each turtle can swim,
public Turtle(int age){
the turtles may swim
this.age = age;
differently depending on their
tankNum = (int)((Math.random()*numTanks)+1);
}
age.
public void swim(){//implementation}
public int getAge(){return age;}
public int getTankOfResidence(){return tankNum;}
public static String fishTank() {return "I have " + numTanks + " fish tanks.";
}
getAge() and
}

fishTank() is a static method and it


accesses a static variable
(numTanks).
JF 7-3
The Static Modifier and Nested Classes

getTankOfResidence() are
instance, non-static, methods
because they access non-static
variables. Static methods cannot
access non-static items.

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Creating Class Instances Using Static


Methods
Another use of static methods is for creating class instances
when the class constructor access is private, and the method
is part of the same class.
This is possible because the static method is publicly
accessible with private access to the class.
...
private Nesting() {implementation}
...
public static Nesting getInstance() {
Nesting nesting = new Nesting();
return nesting; }
...
// Instantiate a private class with a method.
Nesting n1 = Nesting.getInstance();
...
JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Static Modifier and Classes


Static or nested classes:
Can exist as nested classes.
Cannot exist as independent classes.
A nested class is a class that is created inside
another a class.

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Static Nested Classes


Static classes are implemented inside other classes, and the
other classes are known as container classes.
Can extend the behavior of the container class.
Can be overloaded like ordinary constructors.
The super() method call calls the parent class in a class
hierarchy.
The static nested class can extend the behavior of the
containing class.

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Static Nested Classes


The static nested class also provides the means for
instantiating a containing class when it's constructor is
configured with private access.
This is the second way to instantiate a class that has a
restricted or private access qualifier for its class constructors.

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Static Nested Classes Example

public class Space {


//Space class variables
public static class Planet{
//planet class variables and constructors
public Planet() {...implementation...}
public Planet(String name, int size)
{...implementation...}
}
}

//more space class implementation

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Terminology
Key terms used in this lesson included:
Class method
Class variable
Inner class
Nested class
Static modifier
Static method
Static nested class
Static variable
JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Summary
In this lesson, you should have learned how to:
Create static variables
Use static variables
Create static methods
Use static methods
Create static classes
Use static classes

JF 7-3
The Static Modifier and Nested Classes

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Java Fundamentals

7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Demonstrate and explain UML (Unified Modeling Language)
class diagrams
Use the extends keyword to inherit a class
Compare and contrast superclasses and subclasses
Describe how inheritance affects member access
Use super to call a superclass constructor
Use super to access superclass members
Create a multilevel class hierarchy
JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Overview
This lesson covers the following topics:
Recognize when constructors are called in a class hierarchy
Demonstrate understanding of inheritance through the use
of applets
Recognize correct parameter changes in an existing applet

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

What is Inheritance?
Inheritance is a simple but powerful tool of
object oriented languages that allows classes
to inherit methods and fields from other
classes.
Inherit means to receive or obtain something
from your predecessor or parent.
In Java, the concept of inheritance is similar
to genetics.
Genes and genetic traits are passed down from
parent to child.
Children often look and act like their parents as a
result.
JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

More Information about Inheritance


For more information about inheritance, visit:
http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Superclass versus Subclass


Classes can derive from or evolve out of parent classes, which
means they contain the same methods and fields as their
parents, but can be considered a more specialized form of
their parent classes.
The difference between a subclass and a superclass is as
follows:
Superclass

Subclass

The more general class from which


other classes derive their methods and
data.

The more specific class that derives or


inherits from another class (the
superclass).

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Superclass versus Subclass


Superclasses contain methods and fields that are passed
down to all of their subclasses.
Subclasses:
Inherit methods and fields of their superclasses.
May define additional methods or fields that the superclass does not
have.
General

Superclass

Specific

Subclass

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Inheritance Example
Create a Shape class with a variable, color, and one method
which returns the color. Create a Rectangle class which
inherits the variable and method from Shape, and can have
its own methods and variables.
Shape (superclass)
public String color
public String getColor()
Rectangle (subclass)
public String color
public String getColor()
//Rectangle-only data
public int length
public int width
public int getLength()
public int getWidth()
JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Superclass vs. Subclass Example


Consider the Animal and Crab classes from Greenfoot.
Animal is a more general term than Crab and can apply to
more creatures than just Crab.
A Crab is a type of Animal and that Crab applies to a specific
type of Animal.
Therefore, Crab is the subclass and Animal is the superclass.

JF 7-4
Inheritance

General

Animal

Specific

Crab

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Crab Class move Method


Where does the method move() come from in Crab?
There is no visible code showing the logic for the move()
method in the class Crab.
public class Crab extends Animal
{
public void act()
{
move(1);
}
}

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Inherited move Method


Even though the code isn't written in the Crab class, we know
a Crab object can call the move() method.
Therefore, the code must be inherited from the superclass,
Animal, as follows:
public class Animal
{
public void move(int d)
{
//Logic for move()
}
}

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

extends Keyword
In Java, you have the choice of which classes you want to
inherit from by using the keyword extends.
The keyword extends allows you to designate the superclass
that has methods you want to inherit, or whose methods and
data you want to extend.
For example, to inherit methods from the Shape class, use
extends when the Rectangle class is created.
public class Rectangle extends Shape
{
//code
}

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

extends Keyword Example


We want the Crab class to extend the methods and data in
Animal and inherit methods like move(), turn(), etc.
Because the Animal class is extended, you can call the move()
and turn() methods even though they do not appear within
the Crab class code.
public class Crab extends Animal
{
public void act()
{
move(1);
turn(90);
}
}

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

The Rule of Single Inheritance


Single inheritance means that you cannot declare or extend
more than one superclass per class.
The following code will not compile:
public class Crab extends Animal, Crustacean, ...

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Extending More than One Class


Why can't we extend more than one class?
Since superclasses pass down their methods and data to all of
their subclasses and the subclasses of their subclasses, it isn't
really necessary to extend more than one class.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

More About Inheritance


Inheritance is a one-way street.
Subclasses inherit from superclasses, but superclasses cannot
access or inherit methods and data from their subclasses.
This is just like how parents don't inherit genetic traits like
hair color or eye color from their children.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Object: The Highest Superclass


Every superclass implicitly extends the class Object.
Object:
Is considered the highest and most general component of any
hierarchy. It is the only class that does not have a superclass.
Contains very general methods which every class inherits.
General

Specific

Superclass

Subclass

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Object Example 1
Object contains methods that can be used on every class
(such as toString(), or equals()).
For example, after you create a class and construct an
instance of it, can you call the method toString() on your
object?
A_Class class = new A_Class();
class.toString();

Yes. Even though you did not write the method toString(), it is
still legal for you to call this method because it was inherited
from Object.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Object Example 2
Is class.toString() legal if A_Class explicitly extends
Another_Class, a superclass?
Yes. This is also legal since the superclass of A_Class extends
Object.
A_Class class = new A_Class();
class.toString();

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Why Use Inheritance?


The central benefit to inheritance is code reuse.
Inheriting methods from a superclass gives your class access
to the code and data of the superclass.
You will not have to write the code twice, which saves you
time and optimizes your code.
Also, fewer bugs occur.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Inheritance Hierarchies
In many situations, it's common to classify concepts as
hierarchies.
A hierarchy is a way of categorizing the relationship among
ideas, concepts or things with the most general or allencompassing component at the top and the more specific,
or the component with the narrowest scope, at the bottom.
Hierarchies are a useful concept when it comes to inheritance
and can be used to model and organize the relationship
among superclasses and subclasses.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Tree Diagrams
Hierarchies can be organized into tree diagrams.
Computer Scientists will often refer to trees having leaves and
branches, or will refer to the "leaves" as nodes.
For example, shapes can be categorized by different
properties, such as their number of sides.
Branch

Triangle

Shape

Rectangle

Leaf/Node

Circle

Square
JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Tree Diagrams
Notice that Circle, Triangle, and Rectangle all have a different
number of sides, so they are different branches in the tree.
Only nodes with the same properties will occupy the same
branch.
Shape

Triangle

Rectangle

Circle

Square

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Type of Parent Nodes


Anything below a node on the tree is a type of the parent
node.
We know that Square is a type of Rectangle.
Triangle, Rectangle, and Circle are all types of shapes.
Shape

Triangle

Rectangle
Square

JF 7-4
Inheritance

Circle
Type

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Inheritance Hierarchies: "is-a"


With class hierarchies, you can use the phrase "is-a" to
describe a hierarchical relationship.
A node on a branch can be thought of as the same type as the
node on the root.
Example: A Rectangle "is-a" Shape, since it has all of the
properties of a shape.
To model relationships among classes, we use UML.
Shape
Is A
Rectangle
JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Unified Modeling Language: UML


Computer scientists model inheritance hierarchies using a
modeling language called Unified Modeling Language, or
UML.
UML is a way of describing the relationships among classes in
a system, or graphical representation of a system.
UML was developed by Grady Booch, James Rumbaugh, and
Ivar Jacobson, and is standardized so it can be understood
across languages.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Basic Components of UML


Inheritance hierarchies can be modeled simply with UML.
A few simple components are required to start:
Class diagram: Shows the name of the class, and any important data or
methods within the class.
Arrows and lines: Show one class's relationship to other classes.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Class Diagram in UML


A class can be drawn as a box that contains the class name,
instance variables, and methods.
Classes can also be drawn as simple boxes with just the class
name, although including methods is helpful.
It is not necessary to include every attribute or those that
represent collections of data (such as arrays). Include only the
most helpful attributes.
Class Name

Shape

Attributes

Color

Methods

getColor()

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

More Details About UML


UML is a helpful tool for you to plan out how to organize
multilevel class hierarchies.
You are encouraged to use UML for coding projects.
For a more detailed look at UML, visit:
http://www.oracle.com/technetwork/developertools/jdev/gettingstartedwithumlclassmodeling-130316.pdf

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Showing Inheritance in UML


Class diagrams are connected using lines with arrows.
Connecting lines vary depending on the relationship among
classes.
For inheritance, a solid line and a triangular arrow are used to
represent the "is-a" relationship.
Relationship

Symbol

Inheritance

Rectangle
public int length
public int width
public int getLength()
public int getWidth()

JF 7-4
Inheritance

Shape
String color
getColor()

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Encapsulation
Encapsulation is a fundamental concept in object oriented
programming.
Encapsulation means to enclose something into a capsule or
container, such as putting a letter in an envelope. In object-oriented
programming, encapsulation encloses, or wraps, the internal workings
of a Java instance/object

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

How Encapsulation Works


In object-oriented programming,
encapsulation encloses, or wraps, the
internal workings of a Java instance/object.
Data variables, or fields, are hidden from the
user of the object.
Methods can provide access to the private
data or work with the data, but methods
hide the implementation.
Encapsulating your data prevents it from
being modified by the user or other classes
so that the data is not corrupted.
JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

How Encapsulation is Used


Encapsulation can be used to protect sensitive data, such as
personal information, by preventing the data from being
changed, except within the scope of the class itself.
Data is protected and implementation is hidden by declaring
access modifiers on variables and methods.
Access modifiers (public, private, protected, "default") are
keywords that determine whether or not other classes can
access the data or methods of the class.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Access Modifiers
Programmers can customize the visibility of their data and
methods with several levels of access modifiers.
Access Modifier

Accessed by:

public

Any class in any package.

private

Only to other methods within the class itself.

protected

All subclasses and all classes in the same package.

"default"

Any class in the package. Actually when no keyword is


specified. The word default is NOT used.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

35

Declaring Access Modifiers


The general rule for declaring access modifiers is that any
data you want to protect from being altered by other classes,
or data that is sensitive, should be declared private.
This includes variables.
Methods are generally declared as public so other classes can
use them.
However, methods can be declared private when they are
meant to be used only by the class itself.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

36

Declaring Access Modifiers Example


If the Shape class contained data for color, the data in this
class should be private.
public class Shape {
private String color;
}

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

37

Member Access
Use the keyword private to hide data that only the class
should be able to change. (This is the recommended access
modifier.) If access to the data is needed, then a getter
method should be written to achieve this.
public class Shape {
//the color of the Shape
private String color;

//Method which returns the color


public String getColor() {
return color;
}

With the Shape class, we do not


want objects to change the
color of this Shape. Writing
private in the variable
declaration achieves this.

The method getColor() returns


the color. Any method that is
meant for accessing private data
should be public.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

38

Member Access
If the private variables need to be (or are allowed to be)
changed, then a setter method should be written.
public class Shape {
//the color of the Shape
private String color;

//Method which returns the color


public String getColor() {
return color;
}
//Method to change the color
public void setColor(String c){
color = c;
}

JF 7-4
Inheritance

If the color needs to be


changed, a setter method is
created.

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

39

Use Public or Protected to Access Data?


If we wanted the ability to alter the Shape's variable color
from outside the Shape class code, we could set the String
variable color to be public or protected.
However, it is recommended that class variables are declared
as private.
public class Shape {
protected String color;
}
public class Shape {
public String color;
}

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

40

Changing the Color


If the variable is declared as public, code that extends or
creates a Shape object could change the color without using
an accessor method like setColor().
Not recommended
//example for extending the shape class, then changing the color
super.color = "Blue";
//example for creating a Shape object and changing the color
Shape s1 = new Shape();
s1.color = "Blue";

Not recommended

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

41

Member Access and Inheritance


How do these access modifiers affect inheritance?
With encapsulation, even subclasses cannot access private
methods and variables.
public and protected modifiers provide access to superclass
methods and variables.
Access Modifier

Accessed by:

public

All classes.

private

Only the class itself.

protected

All subclasses and all classes in the same package.

"default"

If no keyword is specified, member variables can be


accessed by any class in the package.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

42

Extending the Shape Class


Since Shape is not a specific class, we can extend it by
creating more specific classes, such as, Rectangle and Square.
We will begin by creating a Rectangle class that extends the
Shape class.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

43

Inheriting Constructors
Although a subclass inherits all of the methods and fields
from a parent class, it does not inherit constructors.
You can:
Write your own constructor or constructors.
Use the default constructor.
If you do not declare a constructor, a default no-argument constructor is
provided for you.
If you declare your own constructor, the default constructor is no longer
provided.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

44

Using the Keyword super in a Constructor


When creating a Rectangle object, you will need to set the
color of the Rectangle. If the variable color is private in the
Shape superclass, how do you set it?
To construct an instance of a subclass, it is often easiest to call
the constructor of the parent class.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

45

Using the Keyword super in a Constructor


The super keyword is used to call a parent's constructor.
It must be the first statement of the constructor.
If it is not provided, a default call to super() is implicitly
inserted for you.
The super keyword may also be used to invoke a parent's
method or to access a parent's (non-private) field.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

46

Using the Super Keyword Example


public class Rectangle extends Shape
{
private int length;
private int width;

//Constructor
public Rectangle(String color, int length, int width)
{
This calls the constructor for
super(color);
Shape, which initializes the
this.length = length;
variable color.
this.width = width;
}

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

47

Adding methods for the Rectangle Class


Rectangle methods that would be useful include:
public int getWidth()
public int setWidth(int width)
public int getHeight()
public int setHeight(int height)
public int getArea()

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

48

Rectangle Class Methods


Since Square is a type of Rectangle, or extends the Rectangle
class, it will inherit all of the methods from the Rectangle
superclass:
public int getWidth()
public int setWidth(int width)
public int getHeight()
public int setHeight(int height)
public int getArea()

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

49

Set Up the Class


This code sets up the class.
Use the keyword extends to inherit the methods from
Rectangle.
public class Square extends Rectangle {
}

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

50

Write the Constructor


To write the constructor, consider what values need to be
initialized.
If we use the Rectangle super constructor, we need to pass it
the values: String color, int length, and int width.
Our Square constructor requires these as parameters if we
want to call the super constructor.
public class Square extends Rectangle {
public Square(String color, int length, int width) {
}

Aren't length and width equal


for a square?

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

51

Size Parameter
Although Squares are a type of Rectangle, they have a unique
property such that length = width.
Accommodate this by only requiring one size parameter that
sets both the width and length values.
public class Square extends Rectangle {

public Square(String color, int size) {


super(color, size, size);

JF 7-4
Inheritance

Instead of passing two


different parameters of
length and width, we can
pass a size parameter twice,
which will set the length and
width values (located in the
Rectangle class) to be equal.

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

52

Unique Variables for the Subclass


What about unique variables that apply only to Squares and
not Rectangles?
For example, a feature that tells us whether or not to fill in a
Square. Add a boolean value in the parameters list to add this
unique variable for the Square class:
public class Square extends Rectangle {
private boolean isFilled;

The variable isFilled is unique to the


Square class and is an example of how
subclasses can contain more methods or
fields than their superclasses.

public Square(String color, int size, boolean isFilled){


super(color, size, size);
this.isFilled = isFilled;
}

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

53

Customize Methods
Because a Square has the same values for height and width,
we want to customize the methods setWidth(int width) and
setHeight(int height) so that both are updated when the
method is called.
Use the keyword super to call the superclass's methods
setLength() and setWidth() and set them both to the
parameter value passed to the method.
public int setWidth(int width){
super.setLength(width);
super.setWidth(width);
}

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

54

Square Subclass
The final product will look like the following:
public class Square extends Rectangle {

private boolean isFilled;


public Square(String color, int size, boolean isFilled) {
super(color, size, size);
this.isFilled = isFilled;
}
public void setLength(int length) {
super.setLength(length);
super.setWidth(length);
}
public void setWidth(int width) {
super.setWidth(width);
super.setLength(width);
}
public boolean getIsFilled() {
return isFilled;
}

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

55

Inheritance and Applets


Java applets are another example of using inheritance.
A Java applet is a web-based Java program that can be
embedded into a web browser.
The class Applet can be extended to create special applets
using some of the core methods in the Applet class.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

56

Java Documentation for Applet Class


Visit the Java Documentation for the Applet class to learn
more.
For all documentation, visit:
http://docs.oracle.com/javase/7/docs/api/

For just the class Applet's documentation, visit:


http://docs.oracle.com/javase/7/docs/api/java/applet/Applet.html

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

57

Creating Applets
To create an applet, you can borrow all of the core methods
in the Applet class and customize these methods to suit the
particular needs of your applet.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

58

Creating Applets
For example, to make an applet that draws Shapes, start by
setting up the inheritance with extends:
public class DrawShapes extends Applet
...
}

Now our applet class DrawShapes will inherit methods from


Applet that we can customize to build the applet.

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

59

Applet Example
import
import
import
import
public

java.applet.Applet;
java.awt.Graphics;
java.awt.Graphis2D;
java.awt.Rectangle;
class RectangleApplet extends Applet{

public void paint(Graphics g){


Graphics2D g2 = (Graphics2D)g;
Rectangle testRectangle = new Rectangle(5,10,20,30);
g2.draw(testRectangle);
}

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

60

Terminology
Key terms used in this lesson included:
Access modifiers
Child class
default
Encapsulation
extends
Hierarchy
Inheritance
"is-a" relationship
JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

61

Terminology
Key terms used in this lesson included:
Parent class
private
protected
public
Subclass
super
Superclass
Unified Modeling Language (UML)
JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

62

Summary
In this lesson, you should have learned how to:
Demonstrate and explain UML (Unified Modeling Language)
class diagrams
Use the extends keyword to inherit a class
Compare and contrast superclasses and subclasses
Describe how inheritance affects member access
Use super to call a superclass constructor
Use super to access superclass members

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

63

Summary
In this lesson, you should have learned how to:
Create a multilevel class hierarchy
Recognize when constructors are called in a class hierarchy
Demonstrate understanding of inheritance through the use
of applets
Recognize correct parameter changes in an existing applet

JF 7-4
Inheritance

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

64

Java Fundamentals

7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Objectives
This lesson covers the following objectives:
Apply superclass references to subclass objects
Write code to override methods
Use dynamic method dispatch to support polymorphism
Create abstract methods and classes
Recognize a correct method override

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Overview
This lesson covers the following topics:
Use the final modifier
Explain the purpose and importance of the Object class
Write code for an applet that displays two triangles of
different colors
Describe object references

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Review of Inheritance
When one class inherits from another, the subclass "is-a"
type of the superclass.
Objects of a subclass can be referenced using a superclass
reference, or type.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Learn More
Visit Oracle's tutorial pages to learn more:
Inheritance:

http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

Polymorphism:

http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Inheritance Example
If classes are created for a Bicycle class and a RoadBike class
that extends Bicycle, a reference of type Bicycle can reference
a RoadBike object.
Because RoadBike "is-a" type of Bicycle, it is perfectly legal to
store a RoadBike object as a Bicycle reference.
The type of a variable (or reference) does not determine the
actual type of the object that it refers to.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Inheritance Example
Therefore, a Bicycle reference, or variable, may or may not
contain an object of the superclass type Bicycle since it can
contain any subclass of Bicycle.
Bicycle bike = new RoadBike();

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Polymorphism
When a variable or reference may refer to different types of
objects is called polymorphism.
Polymorphism is a term that means "many forms".
In the case of programming, polymorphism allows variables
to refer to many different types of objects, meaning they can
have multiple forms.
For example, because RoadBike "is-a" Bicycle, there are two
possible references that define the type of object it is (Bicycle
or RoadBike).

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Polymorphism and Nesting Dolls


Polymorphism can be visualized like a set of nesting dolls: The
set of dolls share a type and appearance, but are all unique in
some way.
Each doll has the same shape, with a size determined by the
doll it must fit inside of.
Each smaller doll is stored inside of the next larger doll. From
the outside you do not see the smaller dolls, but you can
open each doll to find a smaller doll inside.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

10

Superclasses and Subclasses


In a similar way, subclasses can "fit" within the reference type
of a superclass.
A superclass variable can hold, or store, a subclass's object,
while looking and acting like the superclass.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

11

Superclass Variables
If you "open up" a superclass variable, or invoke one of its
methods, you will find that you actually have a subclass
object stored inside.
For example, with nesting dolls, you cannot see the smaller
doll until you open the larger doll. Its type may be ambiguous.
When Java code is compiled, Java does not check to see what
type (supertype or subtype) of object is inside a variable.
When Java code is executed, Java will "open up" to see what
type of object is inside the reference, and call methods that
are of that type.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

12

Uncertainty when Referencing Objects


There are benefits to uncertainty when referencing different
objects at compile time. For example:
You write a program that calculates the different tube lengths
of a bicycle frame, given a rider's measurements and type of
bicycle desired (RoadBike or MountainBike).
You want a list to keep track of how many bike objects you
have built. You want only one list, not two separate lists for
each type of bike.
How do you build that list? An array, perhaps?
What's problematic about using an array to build the list?
JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

13

Why Not Use an Array of Class Objects?


Arrays are a collection of elements of the same type, such as
a collection of integers, doubles, or Bicycles.
While it is possible to have an array of objects, they must be
the same type.
This is fine for classes that are not extended.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

14

Why Not Use an Array of Class Objects?


Polymorphism solves this problem.
Since RoadBike and MountainBike are both types of Bicycle
objects, use an array of Bicycle references to store the list of
bikes you have built.
Either type of Bicycle can be added to this array.
Bicycle[] bikes = new Bicycle[size];

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

15

Object References
The Object class is the highest superclass in Java, since it does
not extend another class.
As a result, any class can be stored in an Object reference.
Object[] objects = new Bicycle[size];

In this array example, it is also valid to store our bikes in an


array of Object references.
However, this makes our array type even more ambiguous,
and should be avoided unless there is a reason to do so.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

16

Overriding Methods from Object


Since Object is the superclass of all classes, we know that all
classes inherit methods from Object.
Two of these methods are very useful, such as the equals()
method and the toString() method.
The equals() method allows us to check if two references are
referencing the same object.
The toString() method returns a String that represents the
object.
The String provides basic information about the object such
as it's class, name, and a unique hashcode.
JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

17

Overriding or Redefining Methods


Although the equals() and toString() methods are useful, they
are missing functionality for more specific use.
For the Bicycle class, we may want to generate a String
containing the model number, color, frame type, and price.
Using the method from Object will not return this
information.
The toString() method in the Object class returns a String
representation of the object's location in memory.
Rather than creating a method by another name, we can
override the toString() method, and redefine it to suit our
needs.
JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

18

Overriding Methods
Overriding methods is a way of redefining methods with the
same return type and parameters by adding, or overriding
the existing logic, in a subclass method.
Overriding is different than overloading a method.
Overloading a method means the programmer keeps the
same name (i.e. toString()), but changes the input parameters
(method signature).
Overriding essentially hides the parent's method with the
same signature, and it will not be invoked on a subclass
object unless the subclass uses the keyword super.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

19

Overriding Methods
Overriding does not change the parameters.
It only changes the logic inside the method defined in the
superclass.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

20

Java Tutorials on Overriding Methods


Visit Oracle's Java tutorials for more information on
overriding methods:
http://docs.oracle.com/javase/tutorial/java/IandI/override.html

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

21

Overriding toString()
We can override toString() to return a String that provides
information about the object instead of the location of the
object in memory. First, start with the prototype:
public String toString()

There is no reason to change the return type or parameters,


so we will override toString().
Given our private data (model number, color, frame type, and
price) we can return the following String:
return "Model: " + modelNum +
" Color: " + color +
" Frame Type: " + frameType +
" Price: " + price;

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

22

Overriding toString()
The result for our overridden toString() method:
public String toString(){
return "Model: " + modelNum +
" Color: " + color +
" Frame Type: " + frameType +
" Price: " + price;

It is very common and very helpful when creating Java classes


to override the toString() method to test your methods and
data.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

23

Understanding the Object Model


Polymorphism, like inheritance, is central to the object model
and object oriented programming.
Polymorphism provides for versatility in working with objects
and references while keeping the objects discrete or distinct.
At the heart of the philosophy, the object model turns
programs into a collection of objects versus a set of tasks,
encapsulating the data and creating smaller pieces of a
program, rather than a single large chunk of code.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

24

Object Model Goals


The object model has several goals:
Data abstraction
Protecting information and limiting other classes' ability to change or
corrupt data
Concealing implementation
Providing modular code that can be reused by other programs or
classes.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

25

Polymorphism and Methods


How are the methods in the subclass affected by
polymorphism?
Remember, subclasses may inherit methods from their
superclasses.
If a Bicycle variable can hold a subclasses' object type, how
does Java know which methods to invoke when an overridden
method is called?

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

26

Polymorphism and Methods


Methods called on a reference (bike) will always refer to
methods within the object's (RoadBike) type.
Bicycle bike = new RoadBike();

Imagine that our Bicycle class contains a method


setColor(Color color) to set the color of the bike the rider
wants.
RoadBike inherits this method.
What happens when we do the following?
bike.setColor(new Color(0, 26, 150));

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

27

Dynamic Method Dispatch


Java is able to determine which method to invoke based on
the type of the object being referred to at the time the
method is called.
Dynamic Method Dispatch, also known as Dynamic Binding,
allows Java to correctly and automatically determine which
method to invoke based on the reference type and the object
type.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

28

Abstract Classes
Is it really necessary to define a Bicycle class if we are only
going to create objects of its subclasses: roadBikes and
mountainBikes?
Abstract classes are one alternative that addresses this
concern.
An abstract class is one that cannot be instantiated:
This means that you cannot create objects of this type.
It is possible to create variables, or references of this type.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

29

Abstract Classes
If we declare the Bicycle class to be abstract, we can still use
the syntax below, but we cannot actually create a Bicycle
object.
This means all references of type Bicycle will reference
subclass objects MountainBike or RoadBike.
Bicycle bike = new RoadBike();

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

30

Abstract Classes
Abstract classes can contain fully-implemented methods that
they "pass on" to any class that extends them.
Make a class abstract by using the keyword abstract.
public abstract class Bicycle

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

31

Abstract Classes
Abstract classes can also declare at least one abstract method
(method that does not contain any implementation.
This means the subclasses must use the method prototype
(outline) and must implement these methods.
Abstract methods are declared with the abstract keyword.
abstract public void setPrice();

Declare as abstract
public. Do not use {}.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

32

Abstract Methods
Abstract methods:
Cannot have a method body.
Must be declared in an abstract class.
Must be overridden in a subclass.

This forces programmers to implement and redefine


methods.
Typically, abstract classes contain abstract methods, partially
implemented methods, or fully-implemented methods.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

33

Partially Implemented Methods


Recall that subclasses can call their superclass's constructor
and methods using the keyword super.
With abstract classes, subclasses can also use super to use
their superclass's method.
Typically this is done by first overriding the superclass's
method, then calling the super, or overridden method, and
then adding code.
For example, let's override the equals() method from the
abstract class Bicycle, which is implemented partially.
This means that the equals() method in Bicycle is not
abstract.
JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

34

Partially Implemented Methods


This compares two Bicycle objects based on price and model
number.
Note, this method overrides the equals() method from Object
because it has the same parameters and return type.
public boolean equals(Object obj) {
if(this.price == obj.price && this.modelNum == obj.modelNum) {
return true;
} else {
return false;
}
}

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

35

Partially Implemented Methods


We can override the method in our subclass MountainBike
and check for equivalence on other attributes.
public boolean equals(Object obj) {
if(super.equals(obj)) {
if(this.suspension == obj.suspension)
return true;
}
return false;
}

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

36

Subclassing Abstract Classes


When inheriting from an abstract class, you must do either of
the following:
Declare the child class as abstract.
Override all abstract methods inherited from the parent class.
Failure to do so will result in a compile-time error.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

37

Using Final
Although it is nice to have the option, in some cases, you may
not want some methods to be overridden or to have your
class extended.
Java provides a tool to prevent programmers from overriding
methods or creating subclasses: the keyword final.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

38

Using Final
A good example is the String class.
It is declared:
public final class String {}

Programmers will refer to classes like this as immutable,


meaning that no one can extend String and modify or
override its methods.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

39

Using Final
The final modifier can be applied to variables.
Final variables may not change their values after they are
initialized.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

40

Using Final
Final variables can be:
Class fields
Final fields with compile-time constant expressions are constant variables.
Static can be combined with final to create an always-available, neverchanging variable.

Method parameters
Local variables

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

41

Using Final
Final references must always reference the same object.
The object to which the variable is referencing cannot be
changed.
The contents of that object may be modified.
Visit Oracle's Java tutorial for more information on using final:
http://docs.oracle.com/javase/tutorial/java/IandI/final.html

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

42

Triangle Applet Code


The following code shows the steps involved in writing an
applet with two triangles of different colors.
public class TrianglesApplet extends Applet{
public void paint(Graphics g){
int[] xPoints = {0, 40, 80};
int[] yPoints = {50, 0, 50};
g.setColor(Color.blue);
g.fillPolygon(xPoints, yPoints, 3);
int[] x2Points = {80, 160, 0};
int[] y2Points = {50, 140, 140};
g.setColor(Color.black);
g.fillPolygon(x2Points, y2Points, 3);
}
}

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

43

Triangle Applet Code Explained


Step 1: Extend Applet class to inherit all methods including
paint.
Step 2: Override the paint method to include the triangles.
Step 3: Draw the triangle using the inherited fillPolygon
method.
Step 4: Draw the 2nd triangle using the inherited fillPolygon
method.
Step 5: Run and compile your code.

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

44

Triangle Applet Image


The Triangle Applet code displays the following image:

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

45

Terminology
Key terms used in this lesson included:
abstract
Dynamic Method Dispatch
final
Immutable
Overloading methods
Overriding methods
Polymorphism

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

46

Summary
In this lesson, you should have learned how to:
Apply superclass references to subclass objects
Write code to override methods
Use dynamic method dispatch to support polymorphism
Create abstract methods and classes
Recognize a correct method override

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

47

Summary
In this lesson, you should have learned how to:
Use the final modifier
Explain the purpose and importance of the Object class
Write code for an applet that displays two triangles of
different colors
Describe object references

JF 7-5
Polymorphism

Copyright 2015, Oracle and/or its affiliates. All rights reserved.

48