Chapter 5 Flashcards
Which are immutable: String, StringBuilder, StringBuffer, arrays, or ArrayList?
String is the only immutable class in the list.
What are two ways to create a String object?
String name = "Fluffy"; String name = new String("Fluffy");
What interfaces does String implement?
Serializable, CharSequence, Comparable
What package is String part of?
java.lang
What are the rules for concatenation?
- If both operands are numeric, + means numeric addition.
- If either operand is a String, + means concatenation.
- The expression is evaluated from left to right.
Name as many important String methods as you can (answer contains only methods relevant for OCP exam)
- length()
- charAt()
- indexOf()
- substring()
- toLowerCase() & toUpperCase()
- equals() & equalsIgnoreCase()
- startsWith() & endsWith()
- replace()
- contains()
- trim() & strip() & stripLeading(), and stripTailing()
- intern()
What does the String method length() do?
returns the length of the string, where the first number is 1.
What does the String method charAt() do?
The method charAt() lets you query the string to find out what character is at a specific index.
What does the String method indexOf() do?
The method indexOf() looks at the characters in the string and finds the first index that matches the value.
What does String.indexOf() return?
ex: “test”.indexOf(“z”);
The method returns -1.
What does String.indexOf() return?
ex: “test”.indexOf(“es”);
1
What does String.indexOf() return?
ex: “animals”.indexOf(‘a’);
0.
note: characters can be passed as an argument.
What can be passed as a second argument of the String method indexOf()?
An index that indicates where to start the search.
ex: “animals”.indexOf(‘a’, 4); // returns 4
What will happen when this code is executed?
“test”.charAt(4);
It throws a StringIndexOutOfBoundsException.
What will happen when this code is executed?
“animals”.indexOf(“al”, 5);
It returns -1 (cannot find a match)
What does the String method substring() do?
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.
The String method substring takes two arguments. Is the second argument inclusive in the search?
No.
ex: “animals”.substring(3, 4); // returns m
What will happen when this code is executed?
“animals”.substring(3, 3);
Returns an empty string
What will happen when this code is executed?
“animals”.substring(3, 2);
or
“animals”.substring(3, 8);
Throws an exception.
is the String method equals() case sensitive?
yes
To use equals without case sensitivity, use the method equalsIgnoreCase().
What will happen when this code is executed?
“abc”.equals(“ABC”);
It returns false. Equals is case sensitive.
What will happen when this code is executed?
“abcabc”.replace(‘a’, ‘A’);
It returns “AbcAbc”
What do the strip() and trim() string methods do?
They remove whitespace from the beginning and end of a string.
Whitespace includes \t (tab, \n (newline) and \r (carriage return).
What do the string methods stripLeading() and stripTrailing() do?
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).
What does the string method intern() do?
The intern() method returns the value from the string pool if it is there. Otherwise, it adds the value to the string pool.
What is the following technique called?
(bonus: how many objects are created?)
String result = “AniMal “.trim().toLowerCase().replace(‘a’, ‘A’);
The technique is called method chaining.
Bonus answer: 4 objects
Why should we use Stringbuilder instead of String?
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.
What are the options to construct a StringBuilder?
Stringbuilder b1 = new StringBuilder(); Stringbuilder b2 = new StringBuilder("animal"); Stringbuilder b3 = new StringBuilder(10);
What is the difference between StringBuilder and StringBuffer?
StringBuffer is thread-safe. StringBuilder is faster.
What is an easy way to reverse a String?
Convert it to a StringBuilder and call the reverse() method.
How do we convert a StringBuilder object to a String object?
By calling the toString() method.
Does StringBuilder implement the method equals()?
No.
If you call equals() on two StringBuilder instances, it will check for reference equality. To check for equality, convert it to String first.
Why does the following code not compile?
String string = "a"; StringBuilder builder = new StringBuilder("a"); System.out.println(string == builder);
The compiler is smart enough to know that two references to two different type of objects can never return true.
What is the string pool (also known as intern pool)?
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.
What kinds of strings are stored in the string pool?
Literal strings and constants.
If your program contains literal strings or constants, they are stored in the string pool.
What will happen when this code is executed?
String x = “Hello world”;
String y = “Hello world”;
System.out.println(x == y);
It prints true.
Literal strings and constants are stored in the string pool (and therefore point to the same location in memory).
What will happen when this code is executed?
String x = “Hello world”;
String y = “ Hello world”.trim();
System.out.println(x == y);
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.
How do we force to use a string from a string pool, if it exists?
By calling the intern() method of a string.
What are valid ways to declare an array?
int[] numbers = new int[1]; int[] numbers = new int[] {42, 55}; int[] numbers = {42, 55}; int [] numbers = ... int []numbers = ... int numbers[] = ... int numbers [] = ...
What is the following type of array called?
int[] numbers = {42, 55, 99};
Anonymous array
What type of reference variable does the following code create?
int[] ids, types;
Two variables of type int[].
What type of reference variable does the following code create?
int ids[], types;
One variable of type int[] (ids), one variable of type int.
page 184,185
How do we print the contents of an array in a human-readable way?
Arrays.toString(arrayHere);
Arrays is a class provided by Java that requires an import. What package does it reside in?
java.util
How can we sort an array? Class & method
Using the Arrays.sort() method.
How can we search an array?
Using Arrays.binarySearch().
Requires the array to be sorted.
What does Arrays.binarySearch() return when an element is not found?
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.
What does Arrays.binarySearch() return when the argument array is not sorted?
The answer will be unpredictable.
How can we compare an array?
Using the equals(), Arrays.compare() or the Arrays.mismatch() method.
What are the return value rules for Arrays.compare()?
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.
Does this compile?
Arrays.compare(new int[] {1}, new String[] {“a”});
No. They must be of the same type.
What does Arrays.mismatch() do?
Arrays.mismatch() is familiar to compare(). If the arrays are equal, mismatch() returns -1. Otherwise it returns the first index where they differ.
What does the following code return?
Arrays.mismatch(new int[] {1, 2}, new int[] {1});
It returns 1.
The element at index 1 of the second array is not equal the first array.
What is the benefit of an Arraylist over an array?
Just like a StringBuilder, an Arraylist can change capacity at runtime if needed.
What package does ArrayList reside in?
java.util
What are three ways to instantiate an ArrayList?
new ArrayList(); new ArrayList(10); new ArrayList(otherList); //shallow copy other list
Why does
var list = new ArrayList<>();
compile? and what type is it?
The type of the var is ArrayList. Since there isn’t a type specified for the generic, Java assumed the ultimate superclass (Object).
What is a wrapper class?
A wrapper class is an object type that corresponds to a primitive.
What is the advantage of calling the Wrapper class method valueOf() over using the constructor?
ex: Long.valueOf(1)
the valueOf() method allows object caching (like the String pool)
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?
Integer.parseInt(“123”) returns a primitive
Integer.valueOf(“123”) returns a Wrapper object
Explain what autoboxing and unboxing is
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.
What happens when you try to unbox a null value?
Java will throw a NullPointerException
How do we convert a list to an array? (2 options)
list. toArray(); //returns Object[] array
list. toArray(new String[0]); //returns String[] array
How do we convert an array to a list?
Arrays.asList(array); // returns fixed sized list
List.of(array); //returns immutable list
What happens when you want to change a value in an immutable list?
It throws a UnsupportedOperationException
How do we create a list using varargs? (two options)
Arrays.asList(“one”, “two”);
List.of(“one”, “two”);
What is the difference between Arrays.asList() and List.of()?
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.
What happens when trying to add an item to a set that already contains that item?
It returns false.
What are two common implementations of Set?
HashSet and TreeSet
When is TreeSet more important than Hashset?
When sorting is important
What is the most common implementation of Map?
HashMap
What are common Math methods?
- min() and max()
- round()
- pow()
- random()
What is the difference between the equals method and the == operator?
== 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.
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.
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.
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
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 ==.
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.
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.
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, 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.