OCA Java 7 - V Working with Strings, Arrays, ArrayLists and Dates/Times

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What is output of this code? List<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); numbers.remove(1); System.out.println(numbers);

*1* After adding the two values, the List contains [1, 2]. We then request the element with index 1 be removed. That's right: index 1. Because there's already a remove() method that takes an int parameter, Java calls that method rather than autoboxing.

Thread[] = new Thread[5]; How many objects are created?

*1* Despite how the code appears, the Thread constructor is not invoked. We are not creating Thread instance, but rather a single Thread array object. No thread objects have been created.

Which ArrayList method converts ArrayList into Array?

*List<String> list = new ArrayList<>();* *Object[] objectArray = list.toArray();* ArrayList knows how to convert itself to an array. The only problem is that it defaults to an array of class Object If we want to specify the type of returned array we can do it like this: String[] stringArray = list.toArray(new String[0]);

Which four main types of *Date/Time* we have in Java?

*LocalTime* - Contains just a time *LocalDate* - Contains just a date *LocalDateTime* - Contains both a date and a time but no time zone *ZoneDateTime* - Contains date, time and time zone

Is *equals()* method final?

*No* It's not final hence it can be overriden

In Months related methodes, does Java count from 0?

*No* Months are an exception from counting from 0 rule. For months in the new date and time methods, (Starting from Java 8) Java counts starting from 1 like we human beings do.

Can we apply *polymorphism* to the generic type parameter?

*No* Polymorphic assignments can't be applied to the generic type parameter. You can't say, for example, List<Supertype> c3 = new ArrayList<Subtype>();

Can we assign one dimensional array to previously declared two-dimensional array reference?

*No* They should be the same dimension

What is output of this code? 3. List<Integer> heights = new ArrayList<>(); 4: heights.add(null); 5: int h = heights.get(0);

*NullPointerException* On line 4, we add a null to the list. This is legal because a null reference can be assigned to any reference variable. On line 5, we try to unbox that null to an int primitive. This is a problem. Java tries to get the int value of null. Since calling any method on null gives a NullPointerException, that is just what we get. Be careful when you see null in relation to autoboxing

Date and time classes are mutable or immutable?

*The date and time classes are immutable*, just like String was. This means that we need to remember to assign the results of these methods to a reference variable so they are not lost

What is the problem about this two-dimensional array declaration? int[][] myArray = new int[3][];

*There's no problem*. JVM needs to know only the size of the object assigned to the variable myArray

What is the output of following code? String x = "Hello World"; String y = "Hello World"; System.out.println(x == y);

*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.

Do String methods use zero-based indexes?

*Yes* Except for the second argument of substring()

Given *getArray()[index=2];* Will getArray() method's body be evaluated if the whole expression itself causes error or exception?

*Yes* In an array access, the expression to the left of the brackets appears to be fully evaluated before any part of the expression within the brackets is evaluated. Note that if evaluation of the expression to the left of the brackets completes abruptly, no part of the expression within the brackets will appear to have been evaluated.

Is it possible to create arrays of length zero?

*Yes* Java allows arrays of length zero to be created. Here is an example: int[] zeroLengthArray1 = new int[0]; System.out.println(zeroLengthArray1.length); //will print 0

Can we assign an array of one type to previously declared array reference of it's supertype?

*Yes* i.e. Honda array can be assigned to an array declared as type Car - (if Honda extends Car) Car [] cars = new Honda [5]; But it won't work with primitives.

What will this code return? 3: List<String> birds = new ArrayList<>(); 4: birds.add("hawk"); 5: birds.add("hawk"); 6: System.out.println(birds.remove("cardinal")); 7: System.out.println(birds.remove("hawk")); 8: System.out.println(birds.remove(0));

6. prints *false*, because there is no "cardinal" element in ArrayList 7. prints *true*, because there is such element in ArrayList and it has been removed. Notice that it removes only one match 8. prints *"hawk"*, because it's the element that has been removed from index 0

Which exception you gonna get if you use a bad index value in array?

ArrayIndexOutOfBound Runtime Exception

What is ArrayList declaration syntax? (for normal and polymorphic declaration)

ArrayList<type> newList = new ArrayList<type>(); List<type> = new ArrayList<type>();

Why would anyone use ArrayList?

Because ArrayList allow you to *resize* your list and make *insertions* and *deletions* to your list far more easily than in array

Which method(s) parse String to 1. Primitive type 2. Wrapper type

For parsing *String to primitive* types we have methods like int primitive = Integer.parseInt("123);/parseBoolean/parseShort etc. For parsing *String to Wrapper* classes we have method Integer wrapper = Integer.valueOf("123");

What is the output of this code? DateTimeFormatter shortDateTime = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT); System.out.println(shortDateTime.format(dateTime)); System.out.println(shortDateTime.format(date)); System.out.println( shortDateTime.format(time));

Here we say we want a localized formatter in the predefned short format. The last line *throws an UnsupportedTemporalTypeException* because a time cannot be formatted as a date. The format() method is declared on both the formatter objects and the date/time objects, allowing you to reference the objects in either order.

What can ArrayList hold? A. objects, B. primitives

It can hold *only objects* (not primitives). But you can use autoboxing (automatically convert primitives into wrapper classes)

What array elements can refer to if array is declared as interface type?

It can refer to any instance of any class that *implements the interface* (or it's superclasses might implement the interface)

What does StringBuffer class do?

It has exactly same methods as StringBuilder class, but StringBuilder is faster because it's methods are not synchronized (Recommended to always use StringBuilder)

Which constructors String class has?

It has zillion of constructors. I.e. String s = new String("abc"); String s = "abc";

What would happen if you create a new String without assigning it to any reference variable?

It will be lost to a program

What will this statement return? "String".replace('g','g') == "String"

It will return *true* 1. replace() method usually creates a new String object. 2. replace() method returns the same String object if both the parameters are same, i.e. if there is no change.

What will happen if we are trying to access one-dimensional array through two-dimensional array reference variable?

It will throw *ClassCastException* at runtime

What is Autoboxing?

It's when Java automatically *converts primitive to a relevant wrapper object.* It happens in ArrayLists. When you add primitive, it's autoboxed to a wrapper.

What happens after execution of this code? String s = "abcdef"; s.concat("ghi");

JVM creates *new String object* with"abcdefghi" value and this object becomes *lost*

Is empty String (String str = "";) and null the same?

No

Can we extend String class?

No It's final

Which exception you gonna get if you try to use an array element in an object array, if that element does not refer to a real object?

NullPointerException

Can we use constructors of date and time classes?

The date and time classes have *private constructors* to force you to use the static methods

What will happen if you redirect a String reference to a new String?

The old String *will be lost* (If you didn't assign it to another variable before)

What is the output of following code? String[] strings = { "10", "9", "100" }; Arrays.sort(strings); for (String string : strings) System.out.print(string + " ");

This code outputs *10 100 9*. The problem is that String sorts in alphabetic order, and 1 sorts before 9. (Numbers sort before letters and uppercase sorts before lowercase)

How to convert from Array to ArrayList?

Using *String [ ] array = {"hawk", "robin"};* *List<String> list = Arrays.asList(array);* When converting from Array to ArrayList, the original array and created array backed List are linked. When a change is made to one, it is available in the other. It is a fxed-size list and is also known a backed List because the array changes with it.

Are ArrayLists zero-based?

Yes

Can *ArrayLists* have duplicate entries?

Yes

Can dimensions in multidimensional array have different lengths?

Yes

What's wrong with this code? (if anything) double[][] daa = new double[1][1]; daa[1][1] = new double[3];

daa[1][1] will cause an *ArrayIndexOutofBoundsException* because daa's length is only 1 and the indexing starts from 0. To access the first element, you should use daa[0][0].

Which overloaded versions of String's substring method do we have?

public String substring (int beginIndex); public String substring (int beginIndex, int endIndex);

What's wrong with this code? (if anything) List<String> sl= new List<String>();

*It won't compile.* *List is interface* You can't instantiate interface. You can do List<String> sl = new ArrayList<String>();

Which of the following are output by this code? (Choose all that apply) 3: String s = "Hello"; 4: String t = new String(s); 5: if ("Hello".equals(s)) System.out.println("one"); 6: if (t == s) System.out.println("two"); 7: if (t.equals(s)) System.out.println("three"); 8: if ("Hello" == s) System.out.println("four"); 9: if ("Hello" == t) System.out.println("five"); A. one B. two C. three D. four E. five F. The code does not compile.

*A. C. D.* The code compiles fine. Line 3 points to the String in the string pool. Line 4 calls the String constructor explicitly and is therefore a different object than s. Lines 5 and 7 check for object equality, which is true, and so print one and three. Line 6 uses object reference equality, which is not true since we have different objects. Line 7 also compares references but is true since both references point to the object from the string pool. Finally, line 8 compares one object from the string pool with one that was explicitly constructed and returns false.

Which of the following are true? (Choose all that apply) A. Two arrays with the same content are equal. B. Two ArrayLists with the same content are equal. C. If you call remove(0) using an empty ArrayList object, it will compile successfully. D. None of the above

*B, C*. An array does not override equals() and so *uses object equality*. ArrayList does override equals() and defines it as the same elements in the same order. The *compiler does not know* when an index is out of bounds and thus can't give you a compiler error. The code will throw an exception at runtime, though.

What is the output of the following code? LocalDate date = LocalDate.parse("2018-04-30", DateTimeFormatter.ISO_LOCAL_ DATE); date.plusDays(2); date.plusHours(3); System.out.println(date.getYear() + " " + date.getMonth() + " " + date.getDayOfMonth()); A. 2018 APRIL 2 B. 2018 APRIL 30 C. 2018 MAY 2 D. The code does not compile. E. A runtime exception is thrown.

*D*. A LocalDate does not have a time element. Therefore, it has no method to add hours and the code does not compile.

What is the result of the following? List<String> 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.* List is initialized with String generics. So it should be sorted as Strings, not as Integers. 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 statements? 6: List<String> list = new ArrayList<String>(); 7: list.add("one"); 8: list.add("two"); 9: list.add(7); 10: for(String s : list) System.out.print(s); A. onetwo B. onetwo7 C. onetwo followed by an exception D. Compiler error on line 9. E. Compiler error on line 10.

*D.* The code *does not compile* because list is instantiated using generics. Only String objects can be added to list and 7 is an int.

What is the output of the following code? LocalDateTime d = LocalDateTime.of(2015, 5, 10, 11, 22, 33); Period p = Period.of(1, 2, 3); d = d.minus(p); DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT); System.out.println(d.format(f)); A. 3/7/14 11:22 AM B. 5/10/15 11:22 AM C. 3/7/14 D. 5/10/15 E. 11:22 AM F. The code does not compile. G. A runtime exception is thrown.

*E.* Code compiles. Even though d has both date and time, the formatter only outputs time.

What is the output of this code? 4. int total = 0; 5: StringBuilder letters = new StringBuilder("abcdefg"); 6: total += letters.substring(1, 2).length(); 7: total += letters.substring(6, 6).length(); 8: total += letters.substring(6, 5).length(); 9: System.out.println(total); A. 1 B. 2 C. 3 D. 7 E. An exception is thrown. F. The code does not compile

*E.* Line 6 adds 1 to total because substring() includes the starting index but not the ending index. Line 7 adds 0 to total. Line 8 is a problem: Java does not allow the indexes to be specified in reverse order and the code *throws a StringIndexOutOfBoundsException*

What is the output of the following code? LocalDate date = LocalDate.of(2018, Month.APRIL, 40); System.out.println(date.getYear() + " " + date.getMonth() + " " + date.getDayOfMonth()); A. 2018 APRIL 4 B. 2018 APRIL 30 C. 2018 MAY 10 D. Another date. E. The code does not compile. F. A runtime exception is thrown

*F.* It compiles. Java throws an exception if invalid date values are passed. There is no 40th day in April—or any other month for that matter.

What is the result of the following code? StringBuilder b = "rumble"; b.append(4).deleteCharAt(3).delete(3, b.length() - 1); System.out.println(b); A. rum B. rum4 C. rumb4 D. rumble4 E. An exception is thrown. F. The code does not compile

*F.* This is a trick question. *The first line does not compile because you cannot assign a String to a StringBuilder.* If that line were StringBuilder b = new StringBuilder("rumble"), the code would compile and print rum4. Watch out for this sort of trick on the exam.

What is the output of following code? String x = new String("Hello World"); String y = "Hello World"; System.out.println(x == y);

*False* Since you have specifcally requested a different String object, the pooled value isn't shared.

What is the output of following code? String x = "Hello World"; String z = " Hello World".trim(); System.out.println(x == z);

*False* We don't have two of the same String object. Although x and z happen to evaluate to the same string, after trim() is run, the new String is created in String Pool. Therefore z does not refer to the same String object in String Pool and result is false. But these Strings are meaningfully equal, and if to compare them with equals() method, it'd return true.

What is the output of following code? StringBuilder one = new StringBuilder(); StringBuilder two = new StringBuilder(); StringBuilder three = one.append("a"); System.out.println(one == two); System.out.println(one == three);

*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 points to the same StringBuilder object as one. And Stringbuilers are mutable. This means one and three both point to the same object and the second print statement gives us true

What is the result of following binarySearches performed on an array? int[] numbers = {2,4,6,8}; //a System.out.println(Arrays.binarySearch(numbers, 2)); //b System.out.println(Arrays.binarySearch(numbers, 4)); //c System.out.println(Arrays.binarySearch(numbers, 1)); //d System.out.println(Arrays.binarySearch(numbers, 3)); //e System.out.println(Arrays.binarySearch(numbers, 9));

*a. 0* Line a searches for the index of 2. The answer is index 0 *b. 1* Line b searches for the index of 4, which is 1. *c. -1* Line c searches for the index of 1. Although 1 isn't in the list, the search can determine that it should be inserted at element 0 to preserve the sorted order. Since 0 already means something for array indexes, Java needs to subtract 1 to give us the answer of -1 *d. -2* Line d is similar to c. Although 3 isn't in the list, it would need to be inserted at element 1 to preserve the sorted order. We negate and subtract 1 for consistency, getting -2. *e. -5* Finally, line e wants to tell us that 9 should be inserted at index 4. We again negate and subtract 1, getting -4 -1, also known as -5.

What does *addAll()* method do?

*addAll(Collection<? extends E> c)* Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.

Which java package contains *Date/Time* classes?

*java.time package* You should import it like import java.time.*;

What method will print Array content?

*java.util.Arrays.toString(myArray);* It'll print "[Lorem, Ipsum, Dolor]" Method introduced in Java 5

What does String's *intern()* method does?

*public String intern()* Returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

What does *sublist(int1, int2)* method of List class return?

*subList(int fromIndex, int toIndex)* Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

When JVM finds a String literal it's added to the ...

... String literal pool

Arrays can hold primitives and objects but array itself is always ...

... an object

Chained methods are evaluated ...

... from left to right

The last index you can access in an Array is always one less than ...

... length attribute value

List all the possible ways to declare an ArrayList

1. *ArrayList list1 = new ArrayList();* Create empty ArrayList with default size 2. *ArrayList list2 = new ArrayList(10);* Create empty ArrayList with size 10 3. *ArrayList list3 = new ArrayList(list2);* Create ArrayList copying another ArrayList. It'll copy it's elements and size. 4. *ArrayList<String> list4 = new ArrayList<String>();* Create empty ArrayList which will accept String elements using generics syntax 5. *ArrayList<String> list5 = new ArrayList<>();* As of Java 7 we can omit generic declaration in right side 6. *List<String> list6 = new ArrayList<>();* Polymorphic ArrayList declaration using parent class of ArrayList - List.] 7. *ArrayList<String> list7 = Arrays.asList("first", "second");* Creating Arraylist from anonymous array with two elements.

Given StringBuffer sb1 = new StringBuffer("hi"); StringBuffer sb2 = new StringBuffer("hi"); StringBuffer sb3 = new StringBuffer("hello"); StringBuffer sb4 = sb3; What will be returned from 1. sb1.equals(sb2) 2. sb3.equals(sb4)

1. *False* 2. *True* The StringBuffer class *doesn't override* the equals() method, so two different StringBuffer objects with the same value will not be equal according to the equals() method.

Given String s1 = "hi"; String s2 = "hi"; String s3 = "hello"; String s4 = s3; What will be returned from 1. s1.equals(s2) 2. s3.equals(s4)

1. *True* 2. *True* String class's equals() method has been overridden so that two different String objects with the same value will be considered equal according to the equals() method.

1. Strings have a method called ... 2. Arrays have an attribute called ...

1. ... length() 2. ... length

Which values can 1. Array of primitives accept? 2. Array of objects accept?

1. Any value that can be promoted implicitly to the array's declared type, for example a byte variable can go into int array 2. Any object that passes the IS-A test (of instanceof) for the declared type of the array. For ex., if Horse extends Animal, Horse object can go into Animal array

What do following expressions mean? 1. String[] sa1, sa2; 2. String sa1[], sa2;

1. Here, both - sa1 and sa2 are String arrays. 2. Here, only sa1 is a String array. sa2 is just a String.

What is the result of binarySearch in array in below scenarios? 1. Target element found in sorted array 2. Target element not found in sorted array 3. Unsorted array

1. Index of match 2. Negative value showing one smaller than the negative of index, where a match needs to be inserted to preserve sorted order 3. A surprise—this result isn't predictable

1. How to get current time? 2. How to get date of January 1st 2015

1. LocalTime rightNow = LocalTime.now() 2. LocalDate ourDate = LocalDate.of(2015, Month.JANUARY, 1); or LocalDate ourDate = LocalDate.of(2015, 1, 1);

Which are the steps of making an array?

1. Make a reference variable (declare) 2. Make an array object (construct) 3. Populate array with elements (initialize)

Which of these is immutable? 1. String objects 2. String reference variables

1. String objects are immutable 2. String objects are not immutable

What are 2 key things to know about *StringBuilders*?

1. StringBuilder objects are *mutable* - they can change without creating a new object 2. StringBuilder methods act on the invoking objects, and objects *can change without an explicit assignment* in the statement

1. Will StringBuilder's capacity update automatically if append() grows a StringBuilder past it's capacity 2. Will StringBuilder's capacity be updated automatically if insert() starts within a StringBuilder's capacity, but ends after the current capacity? 3. Will StringBuilder's capacity be updated automatically if insert() start after StringBuilder's capacity?

1. Yes 2. Yes 3. No (exception will be thrown)

1. Where to place brackets in array declaration? 2. Is it legal to include the size of an array in the array declaration?

1. You can place it *either to the left or to the right* of array variable name (but recommended to place to the left) 2. *No. It's not legal*. You must include the size of an array when you construct it (unless you are creating an anonymous array)

ArrayList methods to remember are ...

1. add(element) 2. add(index, element) 3. clear() 4. contains(element) 5. get(index) 6. indexOf(element) 7. remove(index) 8. remove(element) 9. size()

StringBuilder methods to remember?

1. append 2. delete 3. insert 4. reverse 5. deleteCharAt() 6. toString() 7. length() 8. charAt() 9. indexOf() 10. substring()

String methods to remember are ...

1. charAt() 2. concat() 3. equalsIgnoreCase() 4. length() 5. replace() 6. substring() 7. toLowerCase() 8. toUpperCase() 9. toString() 10. trim()

What is the capacity of following StringBuilder constructor? 1. new StringBuilder(); 2. new StringBuilder("ab"); 3. new StringBuilder(x);

1. default capacity = 16 chars 2. cap = 16 + arg's length 3. cap = x (an integer)

What is the syntax 1. For normal array declaration? 2. For anonymous array declaration?

1. int[] myIntArray = new int[5]; 2. int[] myIntArray = new int[] {1,2,3,4,5}; we don't need to assign it to any reference

What is the problem with this code (if any) 20: String[] array = { "hawk", "robin" }; 21: List<String> list = Arrays.asList(array); 22: System.out.println(list.size()); 23: list.set(1, "test"); 24: array[0] = "new"; 25: for (String b : array) System.out.print(b + " "); 26: list.remove(1);

After line 20 array contains [hawk, robin] Line 21 converts the array to a List and returns fixed size list (backed version of a List). Line 22 outputs 2 Line 23 is okay because set() merely replaces an existing value. It updates both array and list because they point to the same data store. Now we have [hawk, test] Line 24 also changes both array and list and makes them contain [new, test] Line 25 outputs new, test Line 26 throws an UnsupportedOperation Exception because we are not allowed to change the size of the list.

What is the main difference between *Strings* and *StringBuilders*?

Strings are *immutable* StringBuilders are *mutable* - they can change without creating new objects

How *System.arraycopy()* method works?

The arraycopy method *public static void arraycopy (Object src, int srcPos, Object dest, int destPos, int length)* basically copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. The last parameter is the number of elements that you want to copy. Throws: IndexOutOfBoundsException - if copying would cause access of data outside array bounds. ArrayStoreException - if an element in the src array could not be stored into the dest array because of a type mismatch. NullPointerException - if either src or dest is null.


Set pelajaran terkait

Hunter education NYS : chapter quiz chapters 1-10

View Set

Blood Banking Chapter 12 - Donors

View Set