Lecture 5:
Arrays
CS 136: Spring 2024
Katie Keith
Quiz 1 next Friday (February 28), last 25 minutes of lecture
Learning Goals:
📣 Announcements
Quiz 1 next Friday (February 28), last 25 minutes of lecture
Logistics:
📣 Announcements
🎯 Today’s Learning Objectives
📚Readings
Review: Classes versus objects
A static method belongs to the class itself.
Example:
convertMGP()
An instance method is attached to a particular object.
Example:
getColor()
Fig Credit: Dan Barowy
A class is not the same thing as an object. A class is a “blueprint for making objects.” We make an instance of a class (an object).
Overloading constructors
The term overloading means that we can have more than one constructor to specify different ways than an object of our class can be instantiated.
public Car(String make, String model, String color_input, double horsePower)
public Car(String color)
Car car1 = new Car("blue");
Car car2 = new Car("Mercedes-Benz", "420", "blue", 201.0);
Java knows which constructor method to use by matching the number, types, and order of parameters we pass into the constructor.
Constructor 1
Constructor 2
Creating objects using either Constructor 1 or Constructor 2
Getting instance variables
If an instance variable has a public access modifier we can obtain its value via the dot operator called on the object’s variable name
If an instance variable has a private access modifier, we cannot access it via the dot operator, and instead need to write a getter instance method.
String carColor = car2.color;
private String vinNumber;
public String getVIN(){
return this.vinNumber;
}
Enforces encapsulation
(important for security/privacy).
The private access modifier means the variable/method is not accessible by other classes.
System.out.println(car1.isBlackWhite);
Setting instance variables
If an instance variable has a public access modifier, we can set it with the assignment operator (=);
If an instance variable has a private access modifier, we need to write a setter instance method.
Car car1 = newCar();
car1.color = "blue";
public String color = “red”;
Declaring and initializing and instance variable
Setting an instance variable
public void setVIN(String newVin){
this.vinNumber = newVin;
}
private int vinNumber =1234;
Declaring and initializing and instance variable
Setting an instance variable
Review: Passing References
459
3
‘c’
‘a’
‘t’
String a = new String(“cat”);
String b = a;
a
459
460
461
462
459
b
When a reference-type variable is aliased or passed as an argument to a method, the reference is copied (not the values of the data).
Why? Large objects consume a lot of memory. Inefficient to copy or move all of its data every time.
Aliasing objects
public static void blah(String b){};
String a = new String(“cat”);
blah(a);
Object passed into a method
public class RacingCar{
public double horsePower;
public String make;
public RacingCar(double hp, String make){
this.horsePower = hp;
this.make = make;
}
public static void swap(RacingCar leftCar, RacingCar rightCar){
RacingCar temp = leftCar;
leftCar = rightCar;
rightCar = temp;
temp.make = "honda";
}
public static void main(String[] args){
RacingCar car1 = new RacingCar(1605.0, "ford");
RacingCar car2 = new RacingCar(1500.0, "ferrari");
swap(car1, car2);
System.out.println(car1.horsePower+" "+car1.make);
}
}
What is printed?
💡Think-pair-share
public class RacingCar{
public double horsePower;
public String make;
public RacingCar(double hp, String make){
this.horsePower = hp;
this.make = make;
}
public static void swap(RacingCar leftCar, RacingCar rightCar){
RacingCar temp = leftCar;
leftCar = rightCar;
rightCar = temp;
temp.make = "honda";
}
public static void main(String[] args){
RacingCar car1 = new RacingCar(1605.0, "ford");
RacingCar car2 = new RacingCar(1500.0, "ferrari");
swap(car1, car2);
System.out.println(car1.horsePower+" "+car1.make);
}
}
What is printed?
Answer
Answer:
“1605 honda”
💡Think-pair-share
RacingCar.java
💻
✅
🎯 Today’s Learning Objectives
Basic building blocks for programming
primitive data types
assignment statements
Java’s built-in
input /output
conditionals and loops
arrays
objects
Any program you might want to write
Arrays are helpful to process many values of same type
Making arrays
Making arrays in Java requires three steps:
double[] a;
a = new double[10];
for (int i = 0; i < 10; i++){
a[i] = 0.0;
}
We’re using new because an Array is a reference type
All elements in an array are the same type (here, a double)
We specify up-front the fixed number of elements in the array
The square brackets allow us to access the ith element of a.
Remember: We start at index 0.
1.
2.
3.
1.
2.
3.
Typical bugs with Arrays
Typical bugs with Arrays
The variable a is null until we use create it with:
a = new double[10];
Typical bugs with Arrays
Task: Create a deck of cards
Initializing arrays
When we have a small number of literal values that we want to keep in array, we can initialize it by listing the values between curly braces, separated by a comma.
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
String[] suits;
suits = new String[4];
suits[0] = "Clubs";
suits[1] = "Diamonds";
suits[2] = "Hearts";
suits[3] = "Spades";
Equivalent
Mutability of arrays
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
Declare and initialize an array of Strings
suits[1] = "New Suit";
Change the element at index 1
Note: New elements must match data type we declared the array elements to be (here, String)
Length of an array
We call the number of elements in the array the length of an array.
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
System.out.println(suits.length); // prints 4
Here, .length is an instance variable of the object suits
Printing out an array
import java.util.Arrays;
…
double[] a = {1.0, 2.0, 3.0, 4.0};
System.out.println(Arrays.toString(a));
// prints [1.0, 2.0, 3.0, 4.0]
We are importing an official Java class called Arrays. See documentation here.
A static method from the Arrays class that takes an array object as an input and returns a string
We must have the import statement in order for this line to work.
double[] a = {1.0, 2.0, 3.0, 4.0};
int n = a.length;
for (int i = 0; i < n/2; i++){
int temp = a[n-i-1];
a[n-i-1] = a[i];
a[i] = temp;
}
System.out.println(Arrays.toString(a));
💡Think-pair-share
double[] a = {1.0, 2.0, 3.0, 4.0};
int n = a.length;
for (int i = 0; i < n/2; i++){
int temp = a[n-i-1];
a[n-i-1] = a[i];
a[i] = temp;
}
System.out.println(Arrays.toString(a));
Answer
double temp
Answer:
💡Think-pair-share
✅
✅
🎯 Today’s Learning Objectives