1 of 28

Lecture 5:

Arrays

CS 136: Spring 2024

Katie Keith

2 of 28

Quiz 1 next Friday (February 28), last 25 minutes of lecture

Learning Goals:

  • Check-in about your computational problem solving and grasp of Java syntax
  • Practice “pen-and-paper” computer science before midterm exam.
  • Why “pen-and-paper”? Helps me assess what you know, and emulates the “white board interview” still used by most companies in industry

📣 Announcements

3 of 28

Quiz 1 next Friday (February 28), last 25 minutes of lecture

Logistics:

  • Covers Lab 0 and Lab 1 and all lecture material through (and including) today (Friday, Feb 21)
  • You’ll be given a problem, you will write Java code to solve the problem
  • Katie’s exams emphasize problem-solving not memorization. All quizzes and exams you’re allowed one 8.5x11 hand-written reference sheet (front and back)
  • Study tip: Form study groups, give each other problems to solve on whiteboard/chalkboard (online textbook; Leet code, AI all good sources for problems)
  • Accommodations: Talk to me by the end of the day today

📣 Announcements

4 of 28

  • Wrap-up Reference-Type Foundations:
    • Getters/Setters
    • Overloaded constructors
  • Arrays

🎯 Today’s Learning Objectives

5 of 28

📚Readings

  • Sedgewick & Wayne. CS:IA. Section 1.4.
  • Oracle Java Tutorials. Packages.

6 of 28

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).

7 of 28

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

8 of 28

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);

9 of 28

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

10 of 28

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

11 of 28

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

12 of 28

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

13 of 28

RacingCar.java

💻

14 of 28

  • Wrap-up Reference-Type Foundations:
    • Getters/Setters
    • Overloaded constructors
  • Arrays

🎯 Today’s Learning Objectives

15 of 28

Basic building blocks for programming

primitive data types

assignment statements

Java’s built-in

Math library

input /output

conditionals and loops

arrays

objects

Any program you might want to write

16 of 28

Arrays are helpful to process many values of same type

17 of 28

Making arrays

Making arrays in Java requires three steps:

  1. Declare the array name and type
  2. Create the array
  3. Initialize the array values

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.

18 of 28

Typical bugs with Arrays

19 of 28

Typical bugs with Arrays

The variable a is null until we use create it with:

a = new double[10];

20 of 28

Typical bugs with Arrays

21 of 28

Task: Create a deck of cards

22 of 28

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

23 of 28

Mutability of arrays

  • A mutable variable is one whose internal state can be changed after it is created, whereas an immutable variable’s state cannot be changed after creation.
  • For arrays, the size the the array is immutable but the individual elements of an array are mutable.

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)

24 of 28

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

25 of 28

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.

26 of 28

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));

  1. What is this chunk of code attempting to do?
  2. There’s syntax bug in one line of this code. What is it and how do we fix it?
  3. Once the bug is fixed, what will it print?

💡Think-pair-share

27 of 28

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));

  • What is this chunk of code attempting to do?
  • There’s syntax bug in one line of this code. What is it and how do we fix it?
  • Once the bug is fixed, what will it print?

Answer

double temp

Answer:

  1. Reverse the elements in an array.
  2. double (not int)
  3. [4.0, 3.0, 2.0, 1.0]

💡Think-pair-share

28 of 28

  • Wrap-up Reference-Type Foundations:
    • Getters/Setters
    • Overloaded constructors
  • Arrays

🎯 Today’s Learning Objectives