0% found this document useful (0 votes)
3 views

s4-Java

This document covers programming concepts including Boolean expressions, if/else statements, arrays, and loops in Java. It explains how to declare and initialize arrays, access their elements, and iterate through them using for loops. Additionally, it introduces object-oriented programming principles, focusing on classes, instances, and their properties and behaviors.

Uploaded by

osamahmdy001
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

s4-Java

This document covers programming concepts including Boolean expressions, if/else statements, arrays, and loops in Java. It explains how to declare and initialize arrays, access their elements, and iterate through them using for loops. Additionally, it introduces object-oriented programming principles, focusing on classes, instances, and their properties and behaviors.

Uploaded by

osamahmdy001
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 90

02/22/2025 1

Managing Multiple Items


Objectives

• After completing this lesson, you should be able to:


• Explain what a Boolean expression is
• Create a simple if/else statement
• Describe the purpose of an array
• Declare and initialize a String or int array
• Access the elements of an array
• Explain the purpose of a for loop
• Iterate through a String array using a for loop
Topics
• Working with conditions
• Working with an array of items
• Processing an array of items
Making Decisions

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

A Boolean expression is a combination of variables, values, and operators


that evaluate to true or false.
• length > 10;
• size <= maxSize;
• total == (cost * price);

Relational operators
Relational Operators

Condition Operator Example

Is equal to == int i=1;


(i == 1)
Is not equal to != int i=2;
(i != 1)
Is less than < int i=0;
(i < 1)
Is less than or equal <= int i=1;
to (i <= 1)
Is greater than > int i=2;
(i > 1)
Is greater than or >= int i=1;
equal to (i >= 1)
Examples
Sometimes there is a quicker way to meet your objective. Boolean expressions
can be used in many ways.

24 int attendees = 4;
25 boolean largeVenue;
26
27 // if statement example
28 if (attendees >= 5){
29 largeVenue = true;
30 } Assign a boolean
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

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


• Declare a boolean, outOfStock.
• if quantity > 1
• Change the message variable to indicate plural
• if/else:
• if item is out of stock:
• Inform the user that the item is unavailable
• else
• Print the message
• Print the total cost
Quiz
What is the purpose of the else block in an if/else statement?
a. To contain the remainder of the code for a method
b. To contain code that is executed when the expression in an if statement is
false
c. To test if an expression is false
Topics
• Working with conditions
• Working with an array of items
• Processing an array of items
What If There Are Multiple Items
in the Shopping Cart?

• 01 // Without an array Not realistic if


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

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


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

0 1 2 3

27 12 82 70
Array Examples

Array of int types


27 12 82 70 54 1 30 34

Array of String types

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

The ages array has eight elements.

First Element
index at index 5

00 1 2 3 4 5 6 7 Indices

27 12 82 70 54 1
1 30 34

Array length is 8.
(ages.length)
Declaring and Initializing an Array

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

• Declare arrays of types String and int:


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

All in
one
line
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

• Get values from the ages array:


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

int myAge = ages[0];


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

• Set values from the names array:


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

names[0] = "Gary";
names[1] = "Rob";
Exercise 5-2: Using an Array

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


names. Then you experiment with accessing the array:
• Declare a String array, names, and initialize it with four String values.
• Print the number of items the customer wants to buy.
• Print one of the array elements.
Quiz
• Why does the following code not compile? Select all that apply.
• int[] lengths = {2, 4, 3.5, 0,
40.04};
a. lengths cannot be used as an array identifier.
b. All of the element values should have the same format (all using double
values, or all using int values).
c. The array was declared to hold int values. double values are not allowed.
Quiz
• Given the following array declaration, which of the following statements
are true?
• int[] classSize = {5, 8, 0, 14, 194};
a. classSize[0] is the reference to the first element in the array.
b. classSize[5] is the reference to the last element in the array.
c. There are 5 integers in the classSize array.
d. classSize.length = 5
Topics
• Working with conditions
• Working with an array of items
• Processing an array of items
Loops
Loops are used in programs to repeat blocks of statements
• Until an expression is false
or
• For a specific number of times:
– I want to print each element of an array.
– I want to print each element of an ArrayList. (The ArrayList class is
covered in the lesson titled “Working with Arrays, Loops, and Dates.”
Processing a String Array
Loop accesses
each element in names array of String types
turn.
George Jill Xinyi Ravi

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

• In this exercise, you loop through an array called itemPrices to print


a message indicating each item price.
Quiz
Given the following code,
int[] sizes = {4, 18, 5, 20};
for (int size : sizes){
if (size > 16){break;}
System.out.println("Size: "+size + ", ");
}
which option below shows the correct output?
a. Size: 4,
b. Size: 4
c. Size: 4,
• Size: 5,
d. There is no output.
Summary

In this lesson, you should have learned how to:


• Use a Boolean expression
• Create a simple if/else block
• Describe the purpose of an array
• Declare and initialize a String or int array
• Access the elements of an array
• Explain the purpose of a for loop
• Iterate through a String Array using a for loop
Play Time!
s ic . 05 is m os t
Ba
im portant.
Play Basic Puzzles 1 through 5 before the lesson titled “Describing Objects
and Classes.”
Your Goal: Design a solution that deflects the ball to Duke.
Consider the following:
What happens when you put a triangle wall or simple wall icon on the blue wheel?
About Java Puzzle Ball
• It is used throughout the course.
• Play a set of puzzles.
• Become familiar with the game mechanics.
• Consider a question as you play.
• The lesson titled “Describing Objects and Classes” debriefs on what you
have observed.
• Apply your observations to understand Java concepts.
Tips
• You must have Java 8 installed to run the game.
• The game may perform better on your personal machine.

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?

Consider the following:


What happens when you put a triangle wall or simple wall icon on the blue wheel?
Java Puzzle Ball Debrief
What happens when you put a triangle wall or simple wall icon on a blue
wheel?
• A wall appears on every instance of a blue bumper object.
• Walls give bumpers behaviors that deflect and interact with the ball.
• All blue bumper instances share these same behaviors.

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

1 public class Customer {


2 public String name = "Junior Duke";
Fields
3 public int custID = 1205;
(Properties)
4 public String address; (Attributes)
5 public int orderNum;
6 public int age;
7
8 public void displayCustomer(){ Methods
9 System.out.println("Customer: "+name); (Behaviors)
10 }
11 }
Modeling Properties and Behaviors

Customer class Class name


name
address
billing info Fields
age
customer number
order number

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

public static void main(String[] args){

Customer customer01 = new Customer();


Create new
Customer customer02 = new Customer();
instances
customer01.age = 40; (instantiate).
customer02.name = "Duke"; Fields are
accessed.
customer01.displayCustomer();
customer02.displayCustomer(); Methods are
} called.
}
Object Instances and Instantiation Syntax
variable becomes a
reference to that object.
The new keyword creates
The syntax is: (instantiates) a new
<class name> variable = new <classinstance.
name>()

public static void main(String[] args){

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

Customer customer02; //Declare the reference


customer02 = new Customer(); //Then instantiate

new Customer(); //Instantiation without a reference


//We can’t use this object later
//without knowing how to reference
it.
}
}
The Dot (.) Operator
Follow the reference variable with a dot operator (.) to access the fields
and methods of an object.

public static void main(String[] args){


Customer class
Customer customer01 = new Customer();
name
address //Accessing fields
billing info System.out.println(customer01.name);
age
customer01.age = 40;
customer number
order number
//Calling methods
requestDiscount() customer01.requestDiscount();
setAddress() customer01.displayCustomer();
shop() }
displayCustomer()
}
Objects with Another Object as a Property
Customer class Cart class

customer number Item[]


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

public static void main(String[] args){

Customer customer01 = new Customer();


customer01.cart.cancel(); //How to access methods of an
//object within another
object
}
Quiz
Which of the following lines of code instantiates a Boat object and
assigns it to a sailBoat object reference?
a. Boat sailBoat = new Boat();
b. Boat sailBoat;
c. Boat = new Boat()
d. Boat sailBoat = Boat();
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
Accessing Objects by Using a Reference

The camera is like the object that is


accessed using a reference.

The remote is like the reference


used to access the camera.
Working with Object References

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

12 Camera remote1 = new Camera();


13 There are two
14 Camera remote2 = new Camera(); Camera objects.
15
16 remote1.play();
17
18 remote2.play();
Working with Object References

There is only one


Camera object.
remote
2 12 Camera remote1 = new Camera();
13
14 Camera remote2 = remote1;
15
16 remote1.play();
17
remote 18 remote2.stop();
1
References to Different Objects

Television

Camcorder

Television
Camcorder remote
remote
References to Different Objects
Reference
type
Reference
variable
Create a new object.

6 Camera remote1 = new Camera();


7 remote1.menu();
8
9 TV remote2 = new TV();
10 remote2.menu();
11
12 Shirt myShirt = new Shirt();
13 myShirt.display();
14
15 Trousers myTrousers = new Trousers();
16 myTrousers.display();
References and Objects in Memory

12 int counter = 10;


13 Shirt myShirt = new Shirt();
14 Shirt yourShirt = new Shirt();

Stack 0x034009 Hea


12 shirtID p
15.99 price
B colorCode

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:

12 Shirt myShirt = new Shirt();


13 Shirt yourShirt = new Shirt();
14
15 myShirt = yourShirt; //The old myShirt object is
16 //no longer referenced
17 myShirt.colorCode = 'R';
18 yourShirt.colorCode = 'G';
19
20 System.out.println("Shirt color: “ + myShirt.colorCode);

Output from 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;

• Not permitted (compiler will show an error):

int [] ages;
ages = {19, 42, 92};
Storing Arrays in Memory

int age = 35;


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

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

Item item = new Item();


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

0 itemId
item 0x034009 0.0 price
U colorCode

items 0x99f311 0 itemId


0x99f311 price
0.0
0x00099 U colorCode
0x00327
0 itemId
0x00990
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 }

NetBeans output window


indicates a
This reference has NullPointerException.
not been
assigned.
Compiling and Running a Program by
Using NetBeans

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

You might also like