s4-Java
s4-Java
Which way
shall I go?
The if/else Statement
Boolean
expression
if ( <some condition is true> ) {
// do something if
} block
else {
// do something different
}
else block
Boolean expressions
Review:
• boolean data type has only two possible values:
– true
– false
Relational operators
Relational Operators
24 int attendees = 4;
25 boolean largeVenue;
26
27 // if statement example
28 if (attendees >= 5){
29 largeVenue = true;
30 } Assign a boolean
31 else { by using an if
32 largeVenue = false; statement.
33 }
34
Assign the
35 // same outcome with less code
boolean directly
36 largeVenue = (attendees >= 5);
from the Boolean
expression.
Exercise 5-1: Using if Statements
0 1 2 3
27 12 82 70
Array Examples
us s ie ys n is n
g it re ng rk e l lo r aw
on Di e K e or
M Da n tK De rM M De
L
gh r on ta ber r ri e l te ugh oe
S a
Hu Aa Al Ca W H M
Array Indices and Length
First Element
index at index 5
00 1 2 3 4 5 6 7 Indices
27 12 82 70 54 1
1 30 34
Array length is 8.
(ages.length)
Declaring and Initializing an Array
• Syntax:
type[] arrayIdentifier = {comma-separated list of
values};
All in
one
line
Declaring and Initializing an Array
• Examples:
• 1 int[] ages = new int[3];
• 2 ages[0] = 19; Multistep
• 3 ages[1] = 42; approach
• 4 ages[2] = 92;
• 5
• 6 String[] names = new String[3]; Multistep
• 7 names[0] = "Mary","Bob","Carlos";
approach
• 8 names[1] = "Mary","Bob","Carlos";
• 9 names[2] = "Mary","Bob","Carlos";
Accessing Array Elements
names[0] = "Gary";
names[1] = "Rob";
Exercise 5-2: Using an Array
Each iteration
returns the next
for (String name : names ) { element of the
System.out.println("Name is " + name); array.
}
Output:
Name is George
Name is Jill
Name is Xinyi
Name is Ravi
Using break with Loops
break example:
01 int passmark = 12;
02 boolean passed = false;
03 int[] scores = {4,6,2,8,12,35,9};
04 for (int unitScore : scores){
05 if (unitScore >= 12){ No need to go
06 passed = true; through the
07 break; loop again, so
08 } use break.
09 }
10 System.out.println("At least one passed? " +passed);
Output:
At least one passed? true
Exercise 5-3: Using a Loop to Process an Array
his
Play t
-
g am e
.
m od e
02/22/2025 33
Describing Objects and Classes
Interactive Quizzes
Objectives
After completing this lesson, you should be able to:
• List the characteristics of an object
• Define an object as an instance of a class
• Instantiate an object and access its fields and methods
• Describe how objects are stored in memory
• Instantiate an array of objects
• Describe how an array of objects is stored in memory
• Declare and instantiate an object as a field
• Use the NetBeans IDE to create and test Java classes
Topics
• Describing objects and classes
• Defining fields and methods
• Declaring, instantiating, and using objects
• Working with object references
• Doing more with arrays
• Introducing NetBeans IDE
• Introducing the soccer league use case
Java Puzzle Ball
Have you played Basic Puzzle 5?
instance
instance
Object-Oriented Programming
• Interaction of objects
• No prescribed sequence
Duke’s Choice Order Process
Characteristics of Objects
Objects are physical or conceptual.
• Objects have properties:
• Size
• Shape
• Name
• Color
• Objects have behaviors:
• Shop Mrs.
• Put item in cart Duke Color property value is
• Pay red
Classes and Instances
• A class:
• Is a blueprint or recipe for an object
• Describes an object’s properties and behaviors
• Is used to create object instances
Object instances
Class
-Properties
-Behaviors
Quiz
Which of the following statements is true?
a. An object is a blueprint for a class.
b. An object and a class are exactly the same.
c. An object is an instance of a class.
d. A class is an instance of an object.
Topics
• Describing objects and classes
• Defining fields and methods
• Declaring, instantiating, and using objects
• Working with object references
• Doing more with arrays
• Introducing NetBeans IDE
• Introducing the soccer league use case
The Customer Properties and Behaviors
Properties: Behaviors:
• Name • Shop
• Address
• Set Address
• Age
• Order number • Add item to cart
• Customer number • Ask for a discount
• Display customer details
The Components of a Class
Class
declaration
requestDiscount()
setAddress() Methods
shop()
displayCustomer()
Exercise 6-1: Creating the Item Class
In this exercise, you create the Item class and declare public fields for ID
(int), descr, quantity (int), and price (double).
Topics
• Describing objects and classes
• Defining fields and methods
• Declaring, instantiating, and using objects
• Working with object references
• Doing more with arrays
• Introducing NetBeans IDE
• Introducing the soccer league use case
Customer Instances
customer01
customer02
1 1
Pick up the remote to Create a Camera object
gain access to the and get a reference to it.
camera.
11 Camera remote1;
12
13 remote1 = new Camera();
14
15 remove1.play();
2 2
Press the remote’s Call a method to have the
controls to have camera Camera object do
do something. something.
Working with Object References
remote remote
1 2
Television
Camcorder
Television
Camcorder remote
remote
References to Different Objects
Reference
type
Reference
variable
Create a new object.
counter 10
0x99f311
myShirt 0x034009 12 shirtID
15.99 price
yourShirt 0x99f311
colorCode
B
Variables Objects
Assigning a Reference to Another Reference
myShirt = yourShirt;
0x034009
12
15.99
B
counter 10
0x99f311
myShirt 0x99f311 12 shirtID
15.99 price
yourShirt 0x99f311
colorCode
B
Two References, One Object
Code fragment:
Shirt color: G
Exercise 6-2: Modify the ShoppingCart to Use
Item Fields
• In this exercise, you:
• Declare and instantiate two variables of type Item in the
ShoppingCart class
• Experiment with accessing properties and calling methods on the
object
Topics
• Describing objects and classes
• Defining fields and methods
• Declaring, instantiating, and using objects
• Working with object references
• Doing more with arrays
• Introducing NetBeans IDE
• Introducing the soccer league use case
Arrays Are Objects
Arrays are handled by an implicit Array object.
• The Array variable is an object reference, not a primitive data type.
• It must be instantiated, just like other objects.
• Example:
int[] ages = new ages[4];
This array
• Previously, you have been using a shortcut to instantiate
canyourhold
arrays.
four
• Example:
elements.
int[] ages = {8,7,4,5};
Declaring, Instantiating, and Initializing
Arrays
All in
• Examples: one
1 String[] names = {"Mary","Bob","Carlos"}; line
2
3 int[] ages = new int[3];
Multistep
4 ages[0] = 19;
approach
5 ages[1] = 42;
6 ages[2] = 92;
int [] ages;
ages = {19, 42, 92};
Storing Arrays in Memory
Primitive
variable of
type int
0x034009
age
35 0 19 Primitive
ages 0x034009
1 42 variables of
2 92 type int held
as array
elements
Storing Arrays of Object References in Memory
0 itemId
item 0x034009 0.0 price
U colorCode
0 itemId
0.0 price
U colorCode
Quiz
The following code is the correct syntax for _____ an array:
array_identifier = new type[length];
a. Declaring
b. Setting array values for
c. Instantiating
d. Declaring, instantiating, and setting array values for
Quiz
Given the following array declaration, which of the following statements
are true?
• int [ ] ages = new int [13];
a. ages[0] is the reference to the first element in the array.
b. ages[13] is the reference to the last element in the array.
c. There are 13 integers in the ages array.
d. ages[5] has a value of 0.
Topics
• Describing objects and classes
• Defining fields and methods
• Declaring, instantiating, and using objects
• Working with object references
• Doing more with arrays
• Introducing NetBeans IDE
• Introducing the soccer league use case
Java IDEs
A Java Integrated Development Environment (IDE) is a type of software
that makes it easier to develop Java applications.
• An IDE provides:
• Syntax checking
• Various automation features
• Runtime environment for testing
• It enables you to organize all your Java resources and environment settings
into a Project.
The NetBeans IDE
Code
Project
Editor
Navigator
Class
Navigato
r
Program Output
Creating a Java Project
1. Select File > New Project.
2. Select Java Application.
3. Name and set the location
for the project.
4. Select “Create Main Class”
if you want it done for you
automatically.
5. Click Finish.
Creating a Java Class
1. Select File > New File.
2. Select your project and choose Java Class.
3. Name the class.
4. Assign a package.
5. Click Finish.
Avoiding Syntax Problems
The code editor will tell you when you have done something wrong.
Compile Error: Variable Not Initialized
1 public static void main(String[] args){
2
3 Customer customer01; //Declare the reference
4 //No instantiation
5 customer01.name = "Robert";
9
10 }
NetBeans indicates
that the variable
may not have been
initialized.
Runtime Error: NullPointerException
1 public static void main(String[] args){
2
3 Customer customer01; //Declare the reference
4 customer01 = new Customer(); //Instantiate and assign
5 customer01.name = "Robert";
6
7 Customer[] customers = new Customer[5];
8 customers[0].name = "Robert";
9
10 }
Save is
equivalent to
javac.
Run is
equivalent
to java.
Topics
• Describing objects and classes
• Defining fields and methods
• Declaring, instantiating, and using objects
• Working with object references
• Doing more with arrays
• Introducing NetBeans IDE
• Introducing the soccer league use case
Soccer Application
Practices 6 through 14 build a soccer league application with the following
features:
• Any number of soccer teams, each with up to 11 players
• Set up an all-play-all league.
• Use a random play game generator to create test games.
• Determine the rank order of teams at the end of the season.
Creating the Soccer Application
A
separate
project
for each
practice
Sample output
showing
events in a
game
Sample output
showing rank
order of teams
Soccer Web Application
Points and
Click the goals scored
Teams listed score of a used for
in rank order game to ordering
show game
details.
Summary
In this lesson, you should have learned how to:
• Describe the characteristics of a class
• Define an object as an instance of a class
• Instantiate an object and access its fields and methods
• Describe how objects are stored in memory
• Instantiate an array of objects
• Describe how an array of objects is stored in memory
• Declare an object as a field
• Use the NetBeans IDE
Challenge Questions: Java Puzzle Ball
• How many objects can you identify in the game?
• Given that a class is a blueprint for an object, which game components best
reflect the class/instance relationship?
• How many object properties can you find?
• Can you guess what some of the methods might be?
Practice 6-1 Overview:
Creating Classes for the Soccer League
This practice covers creating the five classes required for the soccer
application:
• Goal
• Game
• Player
• Team
• League
Practice 6-2 Overview:
Creating a Soccer Game
This practice covers the following topics:
• Creating a new game
• Adding some goals