Chapter 5 Core Java APIs Flashcards

1
Q

What is API?

A

Application Programming Interface (API),
an interface refers to a group of classes or Java interface definitions giving you access to a service or functionality.

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

Creating and Manipulating Strings

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

What is a string?

A

A string is basically a sequence of characters;
here’s an example:

String name = "Fluffy";

the String class is special and doesn’t need to be instantiated with new.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
String name = "Fluffy";

VS

String name = new String("Fluffy");
A

the String class is special and doesn’t need to be instantiated with new.

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

Since a String is a sequence of characters, you probably won’t be surprised to hear that it implements the interface CharSequence.

This interface is a general way of representing several classes, including String and StringBuilder. You’ll learn more about interfaces later in the book.

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

String Concatenation Rules

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
7
Q
System.out.println(1 + 2); 
System.out.println("a" + "b");
System.out.println("a" + "b" + 3);
System.out.println(1 + 2 + "c");
System.out.println("c" + 1 + 2);
A
System.out.println(1 + 2); // 3
System.out.println("a" + "b"); // ab
System.out.println("a" + "b" + 3); // ab3
System.out.println(1 + 2 + "c"); // 3c
System.out.println("c" + 1 + 2); // c12
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
int three = 3;
String four = "4";
System.out.println(1 + 2 + three + four);
A
int three = 3;
String four = "4";
System.out.println(1 + 2 + three + four);//64
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
4: String s = "1";
5: s += "2";
6: s += 3;
7: System.out.println(s);
A
4: String s = "1"; // s currently holds "1"
5: s += "2"; // s currently holds "12"
6: s += 3; // s currently holds "123"
7: System.out.println(s); // 123
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

String is immutable

A

Once a String object is created, it is not allowed to change. It cannot be made larger or smaller, and you cannot change one of the characters inside it.

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

MORE ON IMMUTABILITY

A

Immutable has only a getter. There’s no way to change the value of s once it’s set. Mutable has a setter. This allows the reference s to change to point to a different String later. Note that even though the String class is immutable, it can still be used in a mutable class. You can even make the instance variable final so the compiler reminds you if you accidentally change s.
Also, immutable classes in Java are final, which prevents subclasses creation. You wouldn’t want a subclass adding mutable behavior.

class Mutable {
    private String s;
    public void setS(String newS){ s = newS; } // Setter makes it mutable
    public String getS() { return s; }
}

final class Immutable {
    private String s = "name";
    public String getS() { return s; }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

IMPORTANT STRING METHODS

A
  • length()
  • charAt()
  • indexOf()
  • substring()
  • toLowerCase() and toUpperCase()
  • equals() and equalsIgnoreCase()
  • startsWith() and endsWith()
  • replace()
  • contains()
  • trim(), strip(), stripLeading(), and stripTrailing()
  • intern()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q
int length()
A

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
14
Q
char charAt(int index)
A

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
15
Q
String string = "animals";
System.out.println(string.charAt(0));
System.out.println(string.charAt(6));
System.out.println(string.charAt(7));
A
String string = "animals";
System.out.println(string.charAt(0)); // a
System.out.println(string.charAt(6)); // s
System.out.println(string.charAt(7)); // throws Exception java.lang.StringIndexOutOfBoundsException: String index out of range: 7
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q
int indexOf(int ch)
int indexOf(int ch, int fromIndex)
int indexOf(String str)
int indexOf(String str, int fromIndex)
A

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.

Remember that a char can be passed to an int parameter type.

On the exam, you’ll only see a char passed to the parameters named ch.

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. Because indexes start with 0, the caller knows that –1 couldn’t be a valid index. This makes it a common value for a method to signify to the caller that no match is found.

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

indexOf() examples:

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
String string = "animals";
System.out.println(string.indexOf('a')); // 0
System.out.println(string.indexOf("al")); // 4
System.out.println(string.indexOf('a', 4)); // 4
System.out.println(string.indexOf("al", 5)); // -1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q
String substring(int beginIndex)
String substring(int beginIndex, int endIndex)
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q
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)); 
A
String string = "animals";
System.out.println(string.substring(3)); // mals
System.out.println(string.substring(string.indexOf('m'))); // mals
System.out.println(string.substring(3, 4)); // m
System.out.println(string.substring(3, 7)); // mals
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q
System.out.println(string.substring(3, 3));
System.out.println(string.substring(3, 2)); 
System.out.println(string.substring(3, 8));
A
System.out.println(string.substring(3, 3)); // empty string
System.out.println(string.substring(3, 2)); // Exception java.lang.StringIndexOutOfBoundsException: begin 3, end 2, length 7
System.out.println(string.substring(3, 8)); // Exception java.lang.StringIndexOutOfBoundsException: begin 3, end 8, length 7
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q
String toLowerCase()
String toUpperCase()
A

toUpperCase() converts any lowercase characters to uppercase in the returned string.

toLowerCase() converts any uppercase characters to lowercase in the returned string.

These methods leave alone any characters other than letters.

Also, remember that strings are immutable, so the original string stays the same.

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

toUpperCase() and toLowerCase() examples:

String string = "animals";
System.out.println(string.toUpperCase()); 
System.out.println("Abc123".toLowerCase());
A
String string = "animals";
System.out.println(string.toUpperCase()); // ANIMALS
System.out.println("Abc123".toLowerCase()); // abc123
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q
boolean equals(Object obj)
boolean equalsIgnoreCase(String str)
A

The equals() method checks whether two String objects contain exactly the same characters 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.

equals() takes an Object rather than a String. This is because the method is the same for all objects.

If you pass in something that isn’t a String, it will just return false.

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

equals() and equalsIgnoreCase() examples

System.out.println("abc".equals("ABC")); 
System.out.println("ABC".equals("ABC")); 
System.out.println("abc".equalsIgnoreCase("ABC"));
A
System.out.println("abc".equals("ABC")); // false
System.out.println("ABC".equals("ABC")); // true
System.out.println("abc".equalsIgnoreCase("ABC")); // true
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q
boolean startsWith(String prefix)
boolean endsWith(String suffix)
A

The startsWith() and endsWith() methods look at whether the provided value matches(case-sensitive) part of the String.

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

startWith() and endsWith() example:
~~~
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
System.out.println("abc".startsWith("a")); // true
System.out.println("abc".startsWith("A")); // false
System.out.println("abc".endsWith("c")); // true
System.out.println("abc".endsWith("a")); // false
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q
String replace(char oldChar, char newChar)
String replace(CharSequence target, CharSequence replacement)
A

The replace() method does a simple search and replace on the string.
There’s a version that takes char parameters as well as a version that takes CharSequence parameters.

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

replace() examples:
~~~
System.out.println(“abcabc”.replace(‘a’, ‘A’)); // AbcAbc
System.out.println(“abcabc”.replace(“a”, “A”)); // AbcAbc
~~~

A

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
29
Q

boolean contains(CharSequence charSeq)

A

The contains() method looks for matches (case-sensitive) in the String. It isn’t as particular as startsWith() and endsWith()—the match can be anywhere in the String.

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

contains() examples:
~~~
System.out.println(“abc”.contains(“b”)); // true
System.out.println(“abc”.contains(“B”)); // false
~~~

A

a case-sensitive search in the String. The contains()
method is a convenience 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
31
Q
String strip()
String stripLeading()
String stripTrailing()
String trim()
A

Removing blank space from the beginning and/or end of a String. The strip() and trim() methods remove 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 strip() method is new in Java 11. It does everything that trim() does, but it supports Unicode.

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

You don’t need to know about Unicode for the exam. But if you want to test the difference, one of Unicode whitespace characters is as follows:
char ch = '\u2000';
Additionally, the stripLeading() and stripTrailing() methods
were added in Java 11. The stripLeading() method removes whitespace from the beginning of the String and leaves it at the end. The stripTrailing() method does the opposite. It removes whitespace from the end of the String and leaves it at the beginning.

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

trim(), strip(), stripLeading(), and stripTrailing() examples:
~~~
System.out.println(“abc”.strip()); // abc
System.out.println(“\t a b c\n”.strip()); // a b c
String text = “ abc\t “;
System.out.println(text.trim().length()); // 3
System.out.println(text.strip().length()); // 3
System.out.println(text.stripLeading().length()); // 5
System.out.println(text.stripTrailing().length());// 4
~~~

A

First, remember that \t is a single character. The backslash escapes the t to represent a tab. The first example prints the original string because there are no whitespace characters at the beginning or end.

The second example gets rid of the leading tab, subsequent spaces, and the trailing newline. It leaves the spaces that are in the middle of the string.

The remaining examples just print the number of characters remaining.
You can see that both trim() and strip() leave the same three characters “abc” because they remove both the leading and trailing whitespace. The stripLeading() method only removes the one whitespace character at the beginning of the String. It leaves the tab and space at the end. The stripTrailing() method removes these two
characters at the end but leaves the character at the beginning of the String.

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

String intern()

A

The intern() method returns the value from the string pool if it is there. Otherwise, it adds the value to the string pool.

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

METHOD CHAINING
examples:
~~~
String result = “AniMaL “.trim().toLowerCase().replace(‘a’, ‘A’);
System.out.println(result);
~~~

A

It is common to call multiple methods

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

Remember that String is immutable. What do you think the result of this code is?
~~~
5: String a = “abc”;
6: String b = a.toUpperCase();
7: b = b.replace(“B”, “2”).replace(‘C’, ‘3’);
8: System.out.println(“a=” + a);
9: System.out.println(“b=” + b);
~~~

A

On line 5, we set a to point to “abc” and never pointed a to anything else.
Since we are dealing with an immutable object, none of the code on lines 6 and 7 changes a, and the value remains “abc”.

b is a little trickier. Line 6 has b pointing to “ABC”, which is straightforward. On line 7, we have method chaining. First, “ABC”.replace(“B”, “2”) is called. This returns “A2C”. Next, “A2C”.replace(‘C’, ‘3’) is called. This returns “A23”. Finally, b changes to point to this returned String. When line 9 executes, b is “A23”.

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

Using 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
38
Q
10: String alpha = "";
11: for(char current = 'a'; current <= 'z'; current++)
12:     alpha += current;
13: System.out.println(alpha);
A

line 12 appends an “a”.
However, because the String object is immutable, a new String object is assigned to alpha, and the “” object becomes eligible for garbage collection.
The next time through the loop, alpha is assigned a new String object, “ab”, and the “a” object becomes eligible for garbage collection.
The next iteration assigns alpha to “abc”, and the “ab” object becomes eligible for garbage collection, and so on.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q
15: StringBuilder alpha = new StringBuilder();
16: for(char current = 'a'; current <= 'z'; current++)
17:     alpha.append(current);
18: System.out.println(alpha);
A

On line 15, a new StringBuilder object is instantiated.
The call to append() on line 17 adds a character to the StringBuilder object each time through the for loop appending the value of current to the end of alpha. This code reuses the same StringBuilder without creating an interim String each time.

` `

In old code, you might see references to StringBuffer. It works the same way except it supports threads, which you’ll learn about when preparing for the 1Z0-816 exam. StringBuffer is no longer on either exam. It performs slower than StringBuilder, so just use StringBuilder.

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

MUTABILITY AND CHAINING

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q
4: StringBuilder sb = new StringBuilder("start");
5: sb.append("+middle"); // sb = "start+middle"
6: StringBuilder same = sb.append("+end"); // "start+middle+end"
A

Line 5 adds text to the end of sb. It also returns a reference to sb, which is ignored. Line 6 also adds text to the end of sb and returns a reference to sb. This time the reference is stored in same—which means sb and same point to the same object and would print out the same value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q
4: StringBuilder a = new StringBuilder("abc");
5: StringBuilder b = a.append("de");
6: b = b.append("f").append("g");
7: System.out.println("a=" + a);
8: System.out.println("b=" + b);
A

Did you say both print “abcdefg”? Good. There’s only one StringBuilder object here. We know that because new StringBuilder() was called only once. On line 5, there are two variables referring to that object, which has a value of “abcde”. On line 6, those two variables are still referring to that same object, which now has a value of “abcdefg”. Incidentally, the assignment back to b does absolutely nothing. b is already pointing to that StringBuilder.

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

CREATING A STRINGBUILDER

A

There are three ways to construct a StringBuilder:
~~~
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder(“animal”);
StringBuilder sb3 = new StringBuilder(10);
~~~

The first says to create a StringBuilder containing an empty sequence of characters and assign sb1 to point to it.

The second says to create a StringBuilder containing a specific value and assign sb2 to point to it.

For the first two, it tells Java to manage the implementation details.

The final example tells Java that we have some idea of how big the eventual value will be and would like the StringBuilder to reserve a certain capacity, or number of slots, for characters.

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

IMPORTANT STRINGBUILDER METHODS

A
  • charAt(),
  • indexOf(),
  • length()
  • substring()
  • append()
  • insert()
  • delete() and deleteCharAt()
  • replace()
  • reverse()
  • toString()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

STRINGBUILDER METHODS
charAt(), indexOf(), length(), and substring()

A

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

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

Be sure you can identify the output of this example:
~~~
StringBuilder sb = new StringBuilder(“animals”);
String sub = sb.substring(sb.indexOf(“a”), sb.indexOf(“al”));
int len = sb.length();
char ch = sb.charAt(6);
System.out.println(sub + “ “ + len + “ “ + ch);
~~~

A

The correct answer is anim 7 s.

The indexOf()method calls return 0 and 4, respectively. substring() returns the String starting with index 0 and ending right before index 4.

length() returns 7 because it is the number of characters in the StringBuilder rather than an index.

Finally, charAt() returns the character at index 6. Here we do start with 0 because we are referring to indexes. If any of this doesn’t sound familiar, go back and read the section on String again.

Notice that substring() returns a String rather than a StringBuilder. That is why sb is not changed. substring() is really just a method that inquires about what the state of the StringBuilder happens to be.

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

StringBuilder append(String str)

A

adds the parameter to the StringBuilder and returns a reference to the current StringBuilder.

There are more than 10 method signatures that look similar but that take different data types as parameters.

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

append() examples:
~~~
StringBuilder sb = new StringBuilder().append(1).append(‘c’);
sb.append(“-“).append(true);
System.out.println(sb); // 1c-true
~~~

A

append() is called directly after the constructor. By having all these method signatures, you can just call append() without having to convert your parameter to a String first.

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

StringBuilder insert(int offset, String str)

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.

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

insert() examples:
~~~
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-
7: System.out.println(sb);
~~~

A

Line 4 says to insert a dash at index 7, which happens to be the end of the sequence of characters.

Line 5 says to insert a dash at index 0, which happens to be the very beginning.

Finally, line 6 says to insert a dash right before index 4. The exam creators will try to trip you up on this. As we add and remove characters, their indexes change. When you see a question dealing with such operations, draw what is going on so you won’t be confused.

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

StringBuilder delete(int startIndex, int endIndex)
StringBuilder deleteCharAt(int index)

A

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.

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

delete() examples:

StringBuilder sb = new StringBuilder("abcdef");
sb.delete(1, 3); // sb = adef
sb.deleteCharAt(5); // throws an exception
A

First, we delete the characters starting with index 1 and ending right before index 3. This gives us adef. Next, we ask Java to delete the character at position 5. However, the remaining value is only four characters long, so it throws a StringIndexOutOfBoundsException.

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

delete() examples:
~~~
StringBuilder sb = new StringBuilder(“abcdef”);
sb.delete(1, 100); // sb = a
~~~

A

The delete() method is more flexible than some others when it comes to array indexes. If you specify a second parameter that is past the end of the StringBuilder, Java will just assume you meant the end. That means this code is legal:

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

StringBuilder replace(int startIndex, int endIndex, String newString)

A

The replace() method works differently for StringBuilder than it did for String.

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

replace() examples:
StringBuilder builder = new StringBuilder(“pigeon dirty”);
builder.replace(3, 6, “sty”);
System.out.println(builder); // pigsty dirty

A

First, Java deletes the characters starting with index 3 and ending right before index 6. This gives us pig dirty. Then Java inserts to the value “sty” in that position.

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

replace() examples:
~~~
StringBuilder builder = new StringBuilder(“pigeon dirty”);
builder.replace(3, 100, “”);
System.out.println(builder);
~~~

A

It actually prints “pig”. Remember the method is first doing a logical delete. The replace() method allows specifying a second parameter that is past the end of the StringBuilder. That means only the first three characters remain.

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

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

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

reverse() examples:
~~~
StringBuilder sb = new StringBuilder(“ABC”);
sb.reverse();
System.out.println(sb);
~~~

A

As expected, this prints CBA. This method isn’t that interesting. Maybe the exam creators like to include it to encourage you to write down the value rather than relying on memory for indexes.

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

String toString()

A

This method converts a StringBuilder into a String.

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

toString() examples:

StringBuilder sb = new StringBuilder("ABC");
String s = sb.toString();
A

Often StringBuilder is used internally for performance purposes, but the end result needs to be a String. For example, maybe it needs to be passed to another method that is expecting a String.

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

Understanding Equality

A

In this section, we will look at what it means for two objects to be equivalent or the same. We will also look at the impact of the String pool on equality.

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

COMPARING EQUALS() AND ==

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q
StringBuilder one = new StringBuilder();
StringBuilder two = new StringBuilder();
StringBuilder three = one.append("a");
System.out.println(one == two); // false
System.out.println(one == three); // true
A

one and two are both completely separate StringBuilder objects, giving us two objects. Therefore, the first print statement gives us false.

append() return current reference for chaining This means one and three both point to the same object, and the second print statement gives us true.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q
String x = "Hello World";
String z = " Hello World".trim();
System.out.println(x.equals(z)); // true
A

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

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

the authors of StringBuilder did not implement equals().

If you call equals() on two StringBuilder instances, it will check reference equality. You can call toString() on StringBuilder to get a String to check for equality instead.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q
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 == t3); // true
8:         System.out.println(t1 == t2); // false
9:         System.out.println(t1.equals(t2)); // false
10: } }
A

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 this exam.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q
String string = "a";
StringBuilder builder = new StringBuilder("a");
System.out.println(string == builder); //DOES NOT COMPILE
A

Remember that == is checking for object reference equality. The compiler is smart enough to know that two references can’t possibly point to the same object when they are completely different types.

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

THE STRING POOL

A

The string pool, also known as the intern pool, is a location in the Java virtual machine (JVM) that collects all these strings.

The string pool contains literal values and constants that appear in your program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q
String x = "Hello World";
String y = "Hello World";
System.out.println(x == y); // true
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q
String x = "Hello World";
String z = " Hello World".trim();
System.out.println(x == z); // false
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q
String singleString = "hello world";
String concat = "hello ";
concat += "world";
System.out.println(singleString == concat);
A

This prints false. Concatenation is just like calling a method and results in a new String

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q
String x = "Hello World";
String y = new String("Hello World");
System.out.println(x == y); // false
A

The former says to use the string pool normally. The second says “No, JVM, I really don’t want you to use the string pool. Please create a new object for me even though it is less efficient.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q
String name = "Hello World";
String name2 = new String("Hello World").intern();
System.out.println(name == name2); // true
A

tell Java to use the string pool. The intern() method will use an object in the string pool if one is present. If the literal is not yet in the string pool, Java will add it at this time.

First we tell Java to use the string pool normally for name. Then for name2, we tell Java to create a new object using the constructor but to intern it and use the string pool anyway. Since both variables point to the same reference in the string pool, we can use the == operator.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q
15: String first = "rat" + 1;
16: String second = "r" + "a" + "t" + "1";
17: String third = "r" + "a" + "t" + new String("1");
18: System.out.println(first == second);
19: System.out.println(first == second.intern());
20: System.out.println(first == third);
21: System.out.println(first == third.intern());
A

On line 15, we have a compile-time constant that automatically gets placed in the string pool as “rat1”. On line 16, we have a more complicated expression that is also a compile-time constant. Therefore, first and second share the same string pool reference. This makes line 18 and 19 print true.
On line 17, we have a String constructor. This means we no longer have a compile-time constant, and third does not point to a reference in the string pool. Therefore, line 20 prints false. On line 21, the intern() call looks in the string pool. Java notices that first points to the same String and prints true.

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

Remember to never use intern() or == to compare String objects in your code. The only time you should have to deal with these is on the exam.

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

Understanding Java Arrays

A

An array is an area of memory on the heap with space for a designated number of elements.

an array can be of any other Java type

In other words, an array is an ordered list. It can contain duplicates.

A StringBuilder is implemented as an array where the array object is replaced with a new bigger array object when it runs out of space to store all the characters.

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

CREATING AN ARRAY OF PRIMITIVES
~~~
int[] numbers1 = new int[3];
~~~

A
int[] numbers1 = new int[3];

It specifies the type of the array (int) and the size (3). The brackets [] tell you this is an array.

brackets/array symbal [] is required.

When you use this form to instantiate an array, all elements are set to the default value for that type. As you learned in Chapter 2, the default value of an int is 0. Since numbers1 is a reference variable, it points to the array object

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

CREATING AN ARRAY OF PRIMITIVES

int[] numbers2 = new int[] {42, 55, 99};
A

we also create an int array of size 3. This time, we specify the initial values of those three elements instead of using the defaults.

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

CREATING AN ARRAY OF PRIMITIVES

int[] numbers2 = {42, 55, 99};

A

Java recognizes that this expression is redundant. Since you are specifying the type of the array on the left side of the equal sign, Java already knows the type. And since you are specifying the initial values, it already knows the size. As a shortcut, Java lets you write this:
~~~
int[] numbers2 = {42, 55, 99};
~~~

This approach is called an anonymous array. It is anonymous because you don’t specify the type and size.

80
Q
int[] numAnimals;
int [] numAnimals2;
int []numAnimals3;
int numAnimals4[];
int numAnimals5 [];
A

can type the [] before or after the name, and adding a space is optional.

81
Q

MULTIPLE “ARRAYS” IN DECLARATIONS
~~~
int[] ids, types;
~~~

A

The correct answer is two variables of type int[].

82
Q

MULTIPLE “ARRAYS” IN DECLARATIONS
~~~
int ids[], types;
~~~

A

one variable of type int[] and one variable of type int.

The first one is called ids[]. This one is an int[] called ids. The second one is just called types. No brackets, so it is a regular integer.

Needless to say, you shouldn’t write code that looks like this. But you do need to understand it for the exam.

83
Q

CREATING AN ARRAY WITH REFERENCE VARIABLES
~~~
public class ArrayType {
public static void main(String args[]) {
String [] bugs = { “cricket”, “beetle”, “ladybug” };
String [] alias = bugs;
System.out.println(bugs.equals(alias)); // true
System.out.println(
bugs.toString()); //[Ljava.lang.String;@160bc7c0
} }
~~~

A

We can call equals() because an array is an object. It returns true because of reference equality. The equals() method on arrays does not look at the elements of the array. Remember, this would work even on an int[] too. int is a primitive; int[] is an object.

The second print statement is even more interesting. What on earth is [Ljava.lang .String;@160bc7c0? You don’t have to know this for the exam, but [L means it is an array, java.lang.String is the reference type, and 160bc7c0 is the hash code. You’ll get different numbers and letters each time you run it since this is a reference.

84
Q

Since Java 5, Java has provided a method that prints an array nicely:
Arrays.toString(bugs) would print [cricket, beetle, ladybug].

A
85
Q

The array does not allocate space for the String objects. Instead, it allocates space for a reference to where the objects are really stored.

A
86
Q
class Names {
String names[];
}
A

The answer is null. The code never instantiated the array, so it is just a reference variable to null.

87
Q
class Names {
String names[] = new String[2];
}
A

It is an array because it has brackets. It is an array of type String since that is the type mentioned in the declaration. It has two elements because the length is 2. Each of those two slots currently is null but has the potential to point to a String object.

88
Q
3: String[] strings = { "stringValue" };
4: Object[] objects = strings;
5: String[] againStrings = (String[]) objects;
6: againStrings[0] = new StringBuilder(); // DOES NOT COMPILE
7: objects[0] = new StringBuilder(); // careful!
A

Line 3 creates an array of type String. Line 4 doesn’t require a cast because Object is a broader type than String. On line 5, a cast is needed because we are moving to a more specific type. Line 6 doesn’t compile because a String[] only allows String objects and StringBuilder is not a String.
Line 7 is where this gets interesting. From the point of view of the compiler, this is just fine. A StringBuilder object can clearly go in an Object[]. The problem is that we don’t actually have an Object[]. We have a String[] referred to from an Object[] variable. At runtime, the code throws an ArrayStoreException. You don’t need to memorize the name of this exception, but you do need to know that the code will throw an exception.

89
Q

USING AN ARRAY
~~~
4: String[] mammals = {“monkey”, “chimp”, “donkey”};
5: System.out.println(mammals.length); // 3
6: System.out.println(mammals[0]); // monkey
7: System.out.println(mammals[1]); // chimp
8: System.out.println(mammals[2]); // donkey
~~~

A

Line 4 declares and initializes the array.
Line 5 tells us how many elements the array can hold.
The rest of the code prints the array.
Notice elements are indexed starting with 0. This should be familiar from String and StringBuilder, which also start counting with 0. Those classes also counted length as the number of elements. Note that there are no parentheses after length since it is not a method.

90
Q
String[] birds = new String[6];
System.out.println(birds.length);
A

The answer is 6. Even though all six elements of the array are null, there are still six of them. length does not consider what is in the array; it only considers how many slots have been allocated.

91
Q
5: int[] numbers = new int[10];
6: for (int i = 0; i < numbers.length; i++)
7: numbers[i] = i + 5;
A

Line 5 simply instantiates an array with 10 slots.
Line 6 is a for loop that uses an extremely common pattern. It starts at index 0, which is where an array begins as well. It keeps going, one at a time, until it hits the end of the array.
Line 7 sets the current element of numbers.

92
Q

Can you tell why each of these throws an ArrayIndexOutOfBoundsException for our array of size 10?

numbers[10] = 3;
numbers[numbers.length] = 5;
for (int i = 0; i <= numbers.length; i++) numbers[i] = i + 5;
A

The first one is trying to see whether you know that indexes start with 0. Since we have 10 elements in our array, this means only numbers[0] through numbers[9] are valid. The second example assumes you are clever enough to know 10 is invalid and disguises it by using the length field. However, the length is always one more than the maximum valid index. Finally, the for loop incorrectly uses <= instead of <, which is also a way of referring to that 10th element.

numbers[numbers.length]=5
|        at (#3:1)

Exception java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10

93
Q

ARRAY SORTING

A

Java makes it easy to sort an array by providing a sort method.
can pass almost any array to Arrays.sort().

To use Arrays, you must have either of the following two statements in your class:

import java.util.*; // import whole package including Arrays
import java.util.Arrays; // import just Arrays
94
Q
int[] numbers = { 6, 9, 1 };
Arrays.sort(numbers);
for (int i = 0; i < numbers.length; i++)
    System.out.print(numbers[i] + " ");
A

The result is 1 6 9, as you should expect it to be. Notice that we looped through the output to print the values in the array. Just printing the array variable directly would give the annoying hash of [I@2bd9c3e7. Alternatively, we could have printed Arrays .toString(numbers) instead of using the loop. That would have output [1, 6, 9].

95
Q
String[] strings = { "10", "9", "100" };
Arrays.sort(strings);
for (String string : strings)
    System.out.print(string + " ");
A

This time the result might not be what you expect. This code outputs 10 100 9. The problem is that String sorts in alphabetic order, and 1 sorts before 9. (Numbers sort before letters, and uppercase sorts before lowercase, in case you were wondering.)

96
Q

ARRAY SEARCHING

A

Java also provides a convenient way to search—but only if the array is already sorted.

Binary search rules
1. Target element found in sorted array, return index of match
2. Target element not found in sorted array, return negative value showing one smaller than the negative of the index, where a match needs to be inserted to preserve sorted order
3. Unsorted array, return a surprise—this result isn’t predictable

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

Take note of the fact that line 3 is a sorted array. If it wasn’t, we couldn’t apply either of the other rules. Line 4 searches for the index of 2. The answer is index 0. Line 5 searches for the index of 4, which is 1.

Line 6 searches for the index of 1. Although 1 isn’t in the list, the search can determine that it should be inserted at element 0 to preserve the sorted order. Since 0 already means something for array indexes, Java needs to subtract 1 to give us the answer of –1. Line 7 is similar. Although 3 isn’t in the list, it would need to be inserted at element 1 to preserve the sorted order. We negate and subtract 1 for consistency, getting –1 –1, also known as –2. Finally, line 8 wants to tell us that 9 should be inserted at index 4. We again negate and subtract 1, getting –4 –1, also known as –5.

98
Q
5: int[] numbers = new int[] {3,2,1};
6: System.out.println(Arrays.binarySearch(numbers, 2)); //1
7: System.out.println(Arrays.binarySearch(numbers, 3)); //-4
A

Note that on line 5, the array isn’t sorted. This means the output will not be predictable. When testing this example, line 6 correctly gave 1 as the output. However, line 7 gave the wrong answer. 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.

99
Q

ARRAY COMPARING

A

Java also provides methods to compare two arrays to determine which is “smaller.” First we will cover the compare() method and then go on to mismatch().

100
Q

compare() rules

A
  • A negative number means the first array is smaller than the second.
  • A zero means the arrays are equal.
  • A positive number means the first array is larger than the second.
101
Q
System.out.println(Arrays.compare(new int[] {1}, new int[] {2}));
A

This code prints a negative number.
It should be pretty intuitive that 1 is smaller than 2, making the first array smaller.

102
Q

how to compare arrays of different lengths:

A
  • If both arrays are the same length and have the same values in each spot in the same order, return zero.
  • If all the elements are the same but the second array has extra elements at the end, return a negative number.
  • If all the elements are the same but the first array has extra elements at the end, return a positive number.
  • If the first element that differs is smaller in the first array, return a negative number.
  • If the first element that differs is larger in the first array, return a positive number.
103
Q

Here are some more rules that apply here and to compareTo(), which you’ll see in Chapter 6, “Lambdas and
Functional Interfaces”:

  • null is smaller than any other value.
  • For numbers, normal numeric order applies.
  • For strings, one is smaller if it is a prefix of another.
  • For strings/characters, numbers are smaller than letters.
  • For strings/characters, uppercase is smaller than lowercase.
A
104
Q
System.out.println(Arrays.compare(new int[] {1, 2}, new int[] {1}));
A

return positive number
The first element is the same, but the first array is longer.

105
Q
System.out.println(Arrays.compare(new int[] {1, 2}, new int[] {1, 2}));
A

return zero
Exact match

106
Q
System.out.println(Arrays.compare(new String[] {"a"}, new String[] {"aa"}));
A

return negative number
The first element is a substring of the second.

107
Q
System.out.println(Arrays.compare(new String[] {"a"}, new String[] {"A"}));
A

Return positive number
Uppercase is smaller than lowercase.

108
Q
System.out.println(Arrays.compare(new String[] {"a"}, new String[] {null}));
A

Return positive number
null is smaller than a letter.

109
Q
System.out.println(Arrays.compare(new int[] {1}, new String[] {"a"}));
A

this code does not compile because the types are different. When comparing two arrays, they must be the same array type.

110
Q

mismatch()

A

If the arrays are equal, mismatch() **returns -1. **
Otherwise, it returns the first index where they differ.

111
Q
System.out.println(Arrays.mismatch(new int[] {1}, new int[] {1}));
System.out.println(Arrays.mismatch(new String[] {"a"},
new String[] {"A"}));
System.out.println(Arrays.mismatch(new int[] {1, 2}, new int[] {1}));
A
System.out.println(Arrays.mismatch(new int[] {1}, new int[] {1})); //-1
System.out.println(Arrays.mismatch(new String[] {"a"},
new String[] {"A"})); //0
System.out.println(Arrays.mismatch(new int[] {1, 2}, new int[] {1})); //1
112
Q

Equality vs. comparison vs. mismatch

A
  1. equals(), return true when arrays are same, return false when arrays are different
  2. compare(), return 0 when arrays are same, return Positive or negative number when arrays are different
  3. mismatch(), return -1 when arrays are same, return Zero or positive index when arrays are different.
113
Q

VARARGS

A

varargs (variable arguments)

you can use a variable defined using varargs as if it were a normal array. For example, args.length and args[0] are legal.

public static void main(String... args) // varargs
114
Q

MULTIDIMENSIONAL ARRAYS

A

arrays hold other arrays

115
Q

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

A

The first two examples are nothing surprising and declare a two-dimensional (2D) array.

The third example also declares a 2D array.

The final example declares two arrays on the same line. Adding up the brackets, we see that the vars4 is a 2D array and space is a 3D array.

116
Q

You can specify the size of your multidimensional array in the declaration if you like:
~~~
String [][] rectangle = new String[3][2];
~~~

A

The result of this statement is an array rectangle with three elements, each of which refers to an array of two elements. You can think of the addressable range as [0][0] through [2][1], but don’t think of it as a structure of addresses like [0,0] or [2,1].

117
Q

Now suppose we set one of these values:
~~~
rectangle[0][1] = “set”;
~~~

A
118
Q
int[][] differentSizes = {{1, 4}, {3}, {9,8,7}};
A
119
Q
int [][] args = new int[4][];
args[0] = new int[5];
args[1] = new int[3];
A
120
Q

Using a Multidimensional Array

A
int[][] twoD = new int[3][2];
for (int i = 0; i < twoD.length; i++) {
    for (int j = 0; j < twoD[i].length; j++)
        System.out.print(twoD[i][j] + " "); // print element
    System.out.println(); // time for a new row
}

for (int[] inner : twoD) {
    for (int num : inner)
        System.out.print(num + " ");
    System.out.println();
}
121
Q

Understanding an ArrayList

A

an ArrayList can change capacity at runtime as needed.

Like an array, an ArrayList is an ordered sequence that allows duplicates.

ArrayList requires an import.
~~~
import java.util.*; // import whole package
import java.util.ArrayList; // import just ArrayList
~~~

122
Q

CREATING AN ARRAYLIST

A

there are three ways to create an ArrayList:
~~~
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList(10);
ArrayList list3 = new ArrayList(list2);
~~~

The first says to create an ArrayList containing space for the default number of elements but not to fill any slots yet.

The second says to create an ArrayList containing a specific number of slots, but again not to assign any.

The final example tells Java that we want to make a copy of another ArrayList. We copy both the size and contents of that ArrayList. Granted, list2 is empty in this example, so it isn’t particularly interesting.

123
Q

You also need to know the new and improved way.
Java 5 introduced generics, which allow you to specify the type of class that the ArrayList will contain.
~~~
ArrayList<String> list4 = new ArrayList<String>();
ArrayList<String> list5 = new ArrayList<>();
~~~</String></String></String>

Java 5 allows you to tell the compiler what the type would be by specifying it between < and >. Starting in Java 7, you can even omit that type from the right side. The < and > are still required, though.

A
124
Q

<>

A

This is called the diamond operator because <> looks like a diamond.

125
Q

USING VAR WITH ARRAYLIST
~~~
var strings = new ArrayList<String>();
strings.add("a");
for (String s: strings) { }
~~~</String>

A

The type of var is ArrayList<String>. This means you can add a String or loop through the String objects.

126
Q
var list = new ArrayList<>();
A

Believe it or not, this does compile. The type of the var is ArrayList<Object>. Since there isn’t a type specified for the generic, Java has to assume the ultimate superclass. This is a bit silly and unexpected, so please don’t write this. But if you see it on the exam, you’ll know what to expect.

127
Q
var list = new ArrayList<>();
list.add("a");
for (String s: list) { } // DOES NOT COMPILE
A

The type of var is ArrayList<Object>. Since there isn’t a type in the diamond operator, Java has to assume the most generic option it can.
Therefore, it picks Object, the ultimate superclass. Adding a String to the list is fine. You can add any subclass of Object. However, in the loop, we need to use the Object type rather than String.

128
Q
List<String> list6 = new ArrayList<>();
ArrayList<String> list7 = new List<>(); // DOES NOT COMPILE
A

ArrayList implements an interface called List.

In other words, an ArrayList is a List.
You will learn about interfaces later in the book. In the meantime, just know that you can store an ArrayList in a List reference variable but not vice versa. The reason is that List is an interface and interfaces can’t be instantiated.

129
Q

USING AN ARRAYLIST

A
130
Q

Before reading any further, you are going to see something new in the method signatures: a “class” named E. Don’t worry—it isn’t really a class. E is used by convention in generics to mean “any class that this array can hold.” If you didn’t specify a type when creating the ArrayList, E means Object. Otherwise, it means the class you put between < and >.

You should also know that ArrayList implements toString(), so you can easily see the contents just by printing it. Arrays do not produce such pretty output by default.

A
131
Q
boolean add(E element)
void add(int index, E element)
A

The add() methods insert a new value in the ArrayList.
Don’t worry about the boolean return value. It always returns true.

132
Q
ArrayList list = new ArrayList();
list.add("hawk"); // [hawk]
list.add(Boolean.TRUE); // [hawk, true]
System.out.println(list); // [hawk, true]
A

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. It may not have been
what we intended, but the compiler doesn’t know that.

133
Q
ArrayList<String> safer = new ArrayList<>();
safer.add("sparrow");
safer.add(Boolean.TRUE); // DOES NOT COMPILE
A

This time the compiler knows that only String objects are allowed in and prevents the attempt to add a Boolean.

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

When a question has code that adds objects at indexed positions, draw it so that you won’t lose track of which value is at which index. In this example, line 5 adds “hawk” to the end of birds. Then line 6 adds “robin” to index 1 of birds, which happens to be the end. Line 7 adds “blue jay” to index 0, which happens to be the beginning of birds. Finally, line 8 adds “cardinal” to index 1, which is now near the middle of birds.

135
Q
boolean remove(Object object)
E remove(int index)
A

The remove() methods remove the first matching value in the ArrayList or remove the element at a specified index.

This time the boolean return value tells us whether a match was removed.

The E return type is the element that actually got removed.

136
Q
3: List<String> birds = new ArrayList<>();
4: birds.add("hawk"); // [hawk]
5: birds.add("hawk"); // [hawk, hawk]
6: System.out.println(birds.remove("cardinal")); // prints false
7: System.out.println(birds.remove("hawk")); // prints true
8: System.out.println(birds.remove(0)); // prints hawk
9: System.out.println(birds); // []
A
3: List<String> birds = new ArrayList<>();
4: birds.add("hawk"); // [hawk]
5: birds.add("hawk"); // [hawk, hawk]
6: System.out.println(birds.remove("cardinal")); // prints false
7: System.out.println(birds.remove("hawk")); // prints true
8: System.out.println(birds.remove(0)); // prints hawk
9: System.out.println(birds); // []
  • 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.
137
Q
E set(int index, E newElement)
A

The set() method changes one of the elements of the ArrayList without changing the size.

The E return type is the element that got replaced.

138
Q
15: List<String> birds = new ArrayList<>();
16: birds.add("hawk"); // [hawk]
17: System.out.println(birds.size()); // 1
18: birds.set(0, "robin"); // [robin]
19: System.out.println(birds.size()); // 1
20: birds.set(1, "robin"); // IndexOutOfBoundsException
A
  • Line 16 adds one element to the array, making the size 1.
  • Line 18 replaces that one element, and the size stays at 1.
  • Line 20 tries to replace an element that isn’t in the ArrayList. Since the size is 1, the only valid index is 0. Java throws an exception because this isn’t allowed.
139
Q
boolean isEmpty()
int size()
A

The isEmpty() and size() methods look at how many of the slots are in use.

140
Q
List<String> birds = new ArrayList<>();
System.out.println(birds.isEmpty()); // true
System.out.println(birds.size()); // 0
birds.add("hawk"); // [hawk]
birds.add("hawk"); // [hawk, hawk]
System.out.println(birds.isEmpty()); // false
System.out.println(birds.size()); // 2
A

At the beginning, birds has a size of 0 and is empty.
It has a capacity that is greater than 0.

However, as with StringBuilder, we don’t use the capacity in determining size or length. After adding elements, the size becomes positive, and it is no longer empty. Notice how isEmpty() is a convenience method for size() == 0.

141
Q
void clear()
A

The clear() method provides an easy way to discard all elements of the ArrayList.

142
Q
List<String> birds = new ArrayList<>();
birds.add("hawk"); // [hawk]
birds.add("hawk"); // [hawk, hawk]
System.out.println(birds.isEmpty()); // false
System.out.println(birds.size()); // 2
birds.clear(); // []
System.out.println(birds.isEmpty()); // true
System.out.println(birds.size()); // 0
A

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

143
Q
boolean contains(Object object)
A

The contains() method checks whether a certain value is in the ArrayList.

144
Q
List<String> birds = new ArrayList<>();
birds.add("hawk"); // [hawk]
System.out.println(birds.contains("hawk")); // true
System.out.println(birds.contains("robin")); // false
A
145
Q
boolean equals(Object object)
A

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

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

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.

147
Q

WRAPPER CLASSES

A

Each primitive type has a wrapper class, which is an object type that corresponds to the primitive.

148
Q

Wrapper classes

A
  1. boolean, Boolean, Boolean.valueOf(true)
  2. byte, Byte, Byte.valueOf((byte) 1)
  3. short, Short, Short.valueOf((short) 1)
  4. int, Integer, Integer.valueOf(1)
  5. long, Long, Long.valueOf(1)
  6. float, Float, Float.valueOf((float)1.0)
  7. double, Double, Double.valueOf(1.0)
  8. char, Character, Character.valueOf('c')
149
Q

Each wrapper class also has a constructor. It works the same way as valueOf() but isn’t recommended for new code. The valueOf() allows object caching. Remember how a String could be shared when the value is the same? The wrapper classes are immutable and take advantage of some caching as well.

A
150
Q

The wrapper classes also have a method that converts back to a primitive. You don’t need to know much about the valueOf() or intValue() type methods for the exam because autoboxing has removed the need for them

A
151
Q

There are also methods for converting a String to a primitive or wrapper class. You do need to know these methods. The parse methods, such as parseInt(), return a primitive, and the valueOf() method returns a wrapper class. This is easy to remember because the name of the returned primitive is in the method name.

A
int primitive = Integer.parseInt("123");
Integer wrapper = Integer.valueOf("123");
152
Q
int primitive = Integer.parseInt("123");
Integer wrapper = Integer.valueOf("123");
A
  • The first line converts a String to an int primitive.
  • The second converts a String to an Integer wrapper class.
  • If the String passed in is not valid for the given type, Java throws an exception.
153
Q

If the String passed in is not valid for the given type, Java throws an exception.

A

ex:
~~~
int bad1 = Integer.parseInt(“a”); // throws NumberFormatException
Integer bad2 = Integer.valueOf(“123.45”); // throws
NumberFormatException
~~~

154
Q

Character class doesn’t participate in the parse/valueOf methods. Since a String consists of characters, you can just call charAt() normally.

A
155
Q

lists the methods you need to recognize for creating a primitive or wrapper class object from a String.

A

Boolean
~~~
Boolean.parseBoolean(“true”)
Boolean.valueOf(“TRUE”)
~~~

Byte
~~~
Byte.parseByte(“1”)
Byte.valueOf(“2”)
~~~

Short
~~~
Short.parseShort(“1”)
Short.valueOf(“2”)
~~~

Integer
~~~
Integer.parseInt(“1”)
Integer.valueOf(“2”)
~~~

Long
~~~
Long.parseLong(“1”)
Long.valueOf(“2”)
~~~

Float
~~~
Float.parseFloat(“1”)
Float.valueOf(“2.2”)
~~~

Double
~~~
Double.parseDouble(“1”)
Double.valueOf(“2.2”)
~~~

Character
~~~
None
None
~~~

156
Q

WRAPPER CLASSES AND NULL

A

numeric primitives could not be used to store null values.
One advantage of a wrapper class over a primitive is that because it’s an object, it can be used to store a null value.
For example, if you are storing a user’s location data using (latitude,longitude), it would be a bad idea to store a missing point as (0,0) since that refers to an actual location off the coast of Africa where the user could theoretically be.

157
Q

AUTOBOXING AND UNBOXING

A

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

The reverse conversion of wrapper class to primitive
value is called unboxing.

158
Q
3: List<Integer> weights = new ArrayList<>();
4: Integer w = 50;
5: weights.add(w); // [50]
6: weights.add(Integer.valueOf(60)); // [50, 60]
7: weights.remove(new Integer(50)); // [60]
8: double first = weights.get(0); // 60.0
A

Line 4 autoboxes the int primitive into an Integer object, and line 5 adds that to the List.

Line 6 shows that you can still write code the long way and pass in a wrapper object.

Line 8 retrieves the first Integer in the list, unboxes it as a primitive and implicitly casts it to double.

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

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.

160
Q

What do you think happens if you try to unbox a null?

A

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.

161
Q

What do you think this code outputs?
~~~
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.remove(1);
System.out.println(numbers);
~~~</Integer>

A

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 1, you can write numbers.remove(new Integer(1)) to force wrapper class use.

162
Q

CONVERTING BETWEEN ARRAY AND LIST

A

List to Array:
~~~
16: Object[] objectArray = list.toArray();
17: String[] stringArray = list.toArray(new String[0]);
~~~

Array to List:
1. One option is to create a List that is linked to the original array. When a change is made to one, it is available in the other. It is a fixed-size list and is also known as a backed List because the array changes with it.
1. Another option is to create an immutable List. That means you cannot change the values or the size of the List. You can change the original array, but changes will not be reflected in the immutable List.

163
Q
13: List<String> list = new ArrayList<>();
14: list.add("hawk");
15: list.add("robin");
16: Object[] objectArray = list.toArray();
17: String[] stringArray = list.toArray(new String[0]);
18: list.clear();
19: System.out.println(objectArray.length); // 2
20: System.out.println(stringArray.length); // 2
A

Line 16 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 17 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.

Also, notice that line 18 clears the original List. This does not affect either array. The array is a newly created object with no relationship to the original List. It is simply a copy.

164
Q
20: String[] array = { "hawk", "robin" }; // [hawk, robin]
21: List<String> list = Arrays.asList(array); // returns fixed size list
22: System.out.println(list.size()); // 2
23: list.set(1, "test"); // [hawk, test]
24: array[0] = "new"; // [new, test]
25: System.out.print(Arrays.toString(array));// [new, test]
26: list.remove(1); // throws UnsupportedOperationException
A

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.

165
Q
32: String[] array = { "hawk", "robin" }; // [hawk, robin]
33: List<String> list = List.of(array); // returns immutable list
34: System.out.println(list.size()); // 2
35: array[0] = "new";
36: System.out.println(Arrays.toString(array)); // [new, robin]
37: System.out.println(list); // [hawk, robin]
38: list.set(1, "test"); // throws UnsupportedOperationException
A

Line 33 creates the immutable List. It contains the two values that array happened to contain at the time the List was created.

On line 35, there is a change to the array.

Line 36 shows that array has changed.

Line 37 shows that list still has the original values. This is because it is an immutable copy of the original array.

Line 38 shows that changing a list value in an immutable list is not allowed.

166
Q

USING VARARGS TO CREATE A LIST

A
List<String> list1 = Arrays.asList("one", "two");
List<String> list2 = List.of("one", "two");
167
Q
List<String> list1 = Arrays.asList("one", "two");
List<String> list2 = List.of("one", "two");
A

Both of these methods take varargs, which let you pass in an array or just type out the String values. This is handy when testing because you can easily create and populate a List on one line.
Both methods create fixed-size arrays.

If you will need to later add or remove elements, you’ll still need to create an ArrayList using the constructor.

168
Q

Array and list conversions

A

toArray()
* List to Array
* No allowed to remove values from created object
* Allowed to change values in the created object
* Changing values in the created object do not affects the original or vice versa.

Arrays.asList()
* Array (or varargs) to List
* No allowed to remove values from created object
* Allowed to change values in the created object
* Changing values in the created object affects the original or vice versa.

List.of()
* Array (or varargs) to List
* No allowed to remove values from created object
* No allowed to change values in the created object
* Changing values in the created object affects the original or vice versa. (N/A)

Notice that none of the options allows you to change the number of elements. If you want to do that, you’ll need to actually write logic to create the new object.

169
Q

Notice that none of the options allows you to change the number of elements. If you want to do that, you’ll need to actually write logic to create the new object. Here’s an example:

A
List<String> fixedSizeList = Arrays.asList("a", "b", "c");
List<String> expandableList = new ArrayList<>(fixedSizeList);
170
Q

Sorting an ArrayList is similar to sorting an array.

A
List<Integer> numbers = new ArrayList<>();
numbers.add(99);
numbers.add(5);
numbers.add(81);
Collections.sort(numbers);
System.out.println(numbers); // [5, 81, 99]
171
Q
A
172
Q

Creating Sets and Maps

A
173
Q

INTRODUCING SETS

A

A Set is a collection of objects that cannot contain duplicates.

174
Q

All the methods you learned for ArrayList apply to a Set with the exception of those taking an index as a parameter.

A

Set isn’t ordered

can call other methods like add(value) or remove(value).

add() when trying to add a duplicate value, the method returns false and does not add the value.

175
Q

There are two common classes that implement Set that you might see on the exam. HashSet is the most common. TreeSet is used when sorting is important.

A
176
Q
3: Set<Integer> set = new HashSet<>();
4: System.out.println(set.add(66)); // true
5: System.out.println(set.add(66)); // false
6: System.out.println(set.size()); // 1
7: set.remove(66);
8: System.out.println(set.isEmpty()); // true
A

Line 3 creates a new set that declares only unique elements are allowed.
Both lines 4 and 5 attempt to add the same value. Only the first one is allowed, making line 4 print true and line 5 false.

Line 6 confirms there is only one value in the set.

Removing an element on line 7 works normally, and the set is empty on line 8.

177
Q

INTRODUCING MAPS

A

A Map uses a key to identify values.
The most common implementation of Map is HashMap. Some of the methods are the same as those in ArrayList like clear(), isEmpty(), and size().

178
Q

Common Map methods

A
V get(Object key)

Returns the value mapped by key or null if none is mapped.

V getOrDefault(Object key, V other)
Returns the value mapped by key or other if none is mapped

V put(K key, V value)
Adds or replaces key/value pair. Returns previous value or null

V remove(Object key)
Removes and returns value mapped to key. Returns null if none

boolean containsKey(Object key)
Returns whether key is in map

boolean containsValue(Object value)
**Returns whether value is in map **

Set<K> keySet()
Returns set of all keys

Collection<V> values()

Returns Collection of all values

179
Q
8: Map<String, String> map = new HashMap<>();
9: map.put("koala", "bamboo");
10: String food = map.get("koala"); // bamboo
11: String other = map.getOrDefault("ant", "leaf"); // leaf
12: for (String key: map.keySet())
13: System.out.println(key + " " + map.get(key)); // koala bamboo
A

In this example, we create a new map and store one key/value pair inside. Line 10 gets this value by key. Line 11 looks for a key that isn’t there, so it returns the second parameter leaf as the default value. Lines 12 and 13 list all the key and value pairs.

180
Q

Calculating with Math APIs

A
  1. MIN() AND MAX()
  2. ROUND()
  3. POW()
  4. RANDOM()
181
Q
double min(double a, double b)
float min(float a, float b)
int min(int a, int b)
long min(long a, long b)
A

The min() and max() methods compare two values and return one of them.

There are four overloaded methods, so you always have an API available with the same type. Each method returns whichever of a or b is smaller.
The max() method works the same way except it returns the larger value.

182
Q
int first = Math.max(3, 7); // 7
int second = Math.min(7, -9); // -9
A

The first line returns 7 because it is larger. The second line returns -9 because it is smaller.
Remember from school that negative values are smaller than positive ones.

183
Q
long round(double num)
int round(float num)
A

The round() method gets rid of the decimal portion of the value, choosing the next higher number if appropriate. If the fractional part is .5 or higher, we round up.

There are two overloaded methods to ensure there is enough room to store a rounded double if needed.

184
Q
long low = Math.round(123.45); // 123
long high = Math.round(123.50); // 124
int fromFloat = Math.round(123.45f); // 123
A

The first line returns 123 because .45 is smaller than a half.

The second line returns 124 because the fractional part is just barely a half.

The final line shows that an explicit float triggers the method signature that returns an int.

185
Q
double pow(double number, double exponent)
A

The pow() method handles exponents. As you may recall from your elementary school math class, 32 means three squared. This is 3 * 3 or 9.
Fractional exponents are allowed as well. Sixteen to the .5 power means the square root of 16, which is 4. (Don’t worry, you won’t have to do square roots on the exam.)

186
Q
double squared = Math.pow(5, 2); // 25.0
A

Notice that the result is 25.0 rather than 25 since it is a double. (Again, don’t worry, the exam won’t ask you to do any complicated math.)

187
Q
double random()
A

The random() method returns a value greater than or equal to 0 and less than 1.

188
Q

double num = Math.random();

A

Since it is a random number, we can’t know the result in advance. However, we can rule out certain numbers. For example, it can’t be negative because that’s less than 0. It can’t be 1.0 because that’s not less than 1.

189
Q

String

A
  1. Strings are immutable sequences of characters.
  2. The new operator is optional.
  3. The concatenation operator (+) creates a new String with the content of the first String followed by the content of the second String.
  4. If either operand involved in the + expression is a String, concatenation is used; otherwise, addition is used.
  5. String literals are stored in the string pool.
  6. The String class has many methods.
190
Q

StringBuilders

A
  1. StringBuilders are mutable sequences of characters.
  2. Most of the methods return a reference to the current object to allow method chaining.
  3. The StringBuilder class has many methods.
  4. Calling == on String objects will check whether they point to the same object in the pool.
  5. Calling == on StringBuilder references will check whether they are pointing to the same StringBuilder object.
  6. Calling equals() on String objects will check whether the sequence of characters is the same.
  7. Calling equals() on StringBuilder objects will check whether they are pointing to the same object rather than looking at the values inside.
191
Q

Array

A
  1. An array is a fixed-size area of memory on the heap that has space for primitives or pointers to objects.
  2. You specify the size when creating it—for example, int[] a = new int[6];.
  3. Indexes begin with 0, and elements are referred to using a[0].
  4. The Arrays.sort() method sorts an array.
  5. Arrays.binarySearch() searches a sorted array and returns the index of a match. If no match is found, it negates the position where the element would need to be inserted and subtracts 1.
  6. Arrays.compare() and Arrays .mismatch() check whether two arrays are the equivalent.
  7. Methods that are passed varargs (…) can be used as if a normal array was passed in.
  8. In a multidimensional array, the second-level arrays and beyond can be different sizes.
192
Q
A
193
Q

ArrayList

A
  1. An ArrayList can change size over its life.
  2. It can be stored in an ArrayList or List reference.
  3. Generics can specify the type that goes in the ArrayList.
  4. Although an ArrayList is not allowed to contain primitives, Java will autobox parameters passed in to the proper wrapper type.
  5. Collections.sort() sorts an ArrayList.
194
Q

Set

A

A Set is a collection with unique values. A Map consists of key/value pairs.

195
Q

Math API

A

The Math class provides many static methods to facilitate programming.