Chapter 3 Flashcards
String concatenation
- 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”);
// 3
// ab
// ab3
// 3c
Mutable vs. Immutable
Mutable is another word for changeable. Immutable is the opposite—an object that can’t be changed once it’s created. On the OCA exam, you need to know that String is immutable.
The string pool
Also known as the intern pool, is a location in the Java virtual machine (JVM) that collects all these strings. Java realizes that many strings repeat in the program and solves this issue by reusing common ones.
Important String Methods:
length()
String string = “animals”;
System.out.println(string.length());
// 7
The method length() returns the number of characters in the String.
Important String Methods:
charAt()
String string = “animals”;
System.out.println(string.charAt(0));
System.out.println(string.charAt(6));
System.out.println(string.charAt(7));
// a
// s
// throws exception
The method charAt() lets you query the string to find out what character is at a specific index.
Important String Methods:
indexOf()
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));
// 0
// 4
// 4
// -1
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. The method signatures are as follows:
int indexOf(char ch)
int indexOf(char ch, index fromIndex)
int indexOf(String str)
int indexOf(String str, index fromIndex)
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.
Important String Methods:
substring()
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));
System.out.println(string.substring(3, 3));
System.out.println(string.substring(3, 2));
System.out.println(string.substring(3, 8));
// mals
// mals
// m
// mals
// empty string
// throws exception
// throws exception
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. Notice we said “stop at” rather than “include.” The method signatures are as follows:
int substring(int beginIndex)
int substring(int beginIndex, int endIndex)
Let’s review this one more time since substring() is so tricky. The method returns the string starting from the requested index. If an end index is requested, it stops right before that index. Otherwise, it goes to the end of the string.
Important String Methods:
equals() and equalsIgnoreCase()
System.out.println(“abc”.equals(“ABC”));
System.out.println(“ABC”.equals(“ABC”)); System.out.println(“abc”.equalsIgnoreCase(“ABC”));
// false
// true
// true
The equals() method checks whether two String objects contain exactly the same char- acters 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. The method signatures are as follows:
boolean equals(String str)
boolean equalsIgnoreCase(String str)
Important String Methods:
startsWith() and endsWith()
System.out.println(“abc”.startsWith(“a”));
System.out.println(“abc”.startsWith(“A”));
System.out.println(“abc”.endsWith(“c”));
System.out.println(“abc”.endsWith(“a”));
// true
// false
// true
// false
The startsWith() and endsWith() methods look at whether the provided value matches part of the String. The method signatures are as follows:
boolean startsWith(String prefix)
boolean endsWith(String suffix)
Again, nothing surprising here. Java is doing a case-sensitive check on the values provided.
Important String Methods:
contains()
System.out.println(“abc”.contains(“b”));
System.out.println(“abc”.contains(“B”));
// true
// false
The contains() method also looks for matches in the String. It isn’t as particular as startsWith() and endsWith()—the match can be anywhere in the String. The method signature is as follows:
boolean contains(String str)
Again, we have a case-sensitive search in the String. The contains() method is a conve- nience method so you don’t have to write str.indexOf(otherString) != -1.
Important String Methods:
replace()
System.out.println(“abcabc”.replace(‘a’, ‘A’));
System.out.println(“abcabc”.replace(“a”, “A”));
// AbcAbc
// AbcAbc
The replace() method does a simple search and replace on the string. The method signatures are as follows:
String replace(char oldChar, char newChar)
String replace(CharSequence oldChar, CharSequence newChar)
The first example uses the first method signature, passing in char parameters. The second example uses the second method signature, passing in String parameters.
Important String Methods:
trim()
System.out.println(“abc”.trim());
System.out.println(“\t a b c\n”.trim());
// abc
// a b c
The trim() method removes 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 method signature is as follows:
public String trim()
The StringBuilder class
The StringBuilder class creates a String without storing all those interim String values. Unlike the String class, StringBuilder is not immutable.
Creating a StringBuilder
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder(“animal”);
StringBuilder sb3 = new StringBuilder(10);
Important StringBuilder Methods:
charAt(), indexOf(), length(), and substring()
These four methods work exactly the same as in the String class.
Important StringBuilder Methods:
append()
It adds the parameter to the StringBuilder and returns a reference to the current StringBuilder. One of the method signatures is as follows:
StringBuilder append(String str)
Important StringBuilder Methods:
insert()
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. Here’s one:
StringBuilder insert(int offset, String str)
Pay attention to the offset in these examples. It is the index where we want to insert the
requested parameter.
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
Important StringBuilder Methods:
delete() and deleteCharAt()
StringBuilder sb = new StringBuilder(“abcdef”);
sb.delete(1, 3);
sb.deleteCharAt(5);
// sb = adef
// throws an exception
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. The method signatures
are as follows:
StringBuilder delete(int start, int end)
StringBuilder deleteCharAt(int index)
Important StringBuilder Methods:
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. The method signature is as follows:
StringBuilder reverse()
Important StringBuilder Methods:
toString()
The last method converts a StringBuilder into a String. The method signature is as follows:
String toString()
Understanding Equality
StringBuilder one = new StringBuilder();
StringBuilder two = new StringBuilder();
StringBuilder three = one.append(“a”);
System.out.println(one == two);
System.out.println(one == three);
String x = “Hello World”;
String y = “Hello World”;
System.out.println(x == y);
String x = “Hello World”;
String z = “ Hello World”.trim();
System.out.println(x == z);
String x = new String(“Hello World”);
String y = “Hello World”;
System.out.println(x == y);
String x = “Hello World”;
String z = “ Hello World”.trim();
System.out.println(x.equals(z));
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 == t1);
8: System.out.println(t1 == t2);
9: System.out.println(t1.equals(t2));
10: } }
// false
// true
Since this example isn’t dealing with primitives, we know to look for whether the references are referring to the same object. one and two are both completely separate StringBuilders, giving us two objects. Therefore, the first print statement gives us false. three is more interesting. Remember how StringBuilder methods like to return the current reference for chaining? This means one and three both point to the same object and the second print statement gives us true.
// true
Remember that 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.
// false
In this example, we don’t have two of the same String literal. 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.
// false
Since you have specifi cally requested a different String object, the pooled value isn’t
shared.
// 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 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. In case you are wondering, the authors of StringBuilder did not implement equals(). If you call equals() on two StringBuilder instances, it will check reference equality.
// true
// false
// false
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 the OCA exam.
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
ArrayList Methods
add()
ArrayList list = new ArrayList();
list.add(“hawk”);
list.add(Boolean.TRUE);
System.out.println(list);
ArrayList<String> safer = new ArrayList<>();
safer.add("sparrow");
safer.add(Boolean.TRUE);</String>
4: List<String> birds = new ArrayList<>();
5: birds.add("hawk");
6: birds.add(1, "robin");
7: birds.add(0, "blue jay");
8: birds.add(1, "cardinal");
9: System.out.println(birds);</String>
// [hawk]
// [hawk, true]
// [hawk, true]
The add() methods insert a new value in the ArrayList. The method signatures are as
follows:
boolean add(E element)
void add(int index, E element)
Don’t worry about the boolean return value. It always returns true. It is there because
other classes in the collections family need a return value in the signature when adding an
element.
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.
// DOES NOT COMPILE
This time the compiler knows that only String objects are allowed in and prevents the attempt to add a boolean. Now let’s try adding multiple values to different positions.
// [hawk]
// [hawk, robin]
// [blue jay, hawk, robin]
// [blue jay, cardinal, hawk, robin]
// [blue jay, cardinal, hawk, robin]