Part 1:
Java as an Object-oriented
Programming Language
Arrays
Array basics
2
Data Structures
Sometimes, we have data that have some
natural structure to them
A few examples:
Texts are sequences of characters
Images are matrices of pixels
Classes contain sets of students
Java provides a variety of classes and tools
called data structures
They help organize your data
They make it convenient to access and update your
data
Data Structures
Some common data structure classes in Java
Array/Arrays (the data structure we will cover)
ArrayList
HashSet
LinkedHashSet
LinkedList
TreeSet
Vector
HashMap
Arrays
array: An object that stores many values of the
same type.
element: a value in an array
index: an integer indicating the position of a value in an
array
index 0 1 2 3 4 5 6 7 8 9
value 12 49 -2 26 5 17 -6 84 72 3
element 0 element 4 element 9
5
Array declaration
Declaring/initializing an array:
<type>[] <name> = new <type>[<length>];
Example:
int[] numbers = new int[10];
index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 0
The length can be any integer expression:
int x = 2 * 3 + 1;
int[] data = new int[x % 5 + 2];
6
Array auto-initialization
When arrays are initially constructed, every element
is automatically initialized to a "zero-equivalent"
value.
int: 0
double: 0.0
boolean: false
object type: null (null means "no object")
7
Array auto-initialization: Example
An array of doubles
index 0 1 2 3 4
value 0.0 0.0 0.0 0.0 0.0
An array of booleans
index 0 1 2 3
value false false false false
8
Don't go out of bounds!
Reading or writing any index outside the valid range
will throw an ArrayIndexOutOfBoundsException.
Example:
int[] data = new int[10];
System.out.println(data[0]); // okay
System.out.println(data[-1]); //
exception!
System.out.println(data[9]); // okay
System.out.println(data[10]); //
exception!
index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 9
0
The length field
An array's length field stores its number of
elements.
General syntax:
<array name>.length
NB: Because it's a field (i.e. not a method), it does
not use parentheses like a String's .length()!
10
Array initialization statement
Quick array initialization, general syntax:
<type>[] <name> = {<value>, <value>, ..., <value>};
Example:
int[] numbers = { 12, 49, -2, 26, 5, 17, -6 };
index 0 1 2 3 4 5 6
value 12 49 -2 26 5 17 -6
Useful when you know in advance what the array's
11
element values will be.
Printing arrays: Arrays.toString
Arrays.toString accepts an array as a
parameter and returns the String representation,
which you can then print.
Example:
int[] a = { 2, 5, 1, 6, 14, 7, 9 };
for (int i = 1; i < a.length; i++) {
a[i] += a[i - 1];
}
System.out.println("a is " + Arrays.toString(a));
Output:
a is [2, 7, 8, 14, 28, 35, 44]
12
Enum
Use Enum to create a data type that has a set of
possible discrete values
Example:
public enum Monster{ZOMBIE, VAMPIRE, DEMON,
WEREWOLF};
Enum names are capitalized because an enum defines a
type, not a variable
Values are in all-caps because they are constants; each
instance of the enum has one of these constant values
Enum
Define a variable of an enum type:
Monster m = Monster.ZOMBIE;
Test whether a variable has a particular value:
if(m == Monster.ZOMBIE)
System.out.println(“Zombie approaching!”);
Use as method parameter:
myMethod(Monster m){}
Send as argument:
myMethod(Monster.ZOMBIE);
Multi-dimensional
arrays
15
How can we store a table of values?
Let’s say there’s a class of 8 students,
with 10 quiz grades each:
7.5 4.5 9.5 2 7 8.5 1 8.5 7.5 6
… … … … … … … … … …
… … … … … … … … … …
… … … … … … … … … …
… … … … … … … … … …
… … … … … … … … … …
… … … … … … … … … …
4.5 2 9 9 5.5 4 7.5 6 5 9
How can we declare variables to store all this data?
16
Solution 1: An array per student
double [] student1 = new double[10];
...
double [] student8 = new double[10];
student1: 7.5 4.5 9.5 2 7 8.5 1 8.5 7.5 6
...
student8: 4.5 2 9 9 5.5 4 7.5 6 5 9
Tedious!
17
Ragged 2-D arrays
double [][] quizScores = new double[4][];
quizScores[0] = new double[3];
quizScores[2] = new double[5];
quizScores
quizScores[0]
quizScores[1]
quizScores[2]
quizScores[3]
Text processing
19
Text processing
text processing: Examining, editing, formatting text.
Text processing often involves for loops that examine the
characters of a string one by one.
Two data types involved
char String
Represents individual characters Represents sequences of characters
Primitive type Object type (i.e., not primitive)
Written with single quotes Written with double quotes
e.g.: e.g.:
‘T’ “We the people”
‘t’ “1. Twas brillig, and the slithy toves\n”
‘3’ “”
‘%’ “T”
‘\n’
20
Characters
char: A primitive type representing single characters.
Individual characters inside a String are stored as char
values.
Literal char values are surrounded with apostrophe
(single-quote) marks, such as 'a' or '4' or '\n' or '\''
Like any other type, you can create variables, parameters,
and returns of type char.
char letter = 'S';
System.out.println(letter); // prints S
21
Strings
String: an object type for representing sequences of characters
Sequence can be of length 0, 1, or longer
Each element of the sequence is a char
We write strings surrounded in double-quotes
We can declare, initialize, assign, and use String variables in
expressions just like other data types
String s = “Hello, world\n”; // declare, init
System.out.println(s); // use value
s = s + “I am your master\n”; // concatenate
// and assign
String Methods
Unlike primitive types, object types can have methods.
Here is a list of methods for strings:
Method name Description
charAt(index) returns the character at the given index
indexOf(str) returns the index where the start of the given
string appears in this string (-1 if not found)
length() returns the number of characters in this string
substring(index1,index2) returns the characters in this string from
index1 up to, but not including, index2
toLowerCase() returns a new string with all lowercase letters
toUpperCase() returns a new string with all uppercase letters
23
The charAt method
The characters of a string can be accessed using the
String object's charAt method.
String indices start at 0.
Starts at 0!
String word = “cola”;
charAt(i): ‘c’ ‘o’ ‘l’ ‘a’
Index i: 0 1 2 3
char firstLetter = word.charAt(0);
if (firstLetter == 'c') {
System.out.println("C is for cookie!");
}
24
Calling string methods
Let s be a variable of type String
General syntax for calling a String method:
s.<method>(<args>)
Some examples:
String s = “Cola”;
int len = s.length(); // len == 4
char firstLetter = s.charAt(0); // ‘C’
int index = s.indexOf(“ol”); // index == 1
String sub = s.substring(1,3); // “ol”
String up = s.toUpperCase(); // “COLA”
String down = s.toLowerCase(); // “cola”
Fun with char!
char values can be concatenated with strings.
char initial = 'P';
System.out.println(initial + ". Diddy");
You can compare char values with relational operators.
'a' < 'b' and 'Q' != 'q'
Caution: You should NOT use these operators on a String!
Example:
// print the alphabet
for (char c = 'a'; c <= 'z'; c++) {
System.out.print(c);
}
26
char vs. String
'h' is a char
char c = 'h';
char values are primitive; you cannot call methods on them
can't say c.length() or c.toUpperCase()
"h" is a String
String s = "h";
Strings are objects; they contain methods that can be called
can say s.length() 1
can say s.toUpperCase() "H"
can say s.charAt(0) 'h'
27
Comparing strings
Objects (such as String) should be compared for equality
by calling a method named equals.
Example:
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
if (name.equals("Barney")) {
System.out.println("I love you, you love
me,");
System.out.println("We're a happy family!");
}
28
Comparing strings
There are more methods of a String object that can be
used in <test> conditions.
Method Description
equals(str) whether this string contains exactly the
same characters as the other string
equalsIgnoreCase(str) whether this string contains the same
characters as the other, ignoring upper-
vs. lowercase differences
startsWith(str) whether this string’s beginning matches
the argument
endsWith(str) whether this string’s end matches the
argument
29
Comparing strings: Examples
Hypothetical examples, assuming the existence of various
String variables:
if (title.endsWith("M.D.")) {
System.out.println("What's your number?");
}
if (fullName.startsWith("Giorgio")) {
System.out.println("When are you retiring?");
}
if (lastName.equalsIgnoreCase("lumBerg")) {
System.out.println("I need your TPS reports!");
}
if (name.toLowerCase().indexOf("sr.") >= 0) {
System.out.println("You must be old!");
}
30
What about String typecasts?
The (String) typecasts don’t work with primitive types, like
char, int, and double.
However, there are easy ways to convert to and from
strings:
Converting from strings:
String s to int: Integer.parseInt(x)
String s to double:
Double.parseDouble(x) …
String s to char: Character.parseChar(x)
Reading in Strings
Remember the Scanner method called nextInt()?
You can also use Scanners to read in Strings with the
next() and hasNext() methods.
Example:
Please enter your name: Alexander Pieter
Yates
Name 1 has 9 letters
Name 2 has 6 letters
Name 3 has 5 letters
Solution
import java.util.Scanner;
public class NameLength {
public static void main(String [] args) {
Scanner scan = new Scanner(System.in);
System.out.print(“Please enter your name”);
int i=1;
while(scan.hasNext()) {
String s = scan.next();
int length = s.length();
System.out.println(“Name “ + i + “ has “ +
length + “ letters”);
i++;
}
}
}
Scanner class (so far)
return method Description
int nextInt() Reads the next token, converts it to an int (if
possible), and returns the int value.
double nextDouble() Reads the next token, converts it to a double (if
possible), and returns the double value.
String next() Reads the next token, and returns it.
boolean hasNext() Returns true if there are more tokens.
StringBuilder
The StringBuilder class is a supplement to the
String class.
StringBuilder is more flexible than String. You can add,
insert, or append new contents into a string buffer,
whereas the value of a String object is fixed once the
string is created.
You will often have to parse the StringBuilder to a String
when you are done constructing it.
35
StringBuilder Constructors
java.lang.StringBuilder
+StringBuilder() Constructs an empty string builder with capacity 16.
+StringBuilder(capacity: int) Constructs a string builder with the specified capacity.
+StringBuilder(s: String) Constructs a string builder with the specified string.
36
Modifying Strings in the Builder
java.lang.StringBuilder
+append(data: char[]): StringBuilder Appends a char array into this string builder.
+append(data: char[], offset: int, len: int): Appends a subarray in data into this string builder.
StringBuilder
+append(v: aPrimitiveType): StringBuilder Appends a primitive type value as a string to this
builder.
+append(s: String): StringBuilder Appends a string to this string builder.
+delete(startIndex: int, endIndex: int): Deletes characters from startIndex to endIndex.
StringBuilder
+deleteCharAt(index: int): StringBuilder Deletes a character at the specified index.
+insert(index: int, data: char[], offset: int, Inserts a subarray of the data in the array to the builder
len: int): StringBuilder at the specified index.
+insert(offset: int, data: char[]): Inserts data into this builder at the position offset.
StringBuilder
+insert(offset: int, b: aPrimitiveType): Inserts a value converted to a string into this builder.
StringBuilder
+insert(offset: int, s: String): StringBuilder Inserts a string into this builder at the position offset.
+replace(startIndex: int, endIndex: int, s: Replaces the characters in this builder from startIndex
String): StringBuilder to endIndex with the specified string.
+reverse(): StringBuilder Reverses the characters in the builder.
+setCharAt(index: int, ch: char): void Sets a new character at the specified index in this
37
builder.
The toString, capacity, length, setLength, and charAt
Methods
java.lang.StringBuilder
+toString(): String Returns a string object from the string builder.
+capacity(): int Returns the capacity of this string builder.
+charAt(index: int): char Returns the character at the specified index.
+length(): int Returns the number of characters in this builder.
+setLength(newLength: int): void Sets a new length in this builder.
+substring(startIndex: int): String Returns a substring starting at startIndex.
+substring(startIndex: int, endIndex: int): Returns a substring from startIndex to endIndex-1.
String
+trimToSize(): void Reduces the storage size used for the string builder.
38
Examples
stringBuilder.append("Java");
stringBuilder.insert(11, "HTML and ");
stringBuilder.delete(8, 11) changes the builder to Welcome Java.
stringBuilder.deleteCharAt(8) changes the builder to Welcome o Java.
stringBuilder.reverse() changes the builder to avaJ ot emocleW.
stringBuilder.replace(11, 15, "HTML")
changes the builder to Welcome to HTML.
stringBuilder.setCharAt(0, 'w') sets the builder to welcome to Java.
39
StringTokenizer
boolean hasMoreTokens()
String nextToken()
String nextToken(String delim)
StringTokenizer
+countTokens(): int
+hasMoreTokens():boolean
+nextToken(): String
+nextToken(delim: String): String
14/10/2019 40