Ch5 Core Java APIs Flashcards
What interfaces does String implement?
Serializable, CharSequence, Comparable
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 are the options to construct a StringBuilder?
Stringbuilder b1 = new StringBuilder();
Stringbuilder b2 = new StringBuilder(“animal”);
Stringbuilder b3 = new StringBuilder(10);
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 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.
What is the following type of array called?
int[] numbers = {42, 55, 99};
Anonymous array
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.