SWEN20003 Object Oriented Software Development 0.5 cm Arrays and Strings
SWEN20003
Object Oriented Software Development
Arrays and Strings
Shanika Karunasekera
.au
University of Melbourne
c© University of Melbourne 2020
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 1 / 42
The Road So Far
OOP Foundations
I A Quick Tour of Java
I Classes and Objects
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 2 / 42
Lecture Objectives
After this lecture you will be able to:
Understand how to use Arrays
Understand how to use Strings
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 3 / 42
Arrays
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 4 / 42
Motivation
Store a single integer value
int x;
Store two integer values
int x1, x2;
Store n integer values
int[] intArray;
Keyword
Array: A sequence of elements of the same type arranged in order in
memory
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 5 / 42
Array Declaration
basetype[] varName; OR \\
basetype varName[];
Declares an array ([])
Each element is of type basetype
int[] intArray;
How many elements does this array have?
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 6 / 42
Pitfall: Array Declaration
int[] intArray;
int x = intArray[0];
Program.java:13: error: variable intArray might not have been initialized
Arrays must be initialised, just like any other variable
Let’s look at how
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 7 / 42
Array Initialization and Assignment
int[] intArray_1 = {0, 1, 2, 3, 4};
How many elements?
What are their values?
int[] intArray_2 = new int[100];
How many elements?
What are their values?
int[] intArray_1 = new int[n];
int[] intArray_2 = intArray_1;
How many elements?
What are their values?
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 8 / 42
Assess Yourself
int[] intArray_1 = {10, 20, 30, 40};
int[] intArray_2 = intArray_1;
System.out.println(intArray_2[0]);
intArray_1[0] = 15;
System.out.println(intArray_2[0]);
Program Output:
10
15
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 9 / 42
Pitfall: Array Assignment
Array is a data type, similar to data types you create by defining
Arrays are references!
Manipulating one reference affects all references
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 10 / 42
Assess Yourself
Write a Java static method, computeDoublePowers, that accepts an
integer n, and returns an array of doubles of that size. Your method
should then fill that array with increasing powers of two (starting from
1.0).
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 11 / 42
Assess Yourself
public static double[] computeDoublePowers(int n) {
double[] nums = new double[n];
for (int i = 0; i < n; i++) {
nums[i] = Math.pow(2, i);
}
// For sanity checking
for (int i = 0; i < n; i++) {
System.out.println(nums[i]);
}
return nums;
}
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 12 / 42
Multi-Dimensional Arrays
Java permits “multi-dimensional” arrays
Technically exist as “array of arrays”
Declared just like 1D arrays
int[][] nums = new int[10][10]; // Square array
int[][] nums = new int[10][]; // Irregular array
Initialising 2D arrays slightly more complicated
for (int i = 0; i < nums.length; i++) {
nums[i] = new int[
}
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 13 / 42
Assess Yourself
Write a program that can generate the following 2D array:
Can you write your program with as few assumptions as possible?
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 14 / 42
Assess Yourself
public class Main {
public static void main(String[] args) {
int HEIGHT = 5;
int MAX_WIDTH = HEIGHT;
int[][] triangleArray= new int[HEIGHT][];
for (int i = 0; i < HEIGHT; i++) {
triangleArray[i] = new int[HEIGHT - i];
for (int j = 0; j < HEIGHT - i; j++) {
triangleArray[i][j] = i + j + 1;
}
}
}
}
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 15 / 42
Arrays of Objects
Arrays can be used to store objects.
Follow the steps below to create and store objects.
Declaration of the array:
Circle[] circleArray;
Allocation of Storage:
circleArray = new Circle[25];
I The above statement created an array that can store references to 25
Circle objects.
I Circle objects are not created, you have to create them and store them
in the array - see next example.
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 16 / 42
Arrays of Objects - Example
// CircleArray.java
class CircleArray{
public static void main (String[] args){
//declare an array for Circles
Circle[] circleArray = new Circle[3];
// create circle objects and store in array
for ( int i = 0; i < circleArray.length; i++) {
circleArray[i] = new Circle(i,i, i + 2);
}
for ( int i = 0; i < circleArray.length; i++) {
System.out.println("Circle " + i + " Radius = " +
circleArray[i].getR());
}
}
}
Program Output:
Circle 0 Radius = 2.0
Circle 1 Radius = 3.0
Circle 2 Radius = 4.0
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 17 / 42
Array Methods
Indexing
int[] intArray = new int[10];
int x = intArray[0];
int x = intArray[10];// Gives out of bounds error
int x = intArray[-1];// Gives out of bounds error
Length
int len = intArray.length
Equality
import java.util.Arrays;
int[] n1 = {1, 2, 3};
int[] n2 = {1, 2, 3};
Arrays.equals(n1, n2);
//true if the element values are the same, false otherwise
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 18 / 42
Array Methods
Resizing - arrays are fixed length; resizing requires creating a new
array.
int[] intArray = new int[5];
intArray = new int[intArray.length + 3];
Sorting (“ascending”)
Arrays.sort(n1);
Printing
System.out.println(Arrays.toString(n1));
Output:
[1, 2, 3]
Full Array documentation here
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 19 / 42
https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html
For Each Loop
for (
}
More convenient method of iteration
No indexing required
Useful when operating with/on the data, and not the array
for (Circle c : circleArray) {
System.out.println(c.getRadius());
}
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 20 / 42
Strings
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 21 / 42
Strings
You have already seen Strings in use:
public static void main(String[] args) {… }
final String STRING_CONSTANT = “Welcome to Java”;
public String toString() {….}
System.out.println(“arg[” + i + “]: ” + args[i]);
But what is a String?
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 22 / 42
Assess Yourself
A “String” is a(n) what?
1 Object (not technically correct)
2 Class
3 Variable
4 Data Type
5 Method
6 Privacy Modifier
7 I have literally no clue
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 23 / 42
Strings
Strings store sequences of characters
String is a Java class
Used to represent messages, errors, and “character” related attributes
like name
Incredibly powerful for input and output
Keyword
String: A Java class made up of a sequence of characters.
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 24 / 42
Strings
Some examples of String variables
String s1 = “This is a String”;
String s2 = “This is ” + “also a String”;
String s3 = “10”;
String s4 = “s3 is still a string, even though it’s a number”;
Java Strings are almost identical to Python, except you can’t use single
quotes.
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 25 / 42
Assess Yourself
What does this code output?
System.out.println(“Game of Thrones season 8 was “good”.”);
1 “Game of Thrones season 8 was “good”.”
2 Game of Thrones season 8 was “good”.
3 Game of Thrones season 8 was good.
4 Error
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 26 / 42
Special Characters
Some characters (like ”) are “reserved”
Mean something special to Java
Need to “escape” them with “\” to use alternate meaning
Examples “\n” (newline), “\t” (tab) “\”” (quotation)
System.out.println(“Game of Thrones season 8 was \”good\”.”);
Keyword
Escaping: To include “special” characters in a string, use “\” to escape
from that character’s normal meaning.
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 27 / 42
String Operations
You can use + (and +=) to append/concatenate two strings
I System.out.println(“Hello ” + “World”);
I Prints “Hello World”
+ is clever: if either operand is a string, it will turn the other into a
string
I System.out.println(“a = ” + a + “, b = ” + b);
I If a = 1 and b = 2, this prints: “a = 1, b = 2”
Why is this useful?
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 28 / 42
Assess Yourself
System.out.println(“1 + 1 = ” + 1 + 1);
Actually prints “1 + 1 = 11”
System.out.println(“1 + 1 = ” + (1 + 1));
Prints “1 + 1 = 2”
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 29 / 42
Assess Yourself
Name some “logical” things you might do with a String
Think about how you would do them in C and Python
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 30 / 42
String Methods
Length
I C: Need a helper/buddy variable
I Python: len(“Hello”)
I Java: “Hello”.length()
Upper/Lower case
I C: toupper(*s)
I Python: s.upper()
I Java: s.toUpperCase()
Split
I C: Stop
I Python: s.split()
I Java: s.split(” “)
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 31 / 42
String Methods
Check substring presence
I C: Why
I Python: “Hell” in s
I Java: s.contains(“Hell”)
Find substring location
I C: Never mind
I Python: s.find(“Hell”)
I Java: s.indexOf(“Hell”)
Substring
I C: I’m out
I Python: s[2:7]
I Java: s.substring(2, 7)
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 32 / 42
String Methods
The full String class documentation can be found here.
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 33 / 42
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
Assess Yourself
What does this output?
String s = “Hello World”;
s.toUpperCase();
s.replace(“e”, “i”);
s.substring(0, 2);
s += ” FIVE”;
System.out.println(s);
“Hello World FIVE”
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 34 / 42
Immutability
Strings are immutable; once created, they can’t be modified, only
replaced
This means that every String operation returns a new String
We’ll look at immutability in more detail soon…
Let’s fix up that code
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 35 / 42
Assess Yourself
What does this output?
String s = “Hello World”;
s = s.toUpperCase();
s = s.replace(“e”, “i”);
s = s.substring(0, 2);
s += ” FIVE”;
System.out.println(s);
“HE FIVE”
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 36 / 42
Assess Yourself
What does this output?
System.out.println(“Hello” == “Hello”);
true
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 37 / 42
Assess Yourself
What does this output?
String s = “Hello”;
System.out.println(s == “Hello”);
true
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 38 / 42
Assess Yourself
What does this output?
String s = “Hello”;
String s2 = “Hello”;
System.out.println(s == s2);
true
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 39 / 42
Assess Yourself
What does this output?
String s = “Hello”;
String s2 = new String(“Hello”);
System.out.println(s == s2);
false
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 40 / 42
Equality
In the previous example s and s2 are references to objects.
To check equality between two objects we must use the equals
method.
I Remember the equals method from our previous topic – a standard
method every class should have
String s = “Hello”;
String s2 = new String(“Hello”);
System.out.println(s.equals(s2));
true
Keyword
.equals: A method used to check two objects for equality
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 41 / 42
Lecture Objectives
Upon completion of this topic you will be able to:
Use Arrays
Use Strings
Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 42 / 42