Chapter 3: Core Java APIs Flashcards

Covers using operators, Arrays, Strings & StringBuilder, ArrayList, classes from java.time & wrapper classes

1
Q

What are the features of an ArrayList

A

1) its an ordered list 2) Dynamic in size 3) Allows duplicates

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What must you do before using the ArrayList class?

A

you must import the ArrayList class using either : import java.util.*; (imports entire package) OR import java.util.ArrayList; (imports just the class)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How many ways can you create an ArrayList for the purposes of the exam?List them

A

You can use 3 different constructors ArrayList list = new ArrayList( ); // sets elements to their default values ArrayList list2 = new ArrayList(10); // set the initial capacity ArrayList list3 = new ArrayList(list2); // creating a copy of another list. This constructor takes a collection as a param.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What interface does List extend? How would you create a new type of this interface

A

Interface extends Collection. Collection collection = new ArrayList( ) OR Collection collection2 = new ArrayList<>( );

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Name all the methods for the ArrayList (only the ones you need to know for the exam).

A

add( ) , set( ) remove ( ) , contains ( ) equals ( ) , clear ( ) IsEmpty ( ) , size ( )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Will this compile? Explain.

ArrayList list = new ArrayList <>( );

list.add(Boolean.TRUE);

A

No because we are using generics to specify that this list only accepts type String which Boolean.TRUE isn’t.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Will this compile? Explain.

ArrayList list = new ArrayList( );

list.add(Boolean.TRUE); list.add(“hawk”);

A

Yes, as we haven’t specified a type for this list, we can add any object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does this code do?

List <string>birds = new ArrayList&lt;&gt;( );</string>

birds. add(“hawk”);
birds. add(1, “robin”);

A

it adds “hawk” to the end of the birds list and then adds “robin” to index 1 of the list which is after “hawk”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What will be the output of this code? List<> list1 = new ArrayList( ); list1. add(“hello”)

A

It won’t compile as the diamond operator on the RHS is empty. it should have a type declared inside

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are the method signatures for remove( ) method of an arrayList?

A

boolean remove(Object) // returns a boolean when an element is passed in. AND E remove(int index) // removes an element at the set index

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

In arrayList, what is the method signature for set( )? what does this method do?

A

E set (index, newElement). set( ) replaces an element at the index provided with the new element passed in

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What do the IsEmpty( ) and size( ) methods of ArrayList return when called independently?

A

A boolean and an int

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What does ArrayLists clear( ) method do?

A

clear () empties all the contents of the list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

what does the ArrayList contains( ) do?

A

it checks to see whether the list has the specified value and returns a boolean

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

what is the output of this code?

List<string> one = new ArrayList&lt;&gt;( );</string>

List<string> two = new ArrayList&lt;&gt;( );</string>

one. add(“a”); one.add(“b”);
two. add(“a”);
two. add(0, “b”);

System.out.println(one.equals(two));

A

false. because for the equals to return true, the size and the order of the list has to be the same

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What does the equals() method do?

A

it checks whether the two lists contain the same elements and in the same order.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the method for converting a String into an int primitive?

A

parseInt( ) e.g : int primitive = Integer.parseInt(“123”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the method for converting a String into an Integer wrapper class?

A

valueOf( ) e.g: Integer wrapper = Integer.valueOf(“123”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How do you convert a String into a boolean primitive and a float primitive?

A

Boolean.parseBoolean(“true”); Float.parseFloat(“2.2”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do you convert a String into a Boolean and Float wrapper class?

A

Boolean.valueOf(“true”); Float.valueOf(“2.2”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How do you convert a String into a Character wrapper class

A

No such method exists, you just call charAt normally.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is Autoboxing?

A

This is when Java automatically converts a primitive into its relevant wrapper class. This is great as ArrayLists aren’t allowed to contain primitives

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is unboxing?

A

When you convert a wrapper into a primitive

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What happens on line 1 & 2 of this code? List heights = new ArrayList<>( ); heights. add(null); // 1 int h = heights.get(0); // 2

A

// 1 compiles fine as you can assign null to any variable reference. // 2 will result in a NullPointerEx as you are calling a method on null

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

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

A

1 is the output! As you recall the remove method also takes the index as a param thus this is invoked instead of autoboxing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

How do you convert an ArrayList into an array?

A

ArrayList has a method called “toArray” that you can call on a list. You can then only assign that value to an object array unless you explicitly specify the type of array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Example of converting a list into an array and specifying the type of the array.

A

String[] array = list.toArray( new String [0]); Even though the code says to create an array of size 0, java will figure it out and create a new array to fit the actual size of the array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

How do you convert an Array into a List?

A

you can use the Arrays.asList( ) method that takes the original array as a paramater.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

How do you sort an ArrayList?

A

Using Collections.sort( list )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What happens when you convert an Array into a list?

A

1)The list remains fixed meaning you can’t change its size 2)Any changes you make to the list using set() will also update the original array as both refs are pointing to the same data

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What interface does ArrayList implement? How do you create a new type of this interface?

A

ArrayList implements List. List list = new ArrayList( ) OR List list2 = new ArrayList<>( );

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Post Java 5, how else can you create an ArrayList? Give two variations of this.

A

Using generics which allow you to specify the “type” you want to store in the list. It uses the diamond operator e.g :

1) ArrayList list1 = new ArrayList( );
2) ArrayList<boolean> list2 = new ArrayList&lt; &gt;( );</boolean>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What are the string concatenation rules?

A
  1. When used with numbers it is used for addition.
  2. If used with Strings/booleans, + means concatenation, The expression is evaluated left to right.
    3) When used with += it is added on the end of a string
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What would be the output of this code? int one = 1, two = 2, four = 4; String three = “3”; System.out.println( one + two + three + four);

A

output is 334. this expression is evaluated from left to right, 1 & 2 are added together to get 3 then “3” & 4 are added to the end of 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

1)System.out.println(1 + 2); 2)System.out.println(“a” + “b”); 3)System.out.println(“a” + “b” + 3); 4)System.out.println(1 + 2 + “c”);

A

1) 2 2) ab 3) ab3 4) 2c

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What is the signature for the charAt method?

A

char charAt(int index) - allows you to find out what character is at the specific index in a string. Note: if you call an index that is beyond the string, you get a StringIndexOutOfBoundsException

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What is the signature for the indexOf method?

A

int indexOf() returns the index of a string and can take various parameters ; it can work with indv characters or the whole string

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What does the indexOf method do and what is the signature?

A

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) 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What is the method signature of String’s substring and what does it do?

A

subString(int beginIndex) Or

subString(int beginIndex, int endIndex)

This method takes one or two indexes and returns part of a string. The end index is exclusive which means that it isnt included in the output and the counting stops right before that index.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What is the output on each line of code?

String String = “Hello World!”; System.out.println(String.substring(3)); //1

System.out.println(String.substring(String.indexOf(“ W”))); //2

System.out.println(String.charAt(8)); System.out.println(String.substring(6,6)); // 3

System.out.println(String.substring(6,12)); // 4

System.out.println(String.substring(6,12)); // 5

System.out.println(String.substring(5,13)); //6

System.out.println(String.trim()); // 7

A

1) lo World
2) World// a space then world
3) nothing will be printed as 6 is exclusive
4) World
5) World!// eventhough there are only 11 characters, it is legal to access up 1 past the end of the sequence which in this case is 12.
6) StringIndexOutOfBoundsException
7) Hello World!// trim removes spaces before and after but not in the middle thus the string will remain unchanged

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

What does it mean that Strings are immutable?

A

It means that once created, they can’t be changed, you can add or remove things

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What is the string pool?

A

Storage in the jvm that holds string literals e.g “hello”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What is the difference between == and Strings equals method?

A

== checks for the equality of references so it will only return true if the references are pointing to the same object

equals returns true if the contents inside the string are the same. The two references don’t have to be pointing to the same object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

True or False:

String x1 = “a”;

String x2 = new String(“a”);

x1.equals(x2). // 1

x1 == x2 // 2

A

1) True because even though x1 and x2 are pointing to different objects, the content of the objects are same
2) False as the references are pointing to different objects

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

Convert the string “1” to a long primitive

A

long num = Long.parseLong(“1);

46
Q

What will the output of this code be?

List list4 = new ArrayList();

list4. add(“hawk”);
list4. add(“robin”);

Object[] objectArray = list4.toArray(); // 1

System.out.println(objectArray.length); // 2

String[] stringArray = list4.toArray(new String[0]); // 3

System.out.println(stringArray.length); // 4

A

Line 4 will not compile because an object/ array will not fit into a String array reference without explicit cast.list. toArray() returns a type of Object[]

If the cast (String[] ) was present on line 3, the answer would be 2 & 2 which shows us that the arrays are basically copies

Additionally on line 3, the initialisation (new String [0]) iniside the toArray method is improtant as you are letting the jvm know explicitly that we require a string arrary. without this, a runtime error would occur

47
Q
What is the output of the following code?
StringBuilder a = new StringBuilder("abc");
StringBuilder b = a.append("de");
b = b.append("f").append("g");
System.out.println("a=" + a);
System.out.println("b=" + b);
A

a=abcdefg
b=abcdefg

There is only one StringBuilder object as StringBuilder was called just the once. Thus both references are pointing to the same object, changes made on one variable will reflect on the other

48
Q

What are the 3 ways you can create a StringBuilder?

A

StringBuilder sb1 = new StringBuilder();

StringBuilder sb2 = new StringBuilder(“animal’);

StringBuilder sb3 = new StringBuilder(10); // asking to reseve a certain no of slots for the eventual value aka capacity

49
Q

StringBuilder sb = new StringBuilder(“start”);

sb.append(“+middle”);

Stringbuilder same =sb.append(“+end”);

What is the output of sb and same?

A

Both variables output: start+middle+end

StringBuilder changes its own state and returns a reference to itself. Here sb and same point to the exact same object and as a result print the same value.

50
Q

Will line 1 of this code compile?

StringBuilder sb = new StringBuilder(“animal”);

sb.append(“+middle”);

StringBuilder same = sb.append(“+end”);

System.out.println( sb + same); //1

A

No, the concatenation operator can’t be used with StringBuilder

append is the StringBuilders version of +

51
Q

What are some of the methods of StringBuilder?

A

append()

Insert() // adds chars to the SB

delete( ), deleteCharAt( )

reverse( )

toString ( )

The following are also similar to Strings methods:

charAt() , indexOf, length(), substring()

52
Q

True or false?

StringBuilder one = new StringBuilder( );

StringBuilder two = new StringBuilder( );

StringBuilder three = one.append(“a”);

System.out.println(one == two); // 1

System.out.println(one == three); // 2

A

1) false, one and two point to completely seperate objects
2) true, as references are pointing to the same obj

53
Q

True or False?

String x = “Hello World”;

String z = “ Hello World”.trim( );

System.out.println(x == z);

A

false // eventhough we have two of the same string literal, a new object was created for string z at run time when trim() was called.

54
Q

What is the output of the following code?

LocalDate date = LocalDate.of(2020, Month.JANUARY, 20);
LocalTime time = LocalTime.of(5, 15);
LocalDateTime dateTime = LocalDateTime.of(date, time);
System.out.println(dateTime);
datetime = dateTime.minusDays(1);
System.out.println(dateTime);
dateTime = dateTime.minusHours(10);
System.out.println(dateTime);
dateTime = dateTime.minusSeconds(30);
System.out.println(dateTime);

A

2020-01-20T05:15
2020-01-19T05:15
2020-01-18T19:15
2020-01-18T19:14:30

55
Q

What is the output of this code?

String result = “AniMal “.trim().toLowerCase().replace(‘a’, ‘A’);

System.out.println(result);

A

AnimAl

56
Q

What does the following code output?

StringBuilder sb = new StringBuilder(“abcdef”);

sb. delete(1,3); // 1
sb. deleteCharAt(5); // 2

A

1) adef// like the substring it takes 2 params, the begin and end index; the end index is exclusive.
2) throws a StringIndexOutOfBoundsEx

57
Q

What is the method signature for the insert method of the StringBuilder?

A

StringBuilder insert(int offset, String str)

offset is the index where we want to insert the requested param ( can be a string, boolean, int, char, char array , object etc. theres a no of constructors)

e.g

StringBuilder sb = new StringBuilder(“animals”);

sb.insert(7, “-“); // sb = animals-

58
Q

What is the output of the following code?

StringBuilder puzzle = new StringBuilder("Stephen");
System.out.println(puzzle);
puzzle.substring(1);
System.out.println(puzzle);
A

Stephen

Stephen

the substring method prints tephen but returns a String which is why puzzle is unchanged

59
Q

What would the output of the following code be?

public class ArrayType {

public static void main(String args[]) {
String [] bugs = {“cricket”, “beetle”, “ladybug”};
String [] alias = bugs;
System.out.println(bugs.equals(alias));
System.out.println(bugs.toString());
}
}

A

true // we can call equals cos an array is an object
[Ljava.lang.String;@160bc7c0 // L is the type of array , String is the reference type and the no is the hashcode

60
Q

What would the output of the following code be?

int[] newVals = {};
newVals[0] = 1;
newVals[1] = 2;
if (newVals == null) {
System.out.println(“newVals is null”);

} else {
System.out.println(“newVals is not null”);
}

A

Index out of bounds exception on this line:
newVals[0] = 1; // this is due to the fact that arrays can’t change their size once they have been created.

61
Q

What is an Array?

A

An array is an ordered list that can contain duplicates.

62
Q

How would you instantiate an anonymous array?

A

int [] numbers = {42, 55, 99};

63
Q

What is the output of this code?

String [] stringsArray = new String[3];

stringsArray[0] = “”;

for (String str : stringsArray) System.out.println(str);

A

blank space

null

null

Note: remember you can ommit the parenthesis in the for loop for a single statement

64
Q

What is the syntax for sorting an array?

A

int numbers [] = {6,9,1};

Arrays.sort(numbers);

65
Q

What will this print?

int numbers [] = {6,9,1};

Arrays.sort(numbers);

System.out.println(numbers)

A

A hascode of I@2bd9c3e7.

You have to loop through an array in order to print the values

66
Q

What must you do before using an array’s methods??

A

you must either import the class or package like so:

import java.util.*

import java.util.Arrays

or

use java.util.Arrays.someArrayMethod( )

67
Q

What is the output of this code?

int [] a = {1,2,3,4}

int [] b = {2,3,1,0}

System.out.println( a [(a=b)[3] ] )

A

It prints 1. // statement is evaluated from left to right

1) a on the LHS is assigned the value of the a array
2) inside the paranthesis, array b is assigned to a
3) it now looks like this a[b[3] ]; b[3] = 0 // acceses the 4th index of the b array
4) finally a[0] accesses index 0 of array a which is 1.

68
Q

What are the 3 ways of creating arrays?

A

int numbers = new int [5] // an empty array

OR

int [] numbers = new [] {1,2,3,4,5} // an initialised array

&

int [] numbers = {1,2,3,4,5} // an anonymous array

69
Q

What will be the result of trying to compile and execute the following program? public class TestClass{

public static void main(String args[] ){

int i = 0 ;

int[] iA = {10, 20} ;

iA[i] = i = 30 ;

System.out.println(“”+ iA[0] + “ “ + iA[1] + “ “+i) ; } }

A

It will print 30 20 30

The statement iA[i] = i = 30 ; will be processed as follows:
iA[i] = i = 30; => iA[0] = i = 30 ; => i = 30; iA[0] = i ; => iA[0] = 30 ;

Here is what JLS says on this:
1 Evaluate Left-Hand Operand First
2 Evaluate Operands before Operation
3 Evaluation Respects Parentheses and Precedence
4 Argument Lists are Evaluated Left-to-Right

For Arrays: First, the dimension expressions are evaluated, left-to-right. If any of the expression evaluations completes abruptly, the expressions to the right of it are not evaluated.

70
Q

The following class will print ‘index = 2’ when compiled and run?

class Test {

public static int[] getArray() { return null; }

public static void main(String[] args){

int index = 1;

try{

getArray()[index=2]++;

}

catch (Exception e){ } //empty catch

System.out.println(“index = “ + index);

}

}

A

True

If the array reference expression produces null instead of a reference to an array, then a NullPointerException is thrown at runtime, but only after all parts of the array reference expression have been evaluated and only if these evaluations completed normally.

This means, first index = 2 will be executed, which assigns 2 to index. After that null[2] is executed, which throws a NullPointerException. But this exception is caught by the catch block, which prints nothing. So it seems like NullPointerException is not thrown but it actually is.

In other words, the embedded assignment of 2 to index occurs before the check for array reference produced by getArray().

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.

71
Q

What will happen when the following code is compiled and run?

class AX{

static int[] x = new int[0];

static{

x[0] = 10;

}

public static void main(String[] args){

AX ax = new AX();

}

}

A

It will throw ExceptionInInitializerError at runtime.

The following is the output when the program is run:
java.lang.ExceptionInInitializerError
Caused by: java.lang.ArrayIndexOutOfBoundsException: 0
at AX.(SM.java:6)
Exception in thread “main”
Java Result: 1

Note that the program ends with ExceptionInInitializerError because any exception thrown in a static block is wrapped into ExceptionInInitializerError and then that ExceptionInInitializerError is thrown. Remember that a static or instance initializer can only throw a RuntimeException.

If you try to throw a checked exception from a static block to the outside, the code will not compile.

An instance block is allowed to throw a checked exception but only if that exception is declared in the throws clause of all the constructors of the class.

Even though the line x[0] = 10; will throw java.lang.ArrayIndexOutOfBoundsException, JVM will wrap it and rethrow java.lang.ExceptionInInitializerError.

72
Q

What will the following code snippet print?

int index = 1;

String[] strArr = new String[5];

String myStr = strArr[index];

System.out.println(myStr);

A

null

73
Q

what will this output?

String[] strings = {“10”, “9”, “100”};

Arrays.sort(strings);

for (String string : numbers)

System.out.println(string + “ “);

A

10 100 9 // String sorts in alphabetical order 1 in 10 & 100 comes before 9

74
Q
What will the following class print when run?
public class Sample{
 public static void main(String[] args) {
 String s1 = new String("java");
 StringBuilder s2 = new StringBuilder("java");
 replaceString(s1);
 replaceStringBuilder(s2);
 System.out.println(s1 + s2);
 }
 static void replaceString(String s) {
 s = s.replace('j', 'l');
 }
 static void replaceStringBuilder(StringBuilder s) {
 s.append("c");
 }
}
A

javajavac

String is immutable while StringBuilder is not. So no matter what you do in replaceString() method, the original String that was passed to it will not change.

On the other hand, StringBuilder methods, such as replace or append, change the StringBuilder itself. So, ‘c’ is appended to java in replaceStringBuilder() method.

75
Q

What will the following code print?

System.out.println(“12345”.charAt(6));

A

It will throw an IndexOutOfBoundsException

Since indexing starts with 0, the maximum value that you can pass to charAt is its length-1 so in this case 4

charAt throws IndexOutOfBoundsException if you pass an invalid value (that is, if the index argument is negative or not less than the length of this string).

Both - ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException, extend IndexOutOfBoundsException and although in practice, the charAt method throws StringIndexOutOfBoundsException, it is not a valid option because the implementation is free to throw some other exception as long as it is an IndexOutOfBoundsException.

76
Q

What will the following program print?

public class TestClass{

static String str = “Hello World”;

public static void changeIt(String s){

s = “Good bye world”;

}

public static void main(String[] args){

changeIt(str);

System.out.println(str); } }

A

“Hello World”

Java supports pass by value for primitives and objects.

In the method changeIt(…) you are giving a new value to the local variable but the original reference remains the same.

An example:
 Object o1 = new Object(); //Let us say, the object is stored at memory location 15000.
 //Since o1 actually stores the address of the memory location where the object is stored, it contains 15000.

Now, when you call someMethod(o1); the value 15000 is passed to the method.

Inside the method someMethod():

someMethod( Object localVar) {
/*localVar now contains 15000, which means it also points to the same memory location where the object is stored.
Therefore, when you call a method on localVar, it will be executed on the same object.
However, when you change the value of localVar itself, for example if you do localVar=null,
it then starts pointing to a different memory location. But the original variable o1 still
contains 15000 so it still points to the same object. */

77
Q

Which of the following classes should you use to represent just a date without any time or zone information?

1) java.util.Date
2) java.sql.Date
3) java.time.Date
4) java.time.LocalDate

A

4) java.time.LocalDate
java. util.Date is the old package

78
Q

What classes are included in the java.time Package?

What are some of the features of these classes?

A

LocalDate, LocalTime, LocalDateTime, Instant, Period, Duration

These classes are immutable and thread Safe

79
Q

In what package can java.time.format.DateTimeFormatter be found?

A

java.time.format package

80
Q

Given the following line of code:

LocalDateTime dt = LocalDateTime.parse(“2015-01-02T17:13:50”);

Which of the following lines will return the date string in ISO 8601 format?

1) dt.format(java.time.format.DateTimeFormatter.DATE_TIME);
2) dt.format(java.time.format.DateTimeFormatter.ISO_DATE_TIME);
3) dt.format(java.time.format.DateTimeFormatter.LOCAL_DATE_TIME);
4) dt.toString();

A

2 & 4

LocalDateTime’s toString method generates the String in ISO 8601 format.

81
Q

what is the output of this code?
public String getDateString(LocalDateTime ldt){

return DateTimeFormatter.ISO_ZONED_DATE_TIME.format(ldt);

}

A

The code will compile but will always throw a DateTimeException (or its subclass) at run time.

Note that LocalDateTime class does not contain Zone information but **ISO\_ZONED\_DATE\_TIME** requires it. Thus, it will throw the following exception:
**Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: OffsetSeconds**

UnsupportedTemporalTypeException extends DateTimeException.

82
Q

Name 2 features of the Date-Time API?

A

It uses the calendar system defined in ISO-8601 as the default calendar.

Most of the actual date related classes in the Date-Time API such as LocalDate, LocalTime, and LocalDateTime are immutable.

These classes do not have any setters. Once created you cannot change their contents. Even their constructors are private.

83
Q

What will the following code print?

String abc = “”;

abc. concat(“abc”);
abc. concat(“def”);

System.out.print(abc);

A

It will print empty string (or in other words, nothing).

Strings are immutable so doing abc.concat(“abc”) will create a new string “abc” but will not affect the original string “”.

84
Q

How can you initialize a StringBuilder to have a capacity of at least 100 characters?

A

StringBuilder sb = new StringBuilder(100);

Or

StringBuilder sb = new StringBuilder();
sb.ensureCapacity(100); // Ensures that the capacity is at least equal to the specified minimum

Observe that the question says “at least 100 characters”. In the exam, you may get a question that says “100 characters”, in that case, ensureCapacity() may not be a valid option.

85
Q

Given:

abstract class Vehicle{ }

interface Drivable{ }

class Car extends Vehicle implements Drivable{ }

class SUV extends Car { }

Which of the following options will compile?

1) ArrayList<vehicle> al1 = new ArrayList&lt;&gt;();<br></br>SUV s = al1.get(0)</vehicle>
2) ArrayList<drivable> al2 = new ArrayList&lt;&gt;();<br></br>Car c1 = al2.get(0)</drivable>
3) ArrayList<suv> al3 = new ArrayList&lt;&gt;();<br></br>Drivable d1 = al3.get(0);</suv>
4) ArrayList<suv> al4 = new ArrayList&lt;&gt;();<br></br>Car c2 = al4.get(0);</suv>
5) ArrayList<vehicle> al5 = new ArrayList&lt;&gt;();<br></br>Drivable d2 = al5.get(0);</vehicle>

A

3 and 4 will compile // the rest will need to be cast as they are more general types being assigned to more specific types

86
Q

What would the output of the following code be?

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));

A

0
1
-1
-2
-5

87
Q

true/false, the following lines of code will compile:

public static void main(String[] args)
public static void main(String args[])
public static void main(String… args)

A

true

88
Q

What kind of results would you get when trying to do a binary search in the following array?

int[] numbers = {3, 2, 1, 5};

A

Unpredictable as the array hasnt been sorted first before the search

89
Q

When using Arrays.binarySearch, if no match is found, what happens?

A

it negates the position where the element would need to be inserted and subtracts 1.

90
Q

Arrays.binarySearch() searches a sorted array and returns what? What does it take as its parameters?

A

It takes the arrayList and an element in the list and returns the index of a match

91
Q

What calendar does the Date Time API work on?

A

The ISO-8601 calendar aka the gregorian calendar

92
Q

What import do you need inorder to use the date time package?

A

import java.time.*;

93
Q

If today is the 27th of October 2020 and the current time is 7.30 pm, print out the current date, time and dateTime .

A

you use the static now method

LocalDate.now(); // 2020-10-27

LocalTime.now(); // 19:30:43.875 hour:min:seconds:nanoseconds

LocalDateTime.now(); // 2020-10-27T19:30:43:875

94
Q

Given:

LocalDate d1 = LocalDate.parse(“2015-02-05”, DateTimeFormatter.ISO_DATE); LocalDate d2 = LocalDate.of(2015, 2, 5);

LocalDate d3 = LocalDate.now();

System.out.println(d1);

System.out.println(d2);

System.out.println(d3);

Assuming that the current date on the system is 5th Feb, 2015, which of the following will be a part of the output?

A

None of the mentioned.

All these prints will produce dates in this format : 2015-02-05

95
Q

What will this print?

Period period = Period.of(3,5,12);

System.out.println(period);

A

It will print P3Y5M12D.

inorder to get a date format, you have to use period with either the LocalDate or LocalDateTime objects

E.g - dateNow.minus(period); // 2017-05-15

or

dateTimeNow.minus(period); // 2017-05-15T21:15:56.280

If you use the time object, you will get a runtime exception

96
Q

What is the output of the following code?

DateTimeFormatter f = DateTimeFormatter.ofPattern(“dd MM yyyy”); // 1

LocalDate date = LocalDate.parse(“06 12 1992”, f ); //2

LocalTime time = LocalTime.parse(“11:22”);

System.out.println( “The date is: “ + date + "n” + “ The time is: “ + time);

A

The date is: 1992-12-06
The time is: 11:22

On line 1, we create a DTF object with pattern on dd MM yyyy.

On line 2, we use the parse method of LocalDate that takes a char sequence/ text and the preveiously DTF object. the text inside the parse params should match the pattern of the DTF obj otherwise, we get a runtime exception

97
Q

What is the output of the following code?
LocalDate date = LocalDate.of(2020, Month.JANUARY, 20);
date.plusDays(10);
System.out.println(date);

A

2020-01-20

As LocalDate is immutable it can’t be changed after its been created

98
Q

What method in the StringBuilder class does not modify the value of the object?

A

substring() // substring() returns a string and not a reference to the SB object thus calling this method will have no effect on the reference

99
Q

What is the output of the following code?

LocalDate d = LocalDate.of(2020, Month.JANUARY, 32);

A

DateTimeException which is a runtime exception

100
Q

What is the output of the following code?

LocalDate date = LocalDate.of(2020, Month.JANUARY, 20);
LocalTime time = LocalTime.of(5, 15);
LocalDateTime dateTime = LocalDateTime.of(date, time);
System.out.println(dateTime);
datetime = dateTime.minusDays(1);
System.out.println(dateTime);
dateTime = dateTime.minusHours(10);
System.out.println(dateTime);
dateTime = dateTime.minusSeconds(30);
System.out.println(dateTime);

A

2020-01-20T05:15
2020-01-19T05:15
2020-01-18T19:15
2020-01-18T19:14:30

101
Q

What is the output of the following code?

LocalDate date = LocalDate.of(2020, Month.JANUARY, 20);
LocalTime time = LocalTime.of(11, 12, 34);
LocalDateTime dateTime = LocalDateTime.of(date, time);
DateTimeFormatter shortF = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
DateTimeFormatter mediumF = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
System.out.println(shortF.format(dateTime));
System.out.println(mediumF.format(dateTime));

A

1/20/20 11:12 AM
Jan 20, 2020 11:12:34 AM

102
Q

What does this code print?

StringBuilder sb1 = new StringBuilder();

StringBuilder sb2 = sb1;

sb1.append(“girl,”); sb2.append(“woman,”); sb2.append(“other”);

System.out.println(sb1.equals(sb2));

System.out.println(sb1 == sb2);

System.out.println(sb1);

A

true
true
girl,woman,other. // sb1 & sb2 are pointing to the same object thus will have the same contents

equals method checks to see whether the references are pointing to the same object rather than looking at the values inside.

103
Q
A
104
Q

What does this code print?

Period p = Period.ofYears(5).ofDays(7).ofMonths(6);

A

P6M

Chaining methods doesnt work on Periods “of” method and will only evaluate the last method.

105
Q

Period period = Period.of(3,5,12);

period = period.minusMonths(3).plusDays(15).plusYears(4);

System.out.println(period)

A

P7Y2M27D

106
Q

What are some of the features of the java.time package?

A

Classes are immutable

The constructors are private which forces us to use their static methods

107
Q

Which class is concat method a member of?

A

String class

108
Q

What will be the output of this code?

public class Whiz{

public static void main(String [] args) {

chars[] chars = {‘1’,’Z’, ‘0’,’-‘,’8’,’1’};

StringBuilder sb = new StringBuilder();

sb. append(chars,0,chars.length-1);
sb. append(‘0’);
sb. append(‘8’);

System.out.println(sb); }}

  1. 1Z0-808
  2. 1Z0-8108
  3. 1Z0-810
  4. Compilation fails due to an error on line 6
  5. Compilation fails due to an error on line 7
A

1) 1Z0-808 is correct

We are using one of the overloaded versions of SB’s append method that takes a char sequence, starting index and length of the seq.

So this method will add the sub char array starting from index 0 up to 4 {1Z0-8} to sb then we continue to add 0 then 8 to make 1Z0-808.

109
Q

if “x.equals(y)” returns true, which of the folowing is true?

I. “y.hashCode()” must be equal to “x.hashCode()”

II. Both “x” and “y” objects should have the same field status

III. “y.hashCode()” must be equal to “x.hashCode()”

A

I is correct.

if “x.equals(y)” returns true, then the hashcodes of both objects must be equal

110
Q

Consider below code of Test.java file, What is the result?

package com.udayankhattry.oca;

import java.time.LocalDate;

public class Test {

public static void main(String [] args) {

LocalDate date = LocalDate.parse(“1983-06-30”);

System.out.println(date.plusMonths(8));

}

}

A

1984-02-29

Explanation:

plusMonths(long) method of LocalDate class returns a copy of this LocalDate with the specified number of months added.

This method adds the specified amount to the months field in three steps:

Add the input months to the month-of-year field

Check if the resulting date would be invalid

Adjust the day-of-month to the last valid day if necessary

For the given code,

1983-06-30 plus 8 months would result in the invalid date 1984-02-30. Instead of returning an invalid result, the last valid day of the month, 1984-02-29, is returned.

Please note, 1984 is leap year and hence last day of February is 29 and not 28.

111
Q

Given code of Test.java file:

public class Test {

public static void main(String[] args) {

args[1] = “Day!”;

System.out.println(args[0] + “ “ + args[1]);

}

}

What is the result?

  1. Compilation Error
  2. Good
  3. An exception is thrown at Runtime
  4. Good Day!
A

3.An exception is thrown at Runtime

When command java Test Goo is run, Good is passed into args. Now the args array is of sixe 1 with Good at index 0.

args[1] = “Day!” is trying to access index 1 which doesnt exist and thus will cause an ArrayIndexOutOfBoundsException

112
Q

Consider below code of Test.java file, what will be printed?

public class Test {

public static void main(String[] args) {

List<string> list = new ArrayList&lt;&gt;();</string>

list. add(“P”);
list. add(“O”);
list. add(“T”);

List<string> subList = list.subList(1, 2); //Line 1</string>

subList.set(0, “E”); //Line 2

System.out.println(list); //Line 3

}

}

A

[P,E,T] will be printed

  1. On line 1, we are creating a new list called sublist using List’s subList method. Similar to String’s subString method, it returns the element at the begining index inclusive and end index exclusive.
  2. So sublist = [O]
  3. On line 2 we replace the element at index 0 with E so sublist = [E]
  4. On line 3 list is printed: as we used list to create sublist, the two are now linked so whatever changes made to sublist are reflected in list.