Chapter 5 Core Java APIs Flashcards
What is API?
Application Programming Interface (API),
an interface refers to a group of classes or Java interface definitions giving you access to a service or functionality.
Creating and Manipulating Strings
What is a string?
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.
String name = "Fluffy";
VS
String name = new String("Fluffy");
the String class is special and doesn’t need to be instantiated with new.
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.
String Concatenation Rules
- If both operands are numeric, + means numeric addition.
- If either operand is a String, + means concatenation.
- The expression is evaluated left to right.
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);
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
int three = 3; String four = "4"; System.out.println(1 + 2 + three + four);
int three = 3; String four = "4"; System.out.println(1 + 2 + three + four);//64
4: String s = "1"; 5: s += "2"; 6: s += 3; 7: System.out.println(s);
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
String is immutable
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.
MORE ON IMMUTABILITY
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; } }
IMPORTANT STRING METHODS
- length()
- charAt()
- indexOf()
- substring()
- toLowerCase() and toUpperCase()
- equals() and equalsIgnoreCase()
- startsWith() and endsWith()
- replace()
- contains()
- trim(), strip(), stripLeading(), and stripTrailing()
- intern()
int length()
The method length() returns the number of characters in the String.
char charAt(int index)
The method charAt() lets you query the string to find out what character is at a specific index.
String string = "animals"; System.out.println(string.charAt(0)); System.out.println(string.charAt(6)); System.out.println(string.charAt(7));
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
int indexOf(int ch) int indexOf(int ch, int fromIndex) int indexOf(String str) int indexOf(String str, int fromIndex)
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.
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));
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
String substring(int beginIndex) String substring(int beginIndex, int endIndex)
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.
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));
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
System.out.println(string.substring(3, 3)); System.out.println(string.substring(3, 2)); System.out.println(string.substring(3, 8));
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
String toLowerCase() String toUpperCase()
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.
toUpperCase() and toLowerCase() examples:
String string = "animals"; System.out.println(string.toUpperCase()); System.out.println("Abc123".toLowerCase());
String string = "animals"; System.out.println(string.toUpperCase()); // ANIMALS System.out.println("Abc123".toLowerCase()); // abc123
boolean equals(Object obj) boolean equalsIgnoreCase(String str)
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.
equals() and equalsIgnoreCase() examples
System.out.println("abc".equals("ABC")); System.out.println("ABC".equals("ABC")); System.out.println("abc".equalsIgnoreCase("ABC"));
System.out.println("abc".equals("ABC")); // false System.out.println("ABC".equals("ABC")); // true System.out.println("abc".equalsIgnoreCase("ABC")); // true
boolean startsWith(String prefix) boolean endsWith(String suffix)
The startsWith() and endsWith() methods look at whether the provided value matches(case-sensitive) part of the String.
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”));
~~~
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
String replace(char oldChar, char newChar) String replace(CharSequence target, CharSequence replacement)
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.
replace() examples:
~~~
System.out.println(“abcabc”.replace(‘a’, ‘A’)); // AbcAbc
System.out.println(“abcabc”.replace(“a”, “A”)); // AbcAbc
~~~
The first example uses the first method signature, passing in char parameters.
The second example uses the second method signature, passing in String parameters.
boolean contains(CharSequence charSeq)
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.
contains() examples:
~~~
System.out.println(“abc”.contains(“b”)); // true
System.out.println(“abc”.contains(“B”)); // false
~~~
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.
String strip() String stripLeading() String stripTrailing() String trim()
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.
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.
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
~~~
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.
String intern()
The intern() method returns the value from the string pool if it is there. Otherwise, it adds the value to the string pool.
METHOD CHAINING
examples:
~~~
String result = “AniMaL “.trim().toLowerCase().replace(‘a’, ‘A’);
System.out.println(result);
~~~
It is common to call multiple methods
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);
~~~
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”.
Using the StringBuilder Class
The StringBuilder class creates a String without storing all those interim String values.
Unlike the String class, StringBuilder is not immutable.
10: String alpha = ""; 11: for(char current = 'a'; current <= 'z'; current++) 12: alpha += current; 13: System.out.println(alpha);
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.
15: StringBuilder alpha = new StringBuilder(); 16: for(char current = 'a'; current <= 'z'; current++) 17: alpha.append(current); 18: System.out.println(alpha);
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.
MUTABILITY AND CHAINING
4: StringBuilder sb = new StringBuilder("start"); 5: sb.append("+middle"); // sb = "start+middle" 6: StringBuilder same = sb.append("+end"); // "start+middle+end"
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.
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);
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.
CREATING A STRINGBUILDER
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.
IMPORTANT STRINGBUILDER METHODS
- charAt(),
- indexOf(),
- length()
- substring()
- append()
- insert()
- delete() and deleteCharAt()
- replace()
- reverse()
- toString()
STRINGBUILDER METHODS
charAt(), indexOf(), length(), and substring()
These four methods work exactly the same as in the String class.
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);
~~~
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.
StringBuilder append(String str)
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.
append() examples:
~~~
StringBuilder sb = new StringBuilder().append(1).append(‘c’);
sb.append(“-“).append(true);
System.out.println(sb); // 1c-true
~~~
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.
StringBuilder insert(int offset, String str)
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.
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);
~~~
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.
StringBuilder delete(int startIndex, int endIndex)
StringBuilder deleteCharAt(int index)
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.
delete() examples:
StringBuilder sb = new StringBuilder("abcdef"); sb.delete(1, 3); // sb = adef sb.deleteCharAt(5); // throws an exception
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.
delete() examples:
~~~
StringBuilder sb = new StringBuilder(“abcdef”);
sb.delete(1, 100); // sb = 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:
StringBuilder replace(int startIndex, int endIndex, String newString)
The replace() method works differently for StringBuilder than it did for String.
replace() examples:
StringBuilder builder = new StringBuilder(“pigeon dirty”);
builder.replace(3, 6, “sty”);
System.out.println(builder); // pigsty dirty
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.
replace() examples:
~~~
StringBuilder builder = new StringBuilder(“pigeon dirty”);
builder.replace(3, 100, “”);
System.out.println(builder);
~~~
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.
StringBuilder reverse()
The reverse() method does just what it sounds like: it reverses the characters in the sequences and returns a reference to the current StringBuilder.
reverse() examples:
~~~
StringBuilder sb = new StringBuilder(“ABC”);
sb.reverse();
System.out.println(sb);
~~~
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.
String toString()
This method converts a StringBuilder into a String.
toString() examples:
StringBuilder sb = new StringBuilder("ABC"); String s = sb.toString();
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.
Understanding Equality
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.
COMPARING EQUALS() AND ==
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
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.
String x = "Hello World"; String z = " Hello World".trim(); System.out.println(x.equals(z)); // true
This works because the authors of the String class implemented a standard method called equals to check the values inside the String rather than the string 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.
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.
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: } }
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.
String string = "a"; StringBuilder builder = new StringBuilder("a"); System.out.println(string == builder); //DOES NOT COMPILE
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.
THE STRING POOL
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.
String x = "Hello World"; String y = "Hello World"; System.out.println(x == y); // true
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.
String x = "Hello World"; String z = " Hello World".trim(); System.out.println(x == z); // false
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.
String singleString = "hello world"; String concat = "hello "; concat += "world"; System.out.println(singleString == concat);
This prints false. Concatenation is just like calling a method and results in a new String
String x = "Hello World"; String y = new String("Hello World"); System.out.println(x == y); // false
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.”
String name = "Hello World"; String name2 = new String("Hello World").intern(); System.out.println(name == name2); // true
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.
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());
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.
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.
Understanding Java Arrays
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.
CREATING AN ARRAY OF PRIMITIVES
~~~
int[] numbers1 = new int[3];
~~~
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
CREATING AN ARRAY OF PRIMITIVES
int[] numbers2 = new int[] {42, 55, 99};
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.