Chapter 5 Flashcards

1
Q

Which are immutable: String, StringBuilder, StringBuffer, arrays, or ArrayList?

A

String is the only immutable class in the list.

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

What are two ways to create a String object?

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

What interfaces does String implement?

A

Serializable, CharSequence, Comparable

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

What package is String part of?

A

java.lang

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

What are the rules for 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 from left to right.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Name as many important String methods as you can (answer contains only methods relevant for OCP exam)

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

What does the String method length() do?

A

returns the length of the string, where the first number is 1.

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

What does the String method charAt() do?

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

What does the String method indexOf() do?

A

The method indexOf() looks at the characters in the string and finds the first index that matches the value.

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

What does String.indexOf() return?

ex: “test”.indexOf(“z”);

A

The method returns -1.

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

What does String.indexOf() return?

ex: “test”.indexOf(“es”);

A

1

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

What does String.indexOf() return?

ex: “animals”.indexOf(‘a’);

A

0.

note: characters can be passed as an argument.

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

What can be passed as a second argument of the String method indexOf()?

A

An index that indicates where to start the search.

ex: “animals”.indexOf(‘a’, 4); // returns 4

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

What will happen when this code is executed?

“test”.charAt(4);

A

It throws a StringIndexOutOfBoundsException.

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

What will happen when this code is executed?

“animals”.indexOf(“al”, 5);

A

It returns -1 (cannot find a match)

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

What does the String method substring() do?

A

The method substring() looks for characters in a string and returns part of the string. The first parameter is the index to start with for the returned string.

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

The String method substring takes two arguments. Is the second argument inclusive in the search?

A

No.

ex: “animals”.substring(3, 4); // returns m

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

What will happen when this code is executed?

“animals”.substring(3, 3);

A

Returns an empty string

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

What will happen when this code is executed?

“animals”.substring(3, 2);
or
“animals”.substring(3, 8);

A

Throws an exception.

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

is the String method equals() case sensitive?

A

yes

To use equals without case sensitivity, use the method equalsIgnoreCase().

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

What will happen when this code is executed?

“abc”.equals(“ABC”);

A

It returns false. Equals is case sensitive.

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

What will happen when this code is executed?

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

A

It returns “AbcAbc”

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

What do the strip() and trim() string methods do?

A

They remove whitespace from the beginning and end of a string.

Whitespace includes \t (tab, \n (newline) and \r (carriage return).

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

What do the string methods stripLeading() and stripTrailing() do?

A

stripLeading() removes whitespace from the beginning and stripTrailing() removes whitespace at the end of a string.

Whitespace includes \t (tab, \n (newline) and \r (carriage return).

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

What does the string method intern() do?

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

What is the following technique called?
(bonus: how many objects are created?)

String result = “AniMal “.trim().toLowerCase().replace(‘a’, ‘A’);

A

The technique is called method chaining.

Bonus answer: 4 objects

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

Why should we use Stringbuilder instead of String?

A

Stringbuilder is mutable, whereas Strings are immutable. If we need to work on a piece of String, it might be better to use a StringBuilder to avoid the creation of many objects.

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

What are the options to construct a StringBuilder?

A
Stringbuilder b1 = new StringBuilder();
Stringbuilder b2 = new StringBuilder("animal");
Stringbuilder b3 = new StringBuilder(10);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is the difference between StringBuilder and StringBuffer?

A

StringBuffer is thread-safe. StringBuilder is faster.

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

What is an easy way to reverse a String?

A

Convert it to a StringBuilder and call the reverse() method.

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

How do we convert a StringBuilder object to a String object?

A

By calling the toString() method.

32
Q

Does StringBuilder implement the method equals()?

A

No.

If you call equals() on two StringBuilder instances, it will check for reference equality. To check for equality, convert it to String first.

33
Q

Why does the following code not compile?

String string = "a";
StringBuilder builder = new StringBuilder("a");
System.out.println(string == builder);
A

The compiler is smart enough to know that two references to two different type of objects can never return true.

34
Q

What is the string pool (also known as intern pool)?

A

The string pool is a location in the Java Virtual Machine where common strings are collected such that they can be reused in order to save memory space.

35
Q

What kinds of strings are stored in the string pool?

A

Literal strings and constants.

If your program contains literal strings or constants, they are stored in the string pool.

36
Q

What will happen when this code is executed?

String x = “Hello world”;
String y = “Hello world”;
System.out.println(x == y);

A

It prints true.

Literal strings and constants are stored in the string pool (and therefore point to the same location in memory).

37
Q

What will happen when this code is executed?

String x = “Hello world”;
String y = “ Hello world”.trim();
System.out.println(x == y);

A

It prints false.

Even though x and y evaluate to the same string, it is computed at run-time. Since it isn’t the same at compile-time, a new String object is created.

38
Q

How do we force to use a string from a string pool, if it exists?

A

By calling the intern() method of a string.

39
Q

What are valid ways to declare an array?

A
int[] numbers = new int[1];
int[] numbers = new int[] {42, 55};
int[] numbers = {42, 55};
int [] numbers = ...
int []numbers = ...
int numbers[] = ...
int numbers [] = ...
40
Q

What is the following type of array called?

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

A

Anonymous array

41
Q

What type of reference variable does the following code create?

int[] ids, types;

A

Two variables of type int[].

42
Q

What type of reference variable does the following code create?

int ids[], types;

A

One variable of type int[] (ids), one variable of type int.

page 184,185

43
Q

How do we print the contents of an array in a human-readable way?

A

Arrays.toString(arrayHere);

44
Q

Arrays is a class provided by Java that requires an import. What package does it reside in?

A

java.util

45
Q

How can we sort an array? Class & method

A

Using the Arrays.sort() method.

46
Q

How can we search an array?

A

Using Arrays.binarySearch().

Requires the array to be sorted.

47
Q

What does Arrays.binarySearch() return when an element is not found?

A

It returns the negative value showing one smaller than the negative of the index where a match needs to be inserted to preserve sorted order.

48
Q

What does Arrays.binarySearch() return when the argument array is not sorted?

A

The answer will be unpredictable.

49
Q

How can we compare an array?

A

Using the equals(), Arrays.compare() or the Arrays.mismatch() method.

50
Q

What are the return value rules for Arrays.compare()?

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.

51
Q

Does this compile?

Arrays.compare(new int[] {1}, new String[] {“a”});

A

No. They must be of the same type.

52
Q

What does Arrays.mismatch() do?

A

Arrays.mismatch() is familiar to compare(). If the arrays are equal, mismatch() returns -1. Otherwise it returns the first index where they differ.

53
Q

What does the following code return?

Arrays.mismatch(new int[] {1, 2}, new int[] {1});

A

It returns 1.

The element at index 1 of the second array is not equal the first array.

54
Q

What is the benefit of an Arraylist over an array?

A

Just like a StringBuilder, an Arraylist can change capacity at runtime if needed.

55
Q

What package does ArrayList reside in?

A

java.util

56
Q

What are three ways to instantiate an ArrayList?

A
new ArrayList();
new ArrayList(10);
new ArrayList(otherList); //shallow copy other list
57
Q

Why does

var list = new ArrayList<>();

compile? and what type is it?

A

The type of the var is ArrayList. Since there isn’t a type specified for the generic, Java assumed the ultimate superclass (Object).

58
Q

What is a wrapper class?

A

A wrapper class is an object type that corresponds to a primitive.

59
Q

What is the advantage of calling the Wrapper class method valueOf() over using the constructor?

ex: Long.valueOf(1)

A

the valueOf() method allows object caching (like the String pool)

60
Q

Given the following String “123”

Which Wrapper class method can we use to make it into an int and which method can we use to make it into an Integer?

A

Integer.parseInt(“123”) returns a primitive

Integer.valueOf(“123”) returns a Wrapper object

61
Q

Explain what autoboxing and unboxing is

A

Autoboxing is the conversion of primitive to corresponding wrapper class.

Unboxing is the conversion of wrapper class to primitive.

Java does this automatically for you.

62
Q

What happens when you try to unbox a null value?

A

Java will throw a NullPointerException

63
Q

How do we convert a list to an array? (2 options)

A

list. toArray(); //returns Object[] array

list. toArray(new String[0]); //returns String[] array

64
Q

How do we convert an array to a list?

A

Arrays.asList(array); // returns fixed sized list

List.of(array); //returns immutable list

65
Q

What happens when you want to change a value in an immutable list?

A

It throws a UnsupportedOperationException

66
Q

How do we create a list using varargs? (two options)

A

Arrays.asList(“one”, “two”);

List.of(“one”, “two”);

67
Q

What is the difference between Arrays.asList() and List.of()?

A

With Arrays.asList() it is allowed to change values in the created object.

With Arrays.asList() changing values in the created object affects the original or vice versa.

68
Q

What happens when trying to add an item to a set that already contains that item?

A

It returns false.

69
Q

What are two common implementations of Set?

A

HashSet and TreeSet

70
Q

When is TreeSet more important than Hashset?

A

When sorting is important

71
Q

What is the most common implementation of Map?

A

HashMap

72
Q

What are common Math methods?

A
  • min() and max()
  • round()
  • pow()
  • random()
73
Q

What is the difference between the equals method and the == operator?

A

== checks object equality.

equals() depends on the implementation of the object it is being called on. For Strings, equals() checks the characters inside of it.

74
Q

What is the result of the following?

List hex = Arrays.asList(“30”, “8”, “3A”, “FF”);
Collections.sort(hex);

int x = Collections.binarySearch(hex, “8”);
int y = Collections.binarySearch(hex, “3A”);
int z = Collections.binarySearch(hex, “4F”);

System.out.println(x + “ “ + y + “ “ + z);

A. 0 1 -2
B. 0 1 -3
C. 2 1 -2
D. 2 1 -3
E. None of the above.
F. The code doesn't compile.
A

D.

After sorting, hex contains [30, 3A, 8, FF].
Remember that numbers sort before letters and strings sort alphabetically.
This makes 30 come before 8.
A binary search correctly finds 8 at index 2 and 3A at index 1.
It cannot find 4F but notices it should be at index 2.
The rule when an item isn’t found is to negate that index and subtract 1.
Therefore, we get -2-1, which is -3.

75
Q

What is the result of the following code?

12: int count = 0;
13: String s1 = “java”;
14: String s2 = ”java”;
15: StringBuilder s3 = new StringBuilder(“java”);
16: if (s1 == s2) count++;
17: if (s1.equals(s2)) count++;
18: if (s1 == s3) count++;
19: if (s1.equals(s3)) count++;
20: System.out.println(count);

A. 0
B. 1
C. 2
D. 3
E. 4
F. An exception is thrown
G. The code does not compile
A

G.

The question is trying to distract you into paying attention to logical equality versus object reference equality. The exam creators are hoping you will miss the fact that line 18 does not compile. Java does not allow you to compare String and StringBuilder using ==.

76
Q

What is the result of the following code?

public class Lion {
    public void roar(String roar1, StringBuilder roar2) {
      roar1.concat("!!!");
      roar2.append("!!!");
    }
public static void main(String[] args) {
      String roar1 = "roar";
      StringBuilder roar2 = new StringBuilder("roar");
      new Lion().roar(roar1, roar2);
      System.out.println(roar1 + " " + roar2);
    }
}
A. roar roar
B. roar roar!!!
C. roar!l! roar
D. roar!!! roar!!!
E. An exception is thrown.
F. The code does not compile.
A

B.

A String is immutable. Calling concat() returns a new String but does not change the original. A StringBuilder is mutable. Calling append() adds characters to the existing character sequence along with returning a reference to the same object.

77
Q

Which of the following return the number 5 when run independently? (Choose all that apply.)

var string = "12345"; 
var builder = new StringBuilder("12345"); 
A. builder.charAt(4) 
B. builder.replace(2, 4, "6").charAt(3) 
C. builder.replace(2, 5, "6").charAt(2) 
D. string.charAt(5) 
E. string.length 
F. string.replace("123", "1").charAt(2) 
G. None of the above
A

A, B, F.

Remember that indexes are zero-based, which means that index 4 corresponds to 5 and option A is correct. For option B, the replace () method starts the replacement at index 2 and ends before index 4. This means two characters are replaced, and charAt (3) is called on the intermediate value of 1265. The character at index 3 is 5, making option B correct. Option C is similar, making the intermediate value 126 and returning 6. Option D results in an exception since there is no character at index 5. Option E is incorrect. It does not compile because the parentheses for the length () method are missing. Finally, option F’s replace results in the intermediate value 145. The character at index 2 is 5, so option F is correct.