Chapter 3 Flashcards

1
Q

String concatenation

A
  1. If both operands are numeric, + means numeric addition.
  2. If either operand is a String, + means concatenation.
  3. The expression is evaluated left to right.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

System.out.println(1 + 2);
System.out.println(“a” + “b”);
System.out.println(“a” + “b” + 3);
System.out.println(1 + 2 + “c”);

A

// 3
// ab
// ab3
// 3c

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Mutable vs. Immutable

A

Mutable is another word for changeable. Immutable is the opposite—an object that can’t be changed once it’s created. On the OCA exam, you need to know that String is immutable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

The string pool

A

Also known as the intern pool, is a location in the Java virtual machine (JVM) that collects all these strings. Java realizes that many strings repeat in the program and solves this issue by reusing common ones.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Important String Methods:
length()

String string = “animals”;
System.out.println(string.length());

A

// 7

The method length() returns the number of characters in the String.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Important String Methods:
charAt()

String string = “animals”;

System.out.println(string.charAt(0));
System.out.println(string.charAt(6));
System.out.println(string.charAt(7));

A

// a

// s

// throws exception

The method charAt() lets you query the string to find out what character is at a specific index.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Important String Methods:
indexOf()

String string = “animals”;
System.out.println(string.indexOf(‘a’));
System.out.println(string.indexOf(“al”));
System.out.println(string.indexOf(‘a’, 4));
System.out.println(string.indexOf(“al”, 5));

A

// 0

// 4

// 4

// -1

The method indexOf()looks at the characters in the string and finds the first index that matches the desired value. indexOf can work with an individual character or a whole String as input. It can also start from a requested position. The method signatures are as follows:

int indexOf(char ch)
int indexOf(char ch, index fromIndex)
int indexOf(String str)
int indexOf(String str, index fromIndex)

Unlike charAt(), the indexOf() method doesn’t throw an exception if it can’t find a match. indexOf() returns –1 when no match is found.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Important String Methods:
substring()

String string = “animals”;
System.out.println(string.substring(3)); System.out.println(string.substring(string.indexOf(‘m’))); System.out.println(string.substring(3, 4));
System.out.println(string.substring(3, 7));
System.out.println(string.substring(3, 3));
System.out.println(string.substring(3, 2));
System.out.println(string.substring(3, 8));

A

// mals

// mals

// m

// mals

// empty string

// throws exception

// throws exception

The method substring() also looks for characters in a string. It returns parts of the string. The first parameter is the index to start with for the returned string. As usual, this is a zero-based index. There is an optional second parameter, which is the end index you want to stop at. Notice we said “stop at” rather than “include.” The method signatures are as follows:

int substring(int beginIndex)
int substring(int beginIndex, int endIndex)

Let’s review this one more time since substring() is so tricky. The method returns the string starting from the requested index. If an end index is requested, it stops right before that index. Otherwise, it goes to the end of the string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Important String Methods:
equals() and equalsIgnoreCase()

System.out.println(“abc”.equals(“ABC”));
System.out.println(“ABC”.equals(“ABC”)); System.out.println(“abc”.equalsIgnoreCase(“ABC”));

A

// false

// true

// true

The equals() method checks whether two String objects contain exactly the same char- acters in the same order. The equalsIgnoreCase() method checks whether two String objects contain the same characters with the exception that it will convert the characters’ case if needed. The method signatures are as follows:

boolean equals(String str)
boolean equalsIgnoreCase(String str)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Important String Methods:
startsWith() and endsWith()

System.out.println(“abc”.startsWith(“a”));
System.out.println(“abc”.startsWith(“A”));
System.out.println(“abc”.endsWith(“c”));
System.out.println(“abc”.endsWith(“a”));

A

// true

// false

// true

// false

The startsWith() and endsWith() methods look at whether the provided value matches part of the String. The method signatures are as follows:

boolean startsWith(String prefix)
boolean endsWith(String suffix)

Again, nothing surprising here. Java is doing a case-sensitive check on the values provided.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Important String Methods:
contains()

System.out.println(“abc”.contains(“b”));
System.out.println(“abc”.contains(“B”));

A

// true

// false

The contains() method also looks for matches in the String. It isn’t as particular as startsWith() and endsWith()—the match can be anywhere in the String. The method signature is as follows:

boolean contains(String str)

Again, we have a case-sensitive search in the String. The contains() method is a conve- nience method so you don’t have to write str.indexOf(otherString) != -1.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Important String Methods:
replace()

System.out.println(“abcabc”.replace(‘a’, ‘A’));
System.out.println(“abcabc”.replace(“a”, “A”));

A

// AbcAbc

// AbcAbc

The replace() method does a simple search and replace on the string. The method signatures are as follows:

String replace(char oldChar, char newChar)
String replace(CharSequence oldChar, CharSequence newChar)

The first example uses the first method signature, passing in char parameters. The second example uses the second method signature, passing in String parameters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Important String Methods:
trim()

System.out.println(“abc”.trim());
System.out.println(“\t a b c\n”.trim());

A

// abc

// a b c

The trim() method removes whitespace from the beginning and end of a String. In terms of the exam, whitespace consists of spaces along with the \t (tab) and \n (newline) characters. Other characters, such as \r (carriage return), are also included in what gets trimmed. The method signature is as follows:

public String trim()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

The StringBuilder class

A

The StringBuilder class creates a String without storing all those interim String values. Unlike the String class, StringBuilder is not immutable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Creating a StringBuilder

A

StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder(“animal”);
StringBuilder sb3 = new StringBuilder(10);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Important StringBuilder Methods:
charAt(), indexOf(), length(), and substring()

A

These four methods work exactly the same as in the String class.

17
Q

Important StringBuilder Methods:
append()

A

It adds the parameter to the StringBuilder and returns a reference to the current StringBuilder. One of the method signatures is as follows:

StringBuilder append(String str)

18
Q

Important StringBuilder Methods:
insert()

A

The insert() method adds characters to the StringBuilder at the requested index and
returns a reference to the current StringBuilder. Just like append(), there are lots of
method signatures for different types. Here’s one:

StringBuilder insert(int offset, String str)

Pay attention to the offset in these examples. It is the index where we want to insert the
requested parameter.

3: StringBuilder sb = new StringBuilder(“animals”);
4: sb.insert(7, “-“); // sb = animals-
5: sb.insert(0, “-“); // sb = -animals-
6: sb.insert(4, “-“); // sb = -ani-mals

19
Q

Important StringBuilder Methods:
delete() and deleteCharAt()

StringBuilder sb = new StringBuilder(“abcdef”);
sb.delete(1, 3);
sb.deleteCharAt(5);

A

// sb = adef

// throws an exception

The delete() method is the opposite of the insert() method. It removes characters from
the sequence and returns a reference to the current StringBuilder. The deleteCharAt()
method is convenient when you want to delete only one character. The method signatures
are as follows:

StringBuilder delete(int start, int end)
StringBuilder deleteCharAt(int index)

20
Q

Important StringBuilder Methods:
reverse()

A

The reverse() method does just what it sounds like: it reverses the characters in the sequences and returns a reference to the current StringBuilder. The method signature is as follows:

StringBuilder reverse()

21
Q

Important StringBuilder Methods:
toString()

A

The last method converts a StringBuilder into a String. The method signature is as follows:

String toString()

22
Q

Understanding Equality

StringBuilder one = new StringBuilder();
StringBuilder two = new StringBuilder();
StringBuilder three = one.append(“a”);

System.out.println(one == two);
System.out.println(one == three);

String x = “Hello World”;
String y = “Hello World”;

System.out.println(x == y);

String x = “Hello World”;
String z = “ Hello World”.trim();

System.out.println(x == z);

String x = new String(“Hello World”);
String y = “Hello World”;

System.out.println(x == y);

String x = “Hello World”;
String z = “ Hello World”.trim();

System.out.println(x.equals(z));

1: public class Tiger {
2: String name;
3: public static void main(String[] args) {
4: Tiger t1 = new Tiger();
5: Tiger t2 = new Tiger();
6: Tiger t3 = t1;
7: System.out.println(t1 == t1);
8: System.out.println(t1 == t2);
9: System.out.println(t1.equals(t2));
10: } }

A

// false

// true

Since this example isn’t dealing with primitives, we know to look for whether the references are referring to the same object. one and two are both completely separate StringBuilders, giving us two objects. Therefore, the first print statement gives us false. three is more interesting. Remember how StringBuilder methods like to return the current reference for chaining? This means one and three both point to the same object and the second print statement gives us true.

// true

Remember that Strings are immutable and literals are pooled. The JVM created only one literal in memory. x and y both point to the same location in memory; therefore, the statement outputs true.

// false

In this example, we don’t have two of the same String literal. Although x and z happen to evaluate to the same string, one is computed at runtime. Since it isn’t the same at compile-time, a new String object is created.

// false

Since you have specifi cally requested a different String object, the pooled value isn’t
shared.

// true

This works because the authors of the String class implemented a standard method called equals to check the values inside the String rather than the String itself. If a class doesn’t have an equals method, Java determines whether the references point to the
same object—which is exactly what == does. In case you are wondering, the authors of StringBuilder did not implement equals(). If you call equals() on two StringBuilder instances, it will check reference equality.

// true

// false

// false

The first two statements check object reference equality. Line 7 prints true because we are comparing references to the same object. Line 8 prints false because the two object references are different. Line 9 prints false since Tiger does not implement equals(). Don’t worry—you aren’t expected to know how to implement equals() for the OCA exam.

23
Q

Creating a Multidimensional Array

A

int[][] vars1; // 2D array
int vars2 [][]; // 2D array
int[] vars3[]; // 2D array
int[] vars4 [], space [][]; // a 2D AND a 3D array

24
Q

ArrayList Methods
add()

ArrayList list = new ArrayList();
list.add(“hawk”);
list.add(Boolean.TRUE);
System.out.println(list);

ArrayList<String> safer = new ArrayList<>();
safer.add("sparrow");
safer.add(Boolean.TRUE);</String>

4: List<String> birds = new ArrayList<>();
5: birds.add("hawk");
6: birds.add(1, "robin");
7: birds.add(0, "blue jay");
8: birds.add(1, "cardinal");
9: System.out.println(birds);</String>

A

// [hawk]

// [hawk, true]

// [hawk, true]

The add() methods insert a new value in the ArrayList. The method signatures are as
follows:

boolean add(E element)
void add(int index, E element)

Don’t worry about the boolean return value. It always returns true. It is there because
other classes in the collections family need a return value in the signature when adding an
element.

add() does exactly what we expect: it stores the String in the no longer empty ArrayList. It then does the same thing for the boolean. This is okay because we didn’t specify a type for ArrayList; therefore, the type is Object, which includes everything except primitives.

// DOES NOT COMPILE

This time the compiler knows that only String objects are allowed in and prevents the attempt to add a boolean. Now let’s try adding multiple values to different positions.

// [hawk]

// [hawk, robin]

// [blue jay, hawk, robin]

// [blue jay, cardinal, hawk, robin]

// [blue jay, cardinal, hawk, robin]

25
Q

ArrayList Methods
remove()

3: List<String> birds = new ArrayList<>();
4: birds.add("hawk");
5: birds.add("hawk");
6: System.out.println(birds.remove("cardinal"));
7: System.out.println(birds.remove("hawk"));
8: System.out.println(birds.remove(0));
9: System.out.println(birds);</String>

A

The remove() methods remove the first matching value in the ArrayList or remove the
element at a specified index. The method signatures are as follows:

boolean remove(Object object)
E remove(int index)

// [hawk]
// [hawk, hawk]
// prints false
// prints true
// prints hawk
// []

Line 6 tries to remove an element that is not in birds. It returns false because no such
element is found. Line 7 tries to remove an element that is in birds and so returns true.
Notice that it removes only one match. Line 8 removes the element at index 0, which is the
last remaining element in the ArrayList.

Since calling remove() with an int uses the index, an index that doesn’t exist will throw
an exception. For example, birds.remove(100) throws an IndexOutOfBoundsException.

26
Q

ArrayList Methods
isEmpty() and size()

System.out.println(birds.isEmpty()); // true
System.out.println(birds.size()); // 0
birds.add(“hawk”);
birds.add(“hawk”);
System.out.println(birds.isEmpty());
System.out.println(birds.size());

A

The isEmpty() and size() methods look at how many of the slots are in use. The method
signatures are as follows:

boolean isEmpty()
int size()

// [hawk]

// [hawk, hawk]

// false

// 2

27
Q

ArrayList Methods
clear()

List<String> birds = new ArrayList<>();
birds.add("hawk");
birds.add("hawk");
System.out.println(birds.isEmpty());
System.out.println(birds.size());
birds.clear();
System.out.println(birds.isEmpty());
System.out.println(birds.size());</String>

A

The clear() method provides an easy way to discard all elements of the ArrayList. The
method signature is as follows:

void clear()

// [hawk]
// [hawk, hawk]
// false
// 2
// []
// true
// 0

After we call clear(), birds is back to being an empty ArrayList of size 0.

28
Q

ArrayList Methods
contains()

List<String> birds = new ArrayList<>();
birds.add("hawk");
System.out.println(birds.contains("hawk"));
System.out.println(birds.contains("robin"));</String>

A

The contains() method checks whether a certain value is in the ArrayList. The method
signature is as follows:

boolean contains(Object object)

// [hawk]
// true
// false

This method calls equals() on each element of the ArrayList to see whether there are
any matches. Since String implements equals(), this works out well.

29
Q

ArrayList Methods
equals()

31: List<String> one = new ArrayList<>();
32: List<String> two = new ArrayList<>();
33: System.out.println(one.equals(two));
34: one.add("a");
35: System.out.println(one.equals(two));
36: two.add("a");
37: System.out.println(one.equals(two));
38: one.add("b");
39: two.add(0, "b");
40: System.out.println(one.equals(two));</String></String>

A

Finally, ArrayList has a custom implementation of equals() so you can compare two lists
to see if they contain the same elements in the same order.

boolean equals(Object object)

// true
// [a]
// false
// [a]
// true
// [a,b]
// [b,a]
// false

On line 33, the two ArrayList objects are equal. An empty list is certainly the same
elements in the same order. On line 35, the ArrayList objects are not equal because the size
is different. On line 37, they are equal again because the same one element is in each. On
line 40, they are not equal. The size is the same and the values are the same, but they are
not in the same order.

30
Q

binarySearch()

3: int[] numbers = {2,4,6,8};
4: System.out.println(Arrays.binarySearch(numbers, 2));
5: System.out.println(Arrays.binarySearch(numbers, 4));
6: System.out.println(Arrays.binarySearch(numbers, 1));
7: System.out.println(Arrays.binarySearch(numbers, 3));
8: System.out.println(Arrays.binarySearch(numbers, 9));

A

The exam creators will not expect you to know what incorrect values come out. As soon as you see the array isn’t sorted, look for an answer choice about unpredictable output.

// 0
// 1
// -1
// -2
// -5

31
Q

Autoboxing

3: List<Integer> heights = new ArrayList<>();
4: heights.add(null);
5: int h = heights.get(0);</Integer>

List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.remove(1);
System.out.println(numbers);</Integer>

A

Since Java 5, you can just type the primitive value and Java will convert it to the relevant wrapper class for you.

// NullPointerException

On line 4, we add a null to the list. This is legal because a null reference can be assigned to any reference variable. On line 5, we try to unbox that null to an int primitive. This is a problem. Java tries to get the int value of null. Since calling any method on null gives a NullPointerException, that is just what we get. Be careful when you see null in relation to autoboxing.

It actually outputs 1. After adding the two values, the List contains [1, 2]. We then request the element with index 1 be removed. That’s right: index 1. Because there’s already a remove() method that takes an int parameter, Java calls that method rather than autoboxing. If you
want to remove the 2, you can write numbers.remove(new Integer(2)) to force wrapper class use.

32
Q

Converting between array and list

ArrayList into an Array:
3: List<String> list = new ArrayList<>();
4: list.add("hawk");
5: list.add("robin");
6: Object[] objectArray = list.toArray();
7: System.out.println(objectArray.length);
8: String[] stringArray = list.toArray(new String[0]);
9: System.out.println(stringArray.length);</String>

Array into a List:
20: String[] array = { “hawk”, “robin” };
21: List<String> list = Arrays.asList(array);
22: System.out.println(list.size());
23: list.set(1, "test");
24: array[0] = "new";
25: for (String b : array) System.out.print(b + " ");
26: list.remove(1);</String>

A

line 7: // 2
line 9: // 2

Line 6 shows that an ArrayList knows how to convert itself to an array. The only problem is that it defaults to an array of class Object. This isn’t usually what you want. Line 8 specifies the type of the array and does what we actually want. The advantage of specifying a size of 0 for the parameter is that Java will create a new array of the proper size for the
return value. If you like, you can suggest a larger array to be used instead. If the ArrayList fits in that array, it will be returned. Otherwise, a new one will be created.

line 20: // [hawk, robin]
line 21: // returns fixed size list
line 22: // 2
line 23: // [hawk, test]
line 24: // [new, test]
line 25: // new test
line 26: // throws UnsupportedOperation Exception

Converting from an array to a List is more interesting. The original array and created array backed List are linked. When a change is made to one, it is available in the other. It is a fixed-size list and is also known a backed List because the array changes with it. Line 21 converts the array to a List. Note that it isn’t the java.util.ArrayList we’ve
grown used to. It is a fixed-size, backed version of a List. Line 23 is okay because set() merely replaces an existing value. It updates both array and list because they point to the same data store. Line 24 also changes both array and list. Line 25 shows the array has changed to new test. Line 26 throws an exception because we are not allowed to change
the size of the list.

33
Q

LocalDate

System.out.println(LocalDate.now());

A

Contains just a date—no time and no time zone. A good example of
LocalDate is your birthday this year. It is your birthday for a full day regardless of what time it is.

2015-01-20

The method signatures are as follows:

public static LocalDate of(int year, int month, int dayOfMonth)
public static LocalDate of(int year, Month month, int dayOfMonth)

Month is a special type of class called an enum. You don’t need to know about enums on the OCA exam and can just treat them as constants.

34
Q

LocalTime

System.out.println(LocalTime.now());

A

Contains just a time—no date and no time zone. A good example of
LocalTime is midnight. It is midnight at the same time every day.

12:45:18.401

The method signatures are as follows:

public static LocalTime of(int hour, int minute)
public static LocalTime of(int hour, int minute, int second)
public static LocalTime of(int hour, int minute, int second, int nanos)

35
Q

LocalDateTime

System.out.println(LocalDateTime.now());

A

Contains both a date and time but no time zone. A good example of
LocalDateTime is “the stroke of midnight on New Year’s.” Midnight on January 2 isn’t nearly as special, and clearly an hour after midnight isn’t as special either.

2015-01-20T12:45:18.401