Chapter 3 Flashcards
What does API stand for?
application programming interfaces that give you access to a service or functionality
What is string concatenation?
Placing one String before another String and combining them
what does the + mean here: “a” + “b”
concatenation
What is the order of evaluation with addition and concatenation?
evaluated left to right
What is the output of the following: sys out(1+3); sys out(“a”+”b”); sys out(“a”+”b”+3; sys out(1+2+”c”);
4 ab ab3 3c
What is the output and type of the sysout: int three = 3; String four = “4”; sysout(1+2+three+four):
string 64
What does += do in the context of Strings? (What does s+=”2 mean?)
s = s + “2”;
What is the output? String s = “1”; s +=”2”; s +=”3”; sysout(s)
s is equal to “123”;
What doe sit mean to say that Strings are immutable?
They are not allowed to change. It cannot be made larger or smaller and you can’t change one of the letters inside of it. Nothing about it can change!
What is the output? String s1 = “1”; String s2 = s1.concat(“2”); s2.concat(“3”); System.out.println(s2);
- s2.concat 3 would need to be stored in a new variable
What is the output? String s1 = “1”; String s2 = s1.concat(“2”); s2.concat(“3”); System.out.println(s2);
- s2.concat 3 would need to be stored in a new variable
What does Java do because it realizes Strings take up a lot of memory?
It is able to recognize when one String is use multiple times and reuses common ones.
What is the String pool?
The place containing literal values that appear in your program. For example: “hello” would be in the string pool whereas myObject.toString() would not be in the String pool.
Would “hello” be in the string pool
yes
would myOjbect.toString() be in the string pool?
no
How does the string pool handle this? String name = “fluffy”; String name = new String(“fluffy”);
The first is stored in the string pool. The second says, “No, JVM. I really don’t want you to use the string pool for this one. Make a new object for me even though it is less efficient.
Why does the string pool exist?
Because strings take up a lot of memory. So the pool stores literals and watches for ways to reuse preexisting literals where possible.
With Strings, where does Java index from?
0 (only when indexing
What does myString.length() return?
an int count of the length of myString
What’s the method signature for length()
int length()
What’s the method signature for charAt()
char charAt(int index)
What does charAt(int index) return?
The char at a specified index
What does this return? String string = “animals”; sysout(charAt(0)); sysout(charAt(6)); sysout(charAt(7));
a s throws out of bounds exception because charAt indexes from 0. So max range would be 0-6.
What does indexOf() do?
indexOf() looks at the characters in a string and finds the earliest occurrence, returning the index of the first occurrence as an int.
What do these return? String string = “animals”; sysout(string.indexOf(‘a’));
sysout(string.indexOf(“al”));
sysout(string.indexOf(‘a’,4));
sysout(string.indexOf(“al”,5));
0
4
4 (don’t even look for any matches until you get to the index of 4)
-1 (negative one means no matches were found) Remember that you need double quotes for more than one letter
Does indexOf throw an error if it doesn’t find a match?
No. It will return -1 if it doesn’t find anything.
What are the method signatures for indexOf()? (4)
int indexOf(int ch); int indexOf(char ch, int fromIndex); int indexOf(String str); int indexOf(String str, index fromIndex);
What are the method signatures for substring()?
String subString(int beginIndex); String subString(int beginIndex, int endIndex);
What does substring() do?
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.
What does this return? 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, 6)); System.out.println(string.substring(3, 8)); System.out.println(string.substring(3,3)); System.out.println(string.substring(3,2));
mals mals m mal error empty string error Remember, the last index is not INCLUDING. It’s says, “include up to this index”. If an endIndex is requested it stops right there.
What do String toLowerCase() and String toUpperCase() do?
Keeping in mind that strings are immutable, toUpperCase and toLowerCase return strings that are either now upper or lower case. They only touch characters that are letters.
What does boolean equals(Object obj) do?
It compares whether two objects have the exact same bits. You can only call this on objects. Not primitives.
What does boolean equalsIgnoreCase(Object obj) do?
Checks whether two String objects contains exactly the same letters in the same order with the exception that it will convert case when it needs to)
What’s the output? String string = “animals”; String string2 = new String(“animals”); String string3 = “animals”; System.out.println(string.equals(“animals”)); System.out.println(string.equals(string2)); System.out.println(string.equalsIgnoreCase(new String(“animals”))); System.out.println(string==string2); System.out.println(string==”animals”); System.out.println(string==new String(“animals”)); System.out.println(string==string3);
true true true false true false true remember it is case sensitive unless told to not be so
What do these methods do? boolean startsWith(String prefix) boolean endsWith(String suffix)
They look at whether or not the string ends with or starts with the provided values
What’s the output? String name = “jedd”; System.out.println(name.endsWith(“dd”)); System.out.println(name.endsWith(“DD”));
true false remember it is case sensitive
What does boolean contains (String str) do?
It looks for matches with in the string regardless of whether it starts with/ends with or whatever. it doesn’t care. also case sensitive
What is the output? String name = “jedd”; System.out.println(name.contains(“dd”)); System.out.println(name.contains(“DD”));
true false
What does the replace method do? String replace(char oldChar, char newChar) String replace(CharSequence oldChar, CharSequence newChar)
The replace method does a simple search and replace on the string.
What is the output: System.out.println(“abcabcabc”.replace(‘c’, ‘b’)); System.out.println(“abcabcabc”.replace(“a”, “A”));
abbabbabb AbcAbcAbc Note: the second method is not the same as the first. This is looking for a CharSequence or a String and replacing it with another String.
What does the trim() method do? public String trim()
The trim() method removes whitespace from the beginning and the end of a string. So on the exam this means \t (tab and \n newline characters get trimmed.
What is the output? public static void main(String[] args) { System.out.println(“abc”.trim()); System.out.println(“\t a b c\n”.trim()
abc a b c The second drops the leading tab, subsequent spaces, and the trailing newline. Note that it leaves the spaces in the middle of the spring.
What happens when you call a String method on a String? What happens if you call many methods on a String?
You make a new String each time. Each time one is called, the returned value is put in a new variable.
What does the Stringbuilder class do?
Creates a String without storing all the interim values that occur as you iterate through string objects. String immutability means that each time you “change” a String you are actually making a new one. Often making the old one eligible for garbage collection almost immediately. String builders change their own state and then return references to themselves.
Are instances of StringBuilder s immutable?
no
What is the output and why? StringBuilder a = new StringBuilder(“abc”); StringBuilder b = a.append(“de”); b = b.append(“f”).append(“g”); System.out.println(a); System.out.println(b); System.out.println(a==b);
abcdefg abcdefg true There is only one StringBuilder object here. We know that because new StringBuilder9) was called only once.
How many string objects does this piece of code create? String alpha = “”; for(char current = ‘a’; current <= ‘z’; current++){ alpha+=current; System.out.println(alpha);
- A new string is made with the addition of each new character. (initial empty string + addition of each character of the alphabet). Note that as each string is created the string that it replaced is now available for garbage collection.
How many string objects does this code generate? StringBuilder alpha = new StringBuilder(); for (char current = ‘a’; current <= ‘z’; current++) { alpha.append(current); System.out.println(alpha); }
Just one. This code reuses the same String building without creating an interim string each time.
How does String handle method chaining?
It creates a new string each time.
How does StringBuilder handle method chaining?
StringBuilders change their own state and returns a reference to itself.
What is the output? StringBuilder sb = new StringBuilder(); sb.append(“+middle”); StringBuilder same = sb.append(“+end”); System.out.println(sb); System.out.println(sb == same);
+middle+end true
What’s the difference between StringBuilder() and StringBuffer()?
String Buffer is an older thread safe version of string builder.
What is the output? StringBuilder() one = new StringBuilder(); StringBuilder() two = new StringBuilder(); StringBuilder() three = one.append(“a”); Sysout(one == two); Sysout(one == three);
False True Remember string builders return references to themselves.
What is the output? String x = “Hello world!”; String y = “Hello world!”; sysout(x == y);
This is true because of how the JVM deals with string literals. Strings are immutable and literals are pooled.
What is the output? String x = “Hello world!”; String y = “Hello world!”.trim(); sysout(x == y);
True.
What is the output? String x = “Hello world!”; String y = new String(“Hello world!”); sysout(x == y);
false. As you have specifically requested a new string object the pooled value literal won’t be shared
What is the output? Tiger t1 = new Tiger(); Tiger t2 = new Tiger(); Tiger t3 = t1; Sysout(t1==t3); sysout(t1==t2); sysout(t1.equals(t2));
true false false
What do String and StringBuilder composed of?
They are both arrays of characters?
What is an array?
An array is an area of memory on the heap with space for a designated number of elements.
Can arrays be of any Java type?
yes
char[] letters; Is letters a primitive or a reference variable?
Reference variable. char is a primitive but an array of chars is not.
Describe this in a sentence: int[] numbers1 = new int[3];
This is an array of ints that can contain three elements.
When you first make an array, what are the default values?
Whatever the default value is for the type of array we are dealing with.
Do all of these compile? int[] numbers; int [] numbers; int numbers[]; int numbers [];
yes
Do both of these compile? int [] numbers = new int[] {43,43,43}; int[] numbers = {43,43,43};
Yes. Java recognizes the “new int[]” as redundant. The second wouldn’t be considered an anonymous array, anonymous because we haven’t specified the size and the type.
What does this create? int [] ids, types; int ids[], types;
The first makes two variables of the type int[]. The second makes one int array and one int.
How does the .equals() method work on arrays?
Checks to see if the references are the same.
How does this array work? String [] stuff = {“do”, “try”, “go”};
Stuff stores references to those string objects.
What does this array point to? String names[];
null
What does this array do? String names[] = new String[2];
This is an array with a capacity of two. Currently, both of the values are null. But each null has the capacity to point to a string object.
Do each of these compile?
String[] strings = {“stringValue”};
Object[] objects = strings;
String [] moreStrings = (String[]) objects;
moreStrings[0] = new StringBuilder();
objects[0] = new StringBuilder();
String[] strings = {“stringValue”}; yes
Object[] objects = strings; yes, doesn’t require cast because Object is more broad than String.
String [] moreStrings = (String[]) objects; yes Cast needed because we are moving to a more specific type
moreStrings[0] = new StringBuilder(); no, bad type so no compile
objects[0] = new StringBuilder(); no Object can store StringBuilders, but we don’t have an Object array at this point. objects is pointing to a string array.
Why doesn’t this compile? int [] numbers = new int[10]; for (int j = 0 ; j<= numbers.length; j++){ numbers[j] = j+5; System.out.println(numbers[j]); }
<= causes array index out of bounds.
What is the output? int [] numbers = {6,9,1}; Arrays.sort(numbers); for (int j = 0; j < numbers.length; j++){ System.out.print(numbers[j] + “ “) }
1 6 9;
Can you do an index search on advanced for loops?
no. Only with iterators.
You can search an array, but what must be done first?
It must be sorted.
What are the three binary search rules?
Target element found in sorted array (Result) Index Target element not found in sorted array (Result) Negative value showing one smaller than the negative index, where a match needs to be inserted to preserve sorted order. Unsorted array (Result) A surprise–this result isn’t predictable
What is the output? int [] numbers = {2,4,6,8}; System.out.println(Arrays.binarySearch(numbers,2)); System.out.println(Arrays.binarySearch(numbers,4)); System.out.println(Arrays.binarySearch(numbers,1)); System.out.println(Arrays.binarySearch(numbers,3)); System.out.println(Arrays.binarySearch(numbers,9));
0 1 -1 -2 (3 would be at the index of 1, negate, minus 1 to get -2) -5 (9 this would be at index of four, we negate, minus 1 to get this result) The binary search tells us at which index the number is found OR at which index it would be found if it were part of a sorted list.
Can you use varargs as an array?
yes. (Think main(String..args))
What do each of these represent? int[][] vars1; int vars [][]; int[] vars3[]; int[] vars4 [], space[][][]
one 2d array one 2d array one 2d array one 2d array and one 3d array
Say this in readable language: String [] [] rectangle = new String[3][2];
rectangle is a reference to 3 elements which happen to be 2 dimensional arrays.
Say this in readable language: int [] [] differentSize = {{1,4},{3},{9,8,7}};
differentSize is a two dimensional int array. The first element is a 2d array with the values of 1 and 4 at index 0 and 1. The second array has one element (3) at the index of 0. The third element/array is an array with the values 9, 8, and 7 at index 0,1,2.
Say this in readable language: int [] [] args = new int[4][]; args[0] = new int[5]; args[1] = new int[3];
The first line initialize a 2d array. It also says the first dimension of the array has four elements, or four places that can contain an array. Lines 3 and 4 give the first and second element array sizes, respectively, 5 and 3.
What is the output? int[][] twoD = new int[3][2]; for (int j = 0; j< twoD.length; j++) { for (int k = 0; k < twoD[j].length; k++) { System.out.print(twoD[j][k] + “ “ ); System.out.println(); } }
0 0 0 0 0 0 This finds the first array (of three available) and prints out each value. Then it goes to the next array in order. So from index of 0 to index of 1 and so on.
What’s a glaring short coming of an array?
You have to know how many elements will be in the array when you create it and you are stuck with that choice under threat of index out of bounds errors.
StringBuilder is to String as ____ is to an array?
ArrayList
What is an ArrayList?
an ordered sequence that allows duplicates–like an array–but that can grow from the initial size you set, unlike an array.
Does this compile? ArrayList list1 = new ArrayList(); ArrayList list2 = new ArrayList(10); ArrayList list3 = new ArrayList(list2); ArrayList list4 = new ArrayList(); ArrayList list5 = new ArrayList<>();
yes. note that the last two are better because of generics.
What is the diamond operator?
<>
Which interface does ArrayList implement?
List. In other words, ArrayList is a list.
Why can’t you store an ArrayList in a List reference variable?
Because List is an interfaces so it can’t be instantiated.
Does this compile? List list6 = new ArrayList<>(); ArrayList list7 = new List<>();
The first, yes. The second, no. List is an interface so it’s can’t be instantiated.
What does E mean in the context of generic arrays?
E is used by convention in generics to mean “any class that this array can hold.”
What’s the default type for an ArrayList if you don’t specify a type?
object
Method signatures for ArrayList.add() = boolean add(E element) void add(int index, E element)
Add an element to the end or add an element to an index.
What is the output? ArrayList list = new ArrayList(); list.add(“hawk”); list.add(true); list.forEach(System.out::println);
hawk, true This works as we didn’t specify a type so any Object (so non primitive) works.
What is the output? ArrayList list = new ArrayList<>(); list.add(“sparrow”); list.add(“Boolean.TRUE);
The first add work but the second doesn’t because we have used generics to specify a type.
Method signatures for ArrayList.remove() = boolean remove(Object object) E remove( int index)
Boolean tells us whether the object was removed. The E return type is the element that actually got removed
What is the output? List birds = new ArrayList<>(); birds.add(“hawk”); birds.add(“hawk”); System.out.println(birds.remove(“cardinal”)); System.out.println(birds.remove(“hawk”)); System.out.println(birds.remove(0));
false true hawk note only one hawk string was removed.
What does this do? E set(int index, E newElement) Note that the E return type is the element that was replaced
The set Method changes one of the elements of the ArrayList without changing the size.
What is the output? List birds = new ArrayList<>(); birds.add(“hawk”); System.out.println(birds.size()); birds.set(0, “robin”); System.out.println(birds.size()); birds.set(1, “robin”);
Index out of bounds as the array only has a size of one. The set method only replaces the element, it does not add another.
What does this method do? boolean ArrayList.isEmpty()
If there are no elements it returns true.
What does this method do? ArrayList.size() int size()
Returns the number of elements in the ArrayList.
What is the output? List birds = new ArrayList<>(); System.out.println(birds.isEmpty()); birds.add(“hawk”); System.out.println(birds.isEmpty()); System.out.println(birds.size());
true false 1
What does this method do? ArrayList.clear() void clear()
Discards all the elements in an ArrayList.
What is the output: List birds = new ArrayList<>(); System.out.println(birds.isEmpty()); birds.add(“hawk”); System.out.println(birds.isEmpty()); birds.add(“doggle”); System.out.println(birds.size()); birds.clear(); System.out.println(birds.size());
true false 2 0
What does this method do? ArrayList.contains() boolean contains(Object object)
contains() check whether a certain value is in the array list. It does so by calling equals() on each element of the ArrayList to see if there are any matches.
What is the output: List birds = new ArrayList<>(); birds.add(“hawk”); birds.add(“doggle”); System.out.println(birds.contains(“hawk”)); System.out.println(birds.contains(“Hawk”));
true false
What does this method do? ArrayList.equals() boolean equals(Object object)
This is a custom implementation of equals() so you can compare two lists to see if they contain the same elements in the same order.
What is the output? List listOne = new ArrayList<>(); List listTwo = new ArrayList<>(); System.out.println(listOne.equals(listTwo)); listOne.add(“hawk”); System.out.println(listOne.equals(listTwo)); listTwo.add(“hawk”); System.out.println(listOne.equals(listTwo)); listOne.add(0,”doggle”); listTwo.add(“doggle”); System.out.println(listOne.equals(listTwo));
true false true false Remember, the order has to match.
How is it possible to put primitives into an arrayList?
It’s not, we have to use the wrapper class provided for each primitive.
Do wrapper classes have methods to convert themselves back to primitives?
Yes
What does each line do? int primitive = Integer.parseInt(“123”); Integer wrapper = Integer.valueOf(“123”); int number1 = Integer.parseInt(“1.2”); Integer number2 = Integer.valueOf(“1.2”);
The first line is converting a string to a primitive (int in this case). The second line converts a string into the wrapper class Integer. The third and fourth lines throw errors because these methods won’t handle the decimal. If you wanted to do that you would need to use the Double wrapper valueOf method or the Double wrapper parseDouble method.
How would you convert a String to a primitive?
E.parseE(“ “);
Except Character, this does not of a way to convert the String to it’s primitive.
And remember the way to convert the string back to the primitive is to use the wrapper class and value of.
How would you convert a String to a wrapper class?
E.valueOf(“ “);
Which primitive doesn’t have methods to convert a String to a primitive/wrapper class?
Character. Just use the String methods.
What is auto boxing?
It’s when java converts a primitive to the relevant wrapper class.
What is the output: List numbers = new ArrayList<>(); numbers.add(null); int h = numbers.get(0);
null pointer exception. It’s possible to add a null value, as a null value can be assigned to any reference variable, but not possible to assign a null value to a primitive.
What do you get when you call a method on a null value?
You always get a null pointer exception.
What is a backed List?
A fixed sized list as the array changes with the list. You are not allowed to change the size of a list. When a change is made in one, the value is available in the other
What is the output and how do we know this is a backed list? Will this compile? String[] array = {“hawk”, “robin”}; List list = Arrays.asList(array); System.out.println(list.size()); list.set(1, “test”); array[0] = “new”; for (String b : array) System.out.println(b); list.remove(1);
Note that we made changes to the list but the values were made available to the array. Note that removing it throws an unsupported operation exception. were it not for that, the out put would be new test.
What is the output? String[] array = {“hawk”, “robin”}; List list = Arrays.asList(array); System.out.println(list.size()); list.set(1, “test”); list.add(“hey”); array[0] = “new”; for (String b : array) System.out.println(b);
Unsupported operation exception. You cannot change the size of an array
What is the output? String[] array = {“hawk”, “robin”}; List list = Arrays.asList(array); System.out.println(list.size()); list.set(1, “test”); list.add(“hey”); array[0] = “new”; for (String b : array) System.out.println(b);
Unsupported operation exception. You cannot change the size of an array
What is the output? List numbers = new ArrayList<>(); numbers.add(99); numbers.add(5); numbers.add(10); Collections.sort(numbers); System.out.println(numbers);
[5, 10, 99]
What’s the import for dealing with dates and times?
import java.time.*;
What does will each of these classes expose for use? LocalDate LocalTime LocalDateTime
LocalDate - just a date, no time and no time zone. like 01-01-01 LocalTime - Just the time, no date and no time zone LocalDateTIme - Date and time but no time zone
What would the out put of each be whenever this is read? System.out.println(LocalDate.now()); System.out.println(LocalTime.now()); System.out.println(LocalDateTime.now()); System.out.println(LocalDate date = new LocalDate()):
Something like: 2018-10-15 19:34:49.031 2018-10-15T19:34:49.031 Does not compile. Date methods are static and only static.
What is the output: System.out.println(LocalTime.of(9,30)); System.out.println(LocalTime.of(9,30, 30)); System.out.println(LocalTime.of(9,30, 30, 30));
09:30 09:30:30 09:30:30.000000030
What is the output: LocalDate date1 = LocalDate.of(2018, Month.OCTOBER, 13); LocalTime time1 = LocalTime.of(9, 30); System.out.println(LocalDateTime.of(2015,Month.JANUARY,9,9,30)); System.out.println(LocalDateTime.of(date1, time1)); System.out.print(LocalDateTime.of(2018,11,2,9,30));
2015-01-09T09:30 2018-10-13T09:30 2018-11-02T09:30
Are date and time classes mutable or immutable?
Immutable