Week 3 + Week 2 and 1 Review Flashcards

1
Q

What is a generic type?

A

A generic class or interface that is parameterized over types.

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

Why use Generics?

A

Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods.

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

Two types of generics? What does each do?

A

Generic method - introduce their own type parameters.
Generic class -

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

What is a generic method?

A

Exactly like a normal method but a generic method has type parameters that are cited by actual type.

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

Benefits of generic code over non-generic?

A
  • Stronger type checks at compile time. A java compiler applies strong type checking to generic code and issues errors if the code violates type safety.
  • Elimination of casts.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are generics commonly used with?

A

Collections.

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

What is a generic called when declared on a class?

A

Generic type.

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

Why are generics useful?

A

Because it can help you to restrict a class to only accept objects of a given type and the compiler will prevent you from using any other type.

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

Why would the following code benefit from generics? How would you implement that code?

List names = new ArrayList();

names. add(“Alice”);
name. add(new Object());

A

In this code you would have to hope that other developers would know to use a certain data type. Generics would make it so the developer can only use objects of a given type.

List names = new ArrayList<>();

names. add(“Alice”);
names. add(new Object());

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

What is the Collections Framework?

A

A set of classes and interfaces that implement commonly used data structures.

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

What is a collection?

A

A single object which acts as a container for other objects.

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

Are collections iterable?

A

yes.

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

Main difference between Collection and Map?

A

Collection’s are iterable, maps are not.

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

Three interfaces derived from the Collection interface?

A

List.
Queue.
Set.

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

Classes derived from the List interface?

A

ArrayList.
Vector.
LinkedList.

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

Classes derived from the Queue interface?

A

LinkedList.
Priority Queue.

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

Classes derived from the Set interface?

A

Hash Set.
Linked Hash Set.

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

What is a List in Java?

A

A collection that is ordered and preserves the ordered in which elements are inserted into the list.

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

What is a Vector?

A

An older class which implements List.

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

A thread safe implementation of an ArrayList.

A

Vector.

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

What should you use for implementing a stack?

A

ArrayDeque.

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

ArrayList(class) implements _______ which extends _______.

A

List (interface)
Collection

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

Set Extends _______ which Extends ________ which Implements ________.

A

Sorted Set.
Navigable Set.
Treeset.

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

What is the Set interface?

A

an unordered collection of objects in which duplicate values cannot be stored.

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

How can I make the following code generic?

public class Printer { }

A

Add the type parameter after the class name.

public class Printer { }

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

How can I make the following code print an Integer generic type, assume Printer is generic.

Printer printer = new Printer (5);
printer.print();

A

You need to specify the type.

Printer printer = new Printer<>(5);
printer.print();

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

Generics work with primitive types and wrapper class objects.

A

False. Generics don’t work with primitive types.

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

Find the error in the following code.

Printer doublePrinter = new Printer<>(“Hello”);
doublePrinter.print();

A

The generic type is asking for a double (), but we attempted to print out a string ( (“Hello”) ).

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

Where is the error in the following code?

ArrayList cats = new ArrayList<>();

cats. add(new Cat());
cats. add(new Dog());

A

The ArrayList which is set to is trying to add Dog.

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

Which package is List found in?

A

java.util

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

Which interface does List inherit?

A

Collection

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

What are the four implementation classes of List interface?

A

ArrayList.
LinkedList.
Stack.
Vector.

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

Declare an array of the names of 4 friends. Call it friendsArray.

A

String[] friendsArray = new String[4];

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

Declare an array of your friends with the names… John, Steph, Sam, Amy. Call it friendsArray

A

String[] friendsArray = {“John”, “Steph”, “Sam”, “Amy”};

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

Declare an ArrayList with reference name friendsArrayList.

A

ArrayList friendsArrayList = new ArrayList<>();

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

What is the import for ArrayList?

A

java.util.ArrayList

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

Which have a fixed size, Array or ArrayList? or neither? or Both?

A

Array’s have a fixed size.

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

Declare an ArrayList called friendsArrayList that holds the values John, Chris, Eric, and Luke.

A

ArrayList friendsArrayList = new ArrayList<>(Arrays.asList(“John”, “Chris”, “Eric”, “Luke” ));

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

How can you print out “Steph” from the Array?

String[] friendsArray = {“John”, “Steph”, “Sam”, “Amy”};

A

System.out.println(friendsArray[1]);

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

How can you print out “Eric” from the following:

ArrayList friendsArrayList = new ArrayList<>(Arrays.asList(“John”, “Chris”, “Eric”, “Luke” ));

A

System.out.println(friendsArrayList.get(2));

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

How would I get the length of an Array called friendsArray? Show code.

A

System.out.println(friendsArray.length);

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

How would I get the length of an ArrayList called friendsArrayList? Show code.

A

System.out.println(friendsArrayList.size());

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

how would I add string “Mitch” to an ArrayList called friendsArrayList?

A

friendsArrayList.add(“Mitch”);

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

How would I change the first value in an Array called friendsArray to “Carl”?

A

friendsArray[0] = “Carl”;

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

How would I change the first value in an ArrayList called friendsArrayList to “Carl”?

A

friendsArrayList.set(0, “Carl”);

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

How would I remove “Chris” from an ArrayList called friendsArrayList?

A

friendsArrayList.remove(“Chris”);

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

implement a class called multiThreadThing, which extends thread, in your main method and run two threads. Threads will be called myThing and myThing2

A

public static void main(String[] args) {

 multiThreadThing myThing = new multiThreadThing(); 
 multiThreadThing myThing2 = new multiThreadThing(); 

myThing.start();
myThing2.start();

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

Explain the following code.

for(int i = 0; i < 5; i++)

A

This is a for loop that starts from count 0 (i =0) and iterates through the loop (i++) until i is no longer less than 5 (i<5)

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

Which package are Maps in ?

A

java.util package

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

What is a map?

A

An interface that represents a mapping between a key and a value.

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

how would a maps interface apply to managers and employees relationship?

A

You can map managers and employees with Managers (Key) with a list of Employees(Value) being managed.

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

Can you create objects in an interface? if so, how would you do it? If not, what do you need?

A

No.

You need a class that extends the interface.

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

Identify the problem and fix the code, show solution:

public class Dog {

private String name;
private int age;

public void setName (String name) {
name = name;

A

name = name is setting the passed in String name to itself. So we need to add this. keyword.

public void setName(String name) {
this.name = name;

This will set this.name to the private String name, and set that to the String parameter in setName.

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

Identify the problem and fix the code, show solution:

public class Dog {

private String name;
private int age;

public void setName (String name) {
name = name;

A

name = name is setting the passed in String name to itself. So we need to add this. keyword.

public void setName(String name) {
this.name = name;

This will set this.name to the private String name, and set that to the String parameter in setName.

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

A constructor requires a return type? T/F?

A

False. a constructur can NOT have a return type.

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

Code the following:

class Main

main method

Create method called myMethod, pass through String name.

print out name in method.

call names Tom and Jim through myMethod in main Method.

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

What would I use if i wanted to iterate over a data structure?

A

for loop

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

count from 1-5 using a for loop.

A

for (int i = 0; i <= 5; i++)
System.out.println(i);

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

count from 1-5 using a while loop.

A

i = 1;
while (i <=5) {
System.out.println(i);
i++;

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

import a Scanner.

A

import java.util.Scanner

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

create a Scanner object called scan.

A

Scanner scan = new Scanner(System.in);

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

What is java type casting? Two types.

A

When you assign a value of one primitive data type to another type.
Wide (automatically)
narrow (manually)

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

When do I need to use casting?

A

When passing a smaller size type into a larger type size.

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

Cast the following code: go from double to int. name int variable ‘y’

double x = 9.5;

A

int y = (int) x;

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

Write code that manually boxes the following code. Name variable y.

double x = 5;

A

double y = new Double(x);

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

What are the two types of constructors?

A

No args.
Parameterized.

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

take a class called myClass and create a no args constructor from int num. set equal to 100.

A
public class myClass { 
 int num; 
 myClass() { 
 num = 100; 
} 
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

Add a paramterized constructor to the following code:

class myClass { 
 int x = 5;
A

myClass(int i) {
x = i

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

What is an access modifier? List them, and state their access level.

A

keyword which define the ability of other code to access the given entity.

public - available anywhere
protected - within the same package. and within same class.
default - within same package.
private - only within same class.

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

If i use the private access modifier, what will use to retrieve and change information within a private modifier.

A

Getters and Setters.

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

What is method overloading?

A

a feature that allows a class to have more than one method having the same name, if their parameters are different.

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

What is method overriding?

A

feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.

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

Write code to exemplify overriding with the following:

class Parent

method show

class Child which inherits Parent

override method show

main method to print show.

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

What is an abstract class?

A

A class that you can NOT instantiate.

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

How do you create an abstract class? show code in example of public class called Animal.

A

public abstract class Animal {

}

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

What is an abstract method?

A

A method within an abstract class.

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

What’s the difference betwen an abstract class and an interface?

A

You can implement as many interfaces as you want but you can only extend one class.

And every field declared inside an interface is static and final.

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

Name all non-access modifiers.

A

static.

final.

abstract.

synchornized.

transient.

volatile.

strictfp.

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

What is unit testing?

what are the benefits of unit testing?

A
  • A unit test is a program that exercises a small piece of the codebase in complete isolation.
  • fast. unit tests don’t interact with elements external to the code such as databases, filesystems, or the network.
  • Deterministic. If a given test is failing, it will continue to fail until a change is made to the test or the code.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q

Why is unit testing useful?

A

Unit testing can reduce bugs. Even if your code is technically correct, it might not do what you intend. That’s where testing is useful.

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

What is TDD?

A

test driven development. This is when you use tests to drive the development of the application.

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

3 steps to Workflow of TDD?

A
  1. Start by writing a unit test related to the feature you want to implement.
  2. Make the test pass by writing the lease possible amount of code.
  3. Refactor in order to get rid of duplication or other problems (optional).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
83
Q

What does JUnit Annotations @Test do?

A

declares a method as a test method.

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

What does JUnit Anootation @BeforeClass do?

A

declares a setup method that runs once, before all other methods in the class.

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

What does JUnit Annotation @Before do?

A

decalres a setup method that runs before each test method.

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

What does JUnit annotations @After do?

A

declares a tear-down method that runs before each test method.

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

What does JUnit Annotations @AfterClass do?

A

Declares a tear-dpwn method that runs once, after all other methods in the class.

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

Difference between checked and unchecked exception?

A
  • Checked Exceptions are required to be handled or declared by the programmer.
  • Unchecked Exceptions is not required to be handled or declared.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
89
Q

What is an exception in java?

A

an unwanted or unexpected event.

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

When an exceptions occurrs within a method, it creates an ______. This is called an ________.

A

object.

exception object.

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

What does the exception object contain?

A

Information about the exception such as the name and description of the exception and the state of the program when the exception occurred.

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

Error vs Exception. What’s the difference?

A
  • An error indicatesa a serious problem that a reasonable application should not try to catch.
  • An exception indicates conditions that a reasonable application might try to catch.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
93
Q

What is a try/catch block used for?

A

to handle exceptions that could be thrown in our application.

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

explain the two functions of the try/catch block.

A

The try block enclose the code that may throw an exception .

The catch block defines an exception to catch and runs the code inside only if that type of exeption is thrown.

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

What is a HashMap?

A

A map which:

stores elements in key-value pairs.

Insertion/Retrieval of element by key is fat.

Does not maintain order of insertion.

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

How to access a value in the HashMap? show example if I wanted to get the String “England” from an object called capitalCities.

A

Use get() method.

capitalCities.get(“England”)

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

Declare a HashMap called capitalCities. Put two Strings, the first being the country then the capital. Do with the following then print.

England, London

Berling, Germany

Washington DC, USA

A

HashMap capitalCities = new HashMap();

capitalCities.put(“England”, “London);

capitalCities.put(“USA”, “Washington DC”);

capitalCities.put(“Germany”, “Berlin”);

System.out.println(capitalCities);

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

which package is LinkedList in?

A

java.util

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

Create a linked list with the following:

class Main

main method

Linked list animals

elements in list include Dog, Cat, Cow

print out Linked List.

A

import java.util.LinkedList;

class Main {

public static void main(String[] args) {

LinkedList animals = new LinkedList<>();

animals. add(“Dog”);
animals. add(“Cat”);
animals. add(“Cow”);

System.out.println(“LinkedList: “ + animals);

}

}

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

What is an ArrayDeque?

A

A special kind of growable array that allows us to add or remove an element from both sides.

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

Which two itnerfaces does an arraydeque implement? Explain each.

A

Queue Interface: Interface that is a FIFO data structure where the elements are added from the back.

Deque Interface: A doubly ended Queue in which you can insert elements from both sides.

102
Q

Write a line of code that would retrieve the first element from an Array Deque called animals.

Call it firstElement.

A

String firstElement = animals.getFirst()

103
Q

Code an Array Deque with the following information:

class is Main

main method

insert Dog and Horse at the end of the array deque

insert cat at the beginning of the array deque.

print.

A
104
Q

Create a priority queue with the following:

class Main

main method

call priority queue pQueue

add 10, 20, and 15 to pQueue

print out pQueue

print out the top element

print out the top elemenet and remove from container

print out top element again

A
105
Q

Create a tree set with the following:

class Main

main method

create tree set called tsOne

add “A”, “B”, and “C” to the tree set

print

A
106
Q

Declare a two dimensional array of ints

A

int [] []

107
Q

create a two dimensional array that holds 200 elements with 10 in one array and 20 in another. call the array x.

A

int [] [] x = new int[10][20]

108
Q

What does an iterator interface do?

A

allows us to access elements of the collection and is used to iterate over the elements in the collection(Map,List, or Set).

109
Q

create an array list and iterate through the list to print out the values. Use the following:

imports

class Main

main method

ArrayList for cars and add Volvo, BMW, Ford, Mazda

Iterate through and print each.

A
110
Q

which package is comparable interface found in?

A

java.lang

111
Q

Write code that sorts integers in an array with the following:

class Main

main method

array containing 11,55,22,0,89. Then have program sort them from least to greatest.

print out sorted array.

A
112
Q

What is garbage collection in java?

A

process by which java programs perform automatic memory management.

113
Q

What is the StringBuilder class?

What is the difference between a StringBuilder and StringBuffer?

A
  • A class used to create mutable (modifiable) strings.
  • they are the same except that StringBuilder is non-synchronized.
114
Q

What does the constructor, StringBuilder(), do?

A

It creates an empty String Builder with intial capacity of 16.

115
Q

What does the constructor, StringBuilder(String str), do?

A

It creates a String Builder with a specified string.

116
Q

What does the constructor, StringBuilder(int length), do?

A

It creates an empty String Builder with the specified capacity as length.

117
Q

Explain the following code:

class Driver{

public static void main(String args[]){

StringBuilder sb=new StringBuilder(“Hello “);

sb.append(“Java”);

System.out.println(sb);

A

This creates a StringBuilder called sb and assigns “Hello” to it.

Then it changes sb to “Java” using the append method.

118
Q

Explain the following String Builder methods:

append()

insert()

replace()

A
  • append() method changes a String Builder argument with a given string.
  • insert() method inserts a string inside a given position in the original string.
  • replace() method replace a given string from a specified begin and end index.
119
Q

what is a String Buffer? How is it different than a String Builder?

A

A String Buffer is a string that can be modified.

A String Buffer is synchronized, unlike a String Builder. This means that String Buffer is useful in multi-threading cases.

120
Q

Explain the following String Buffer constructors:

StringBuffer()

StringBuffer(CharSequence seq)

StringBuffer(int capacity)

StringBuffer(String str)

A
  • StringBuffer() constructs a string buffer with no charafcters in it and an initial capcacity of 16 characters.
  • StringBuffer(CharSequence seq) constructs a string buffer that contains the same characters as the specified CharSequence.
  • StringBuffer(int capacity) constructs a string buffer with no characters in it and the specified initial capacity.
  • StringBuffer(String str) constructs a string buffer initiailized to the contents of the specified string.
121
Q

What is a java runnable interface? What is the most common use?

A

an interface used to execute code on a concurrent thread.

Most common use is when we want only to override the run method.

122
Q

import Thread class package.

A

import java.lang.Thread;

123
Q

Two ways to create a Thread.

A

extending the Thread class and overriding the run() method.

OR implement Runnable interface.

124
Q

created a Thread through extension using the following:

class Main

print out “This is a thread”

use a run() method.

A
125
Q

What are the 6 thread states?

A

New.

Runnable.

Blocked.

Waiting.

Time Waiting.

Terminated.

126
Q

Explain the New Thread state.

A

This is when a new thread is created. The thread has not yet started to run when the thread is in this state.

127
Q

Explain runnable Thread State.

A

A thread that is ready to run is moved to a runnable state. In this state, a thread might be running or it might be ready to run at any time.

128
Q

Explain blocked/waiting Thread state.

A

When a thread is temporarily inactive it is either blocked or waiting.

129
Q

Explain the Timed waiting State

A

A thread is in timed waiting state when it calls a method with a time-out parameter. A thread lies in this state until the timeout is completed or until a notification is received.

130
Q

Explain the Terminated state Thread.

A

A thread terminates because 1 of 2 things:

the entired code has been executed normally OR

because there occurred some event, like segmentation fault or unhandled exception.

131
Q

What is a functional interface in Java?

A

An interface that contains exactly one abstract method. It can have any number of default, static methods but only one abstract method.

132
Q

4 reasons to use a Lambda expression?

A
  • REduced lines of code
  • sequential and parallel execution support
  • passing behaviors into methods

higher efficiency with laziness.

133
Q

What is a lambda expression?

A

A short block of code which takes in parameters and retursn a value. They are similar to methods but they do not need a name and they can be implemented right in the body of a method.

134
Q

What is needed to store a lambda expression in a variable?

A

Consumer intreface in the java.util.function package.

import java.util.function.Consumer;

135
Q

What does the forEach loop do?

A

it performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

136
Q

Write the following code:

class Main

ArrayList Integer called Numbers

add 23,32,45,63.

use a forEach loop to print the numbers.

A
137
Q

Describe the Thread model.

A
138
Q

What is Gradle? Explain.

A

Gradle is a build automation tool. A build auto tool use used to automate the creation of applications. This include compiling, linkning, and packaging the code.

139
Q

What is a join() method java?

What is the type?

What is the exception?

A

Allows one thread to wait until another thread completes its execution. Simply, it waits for the other thread to die.

  • void type.
  • InterruptedException
140
Q

Explain isAlive() method.

A

method of thread claass tests if the thread is alive. This method returns true if the Thread is still running and not finished.

141
Q

Explain the Producer/Consumer problem. What is happening in a producer/consumer problem?

A

This is a multi-process synchronization problem.

The producer and consumer share a common, fixed-size buffer used as a queue. The producer’s job is to generate data, put it into the buffer, and start again. At the same time, the consumer is consuming data (removing from the buffer), one piece at a time.

142
Q

How do we solve a producer/consumer problem? Explain.

A
  • We make sure that the producer won’t try to add data into the buffer if its’ full AND that the consumer won’t try to remove data from an empty buffer.
  • The producer is to either go to sleep or discard data if the buffer is full.
  • If the consumer removes an item from the buffer, it notifies the producer, who starts to fill the buffer again
143
Q
A
144
Q

What keywords are used for Exception handling?

A

Try, Catch, Finally, Throw, Throws

145
Q

Explain the Try keyword

A

Used to specify the block of code that might give rise to the exception in a special block with a “Try” keyword.

146
Q

Explain the Catch block keyword.

A

catch block follows the try block that raises an exception. The keyword catch should always be used with a try.

147
Q

Explain the Finally keyword

A

Sometimes we have an important code in our program that needs to be executed irrespective of whether or not the exception is thrown. This code is placed in a special block starting with the “Finally” keyword. The Finally block follows the Try-catch block.

148
Q

Explain the Throw keyword.

A

With this keyword you can throw an exception if we are checking a part of the code.

149
Q

Explain the Throws keyword.

A

The Throws keyword is used to declare exceptions. This is used to indicate that an exception might occur in the program or method.

150
Q

What is the finalize() method?

A

a method of Object class which the Garabge Collector always calls just before the deletion/destroying of the object which is eligible.

151
Q

What is a marker interface? Give 3 examples of Markter interfaces used in real-time applications.

A

An empty interface.

  • Cloneable interface
  • Serializable Interface
  • Remote interface.
152
Q

What is a cloneable interface? which package is it in?

A

A cloneable interface is in the java.lang package. It is an interface that invokes the method clone(). A class that implements the clonebale interface indicates that it is legal for clone() method to make a field-for-field copy of instances of that class.

153
Q

What is a serializable interface? which package is it in?

A

java.io package.

It is used to make an object eligible for saving its state into a file.

154
Q

What is a remote interface? which package is it in?

A

java.rmi

A remote object is an object which is stored at one machine and accessed from another machine. You make an object a remote object by using a Remote interface.

155
Q

Explain Generalization and Specialization.

A

Generalization is the process of extracting shared characterisitics from two or more lasses and combingin them into a generalized superclass.

Specialization means creating new subclasses from an existing class.

156
Q

What are FileWriter and FileReader used for?

A

They are classes that are used to write and read data from text files.

157
Q

Explain FileWriter

A

A file handling class that is meant for writing streams of characters.

158
Q

Explain Each Constructor:

FileWriter(File file)

FileWriter (File file, boolean append)

FileWriter (FileDescriptor fd)

FileWriter (String fileName)

FileWriter (String fileName, Boolean append)

A

FileWriter(File file) – Constructs a FileWriter object given a File object.

FileWriter (File file, boolean append) – constructs a FileWriter object given a File object.

FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with a file descriptor.

FileWriter (String fileName) – constructs a FileWriter object given a file name.

FileWriter (String fileName, Boolean append) – Constructs a FileWriter object given a file name with a Boolean indicating whether or not to append the data written.

159
Q
A
160
Q

What is a FileReader?

A

meant for reading streams of characters.

161
Q

Explain the following constructors:

FileReader(File file)

FileReader(FileDescripter fd)

FileReader(String fileName)

A

FileReader(File file) – Creates a FileReader , given the File to read from

FileReader(FileDescripter fd) – Creates a new FileReader , given the FileDescripter to read from

FileReader(String fileName) – Creates a new FileReader , given the name of the file to read from

162
Q

What is a Singleton Class.

A

A class that can only have one object(an instance of the class) at time.

163
Q

What is a dependency injection?

A

a technique in which an object receives other objects that it depends on, called dependencies.

164
Q

What happens in factory design pattern?

A

In factory design pattern we create an object from a factory class without exposing the creation logic to the client. Objects will be created by an interface or abstract class.

165
Q

What is the main advantage of factory design patttern?

A

it provides loose-coupling.

166
Q

What is loose-coupling?

A

When two classes,modules, or components have low dependencies on each other.

167
Q
A
168
Q

What is loggin gin java?

A

an API that provides the ability to trace out the errors of the applications.

169
Q

What are the components of logging in java?

A

Loggers.

Logging Handlers or Appender

Logging Formatters or Layouts.

170
Q

What are Loggers?

A

The code used by the client sends the log request to the Logger objects.

These logger objects keep track of a log level that is insterted in.

So, it is responsible for capturing log records. After that, it passes the records to the corresponding appender.

171
Q

Describe the following Log Handlers…

StreamHandler:

ConsoleHandler:

FileHandler:

MemoryHandler:

SocketHandler:

A

StreamHandler: It writes the formatted log message to an OutputStream.

ConsoleHandler: It writes all the formatted log messages to the console.

FileHandler: It writes the log message either to a single file or a group of rotating log files in the XML format.

SocketHandler: It writes the log message to the remote TCP ports.

MemoryHandler: It handles the buffer log records resides in the memory.

172
Q

What are collections in Java?

A

A general data structure that contains Objects. Also the name of the API

173
Q

What are the interfaces in the Collections API?

A

Iterable, Collection, List, Queue, Set, Map, SortedSet, SortedMap

174
Q

What is the difference between a Set and a List?

A

Set does not allow duplicates (its members are unique)

175
Q

What is the difference between a Array and an ArrayList?

A

An array is static and its size cannot be changed, but an ArrayList can grow/shrink

176
Q

What is the difference between ArrayList and Vector?

A

Vector is synchronized whereas ArrayList is not.

177
Q

What is the difference between TreeSet and HashSet?

A

The two general purpose Set implementations are HashSet and TreeSet. HashSet is much faster (constant time versus log time for most operations) but offers no ordering guarantees.

178
Q

What is the difference between HashTable and HashMap?

A

a. Hashtable is synchronized whereas Hashmap is not.
b. Hashmap permits null values and the null key.

179
Q

Are Maps in the Collections API?

A

Yes, but they do not implement Collection or Iterable interfaces

180
Q

What are generics? What is the diamond operator (<>)?

A

A way of specifying a type within a data structure - they enforce type safety. <> operator lets you infer generic types from the LHS of assignment operation

181
Q

What is multi-threading?

A

Handling multiple threads / paths of execution in your program.

182
Q

In what ways can you create a thread?

A

By extending the Thread Class or by implementing the Runnable Interface. You must call Thread’s .start() method to start it as a new thread of execution.

183
Q

Lifecycle of a thread

A

When created, in NEW state.

When .start() is called, it goes to RUNNABLE state.

When .run() is called, goes to RUNNING state.

If .sleep() or .wait() is called, will go to WAITING.

If dependent on another thread to release a lock, it will go to BLOCKED state.

When finished executing, will be in DEAD state and cannot be restarted.

184
Q

What is deadlock?

A

When two or more threads are waiting on locks held by the others, such that no thread can execute

185
Q

What is synchronized keyword?

A

Only allowing one thread access to the method or variable at a time - enforces thread-safety

186
Q

What is a Marker interface?

A

A marker interface is an interface which has no methods at all. Example: Serializable, Remote, Cloneable. Generally, they are used to give additional information about the behavior of a class.

187
Q

What are transient variables?

A

Transient variables are those variables which cannot be serialized.

188
Q

Difference between FileReader and BufferedReader?

A

FileReader is just a Reader which reads a file, so it reads characters and uses the platform-default encoding.

BufferedReader reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines (e.g. can read one line at a time).

So you can wrap a BufferedReader around a FileReader

189
Q

What are Singleton / Factory design patterns?

A

Singleton - allows for creation of only 1 object. Method for retrieving object returns reference to the same object in memory. Implement via private constructor

Factory - abstracts away instantiation logic, usually used in conjunction with singleton pattern

190
Q

What is an advantage to using a logging library?

A

Allows you to set logging thresholds

191
Q

What is log4j?

A

Logging library for Java

192
Q

What are the logging levels of log4j?

A

TRACE, DEBUG, INFO, WARN, ERROR, FATAL

193
Q

What are functional interfaces?

A

Functional interfaces only have one method, and can be used in conjuntion with lambdas

194
Q

What are lambdas?

A

Like anonymous functions, they allow implementation of functional interfaces directly without creating a class

195
Q

What is try-with-resources? What interface must the resource implement to use this feature?

A

Try-with-resources allows for automatically closing resources in a try/catch block using try(resource) {…} syntax. Must implement the AutoCloseable interface

196
Q

How to make numbers in your code more readable?

A

Use the _ for numeric literals - must be placed between numbers

197
Q

Which collections cannot hold null values?

A

HashTable, TreeSet, ArrayDeque, PriorityQueue

198
Q

If 2 interfaces have default methods and you implement both, what happens?

A

The code will NOT compile unless you override the method. However, the code WILL compile if one interface is implemented further up in the class hierarchy than the other - in this case, the closest method implementation in the hierarchy will be called

199
Q

If 2 interfaces have same variable names and you implement both, what happens?

A

The code will compile unless you make a reference to the variable (this is an ambiguous reference). You must explicitly define the variable by using the interface name: int a = INTERFACENAME.a;

200
Q

Why does HashTable not take null key?

A

The hash table hashes the keys given as input, and the null value cannot be hashed

201
Q

What new syntax for creating variables was introduced with Java 10?

A

The var keyword was introduced - with type inference

202
Q

Is there an interactive REPL tool for Java like there is for languages like Python?

A

Yes, the jshell tool introduced in Java 9

203
Q

What are collection factory methods?

A

They allow you to directly populate collections, e.g. Set.of(1,2,3)

204
Q

What is wrong with this line of code? Set myints = new HashSet<>()

A

Primitives cannot be used with collections; instead, use the wrapper class

205
Q

If you want to set up custom ordering of objects in a collection, use the Comparator interface. T/F

A

True

206
Q

Which logging threshold level is default if not explicitly configured?

A

DEBUG

207
Q

Which collection should I use if I want it to store sorted, unique values?

A

TreeSet

208
Q

If I add 3 of the same exact object to a HashSet, how many will be stored?

A

1

209
Q

What is the purpose of multithreading?

A

Improve application performance and concurrency when done correctly.

210
Q

If a thread’s state becomes “not running” because its wait() method is invoked, which method needs to be invoked to test all waiting threads to see if they should wake up again?

A

notifyAll();

211
Q

Which of the following is true about log4j levels?

A log request of level x in a logger with level y is enabled if x >= y.

A log request assumes that levels are ordered.

For the standard levels, we have ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF.

All of the above.

A

All of the above.

212
Q

ERROR is a higher logging level than FATAL. t/f?

A

True

213
Q

INFO is a higher logging level than DEBUG.

A

False

214
Q

Which of the following statements are correct concerning log4j?

log4j is a reliable, fast and flexible logging framework (APIs) written in Java, which is distributed under the Apache Software License.

log4j has been ported to the C, C++, C#, Perl, Python, Ruby, and Eiffel languages.

log4j is highly configurable through external configuration files at runtime.

All of the above.

A

All of the above.

215
Q

Which is true about an Iterator?

A

It enables the traversal through a collection.

216
Q

HashMaps can contain null values and a null key. t/f?

A

True

217
Q

What is the difference between ArrayDeque and PriorityQueue?

A

ArrayDeque is an implementation of a pure double-ended queue (elements can be added or removed from either end of the queue). PriorityQueue is an implementation of a queue that does not have specified ends (addition or removal of elements doesn’t happen on any specific end of the queue).

218
Q

True or false: Logging is the process of writing log messages during the execution of a program to a central place and allows you to report and persist error and warning messages as well as info messages so that the messages can later be retrieved and analyzed.

A

True

219
Q

True or false: The Map interface is a part of the Java Collection interface.

A

False

220
Q
A
221
Q

Define Queue

A

A collection interface that holds and processes elements in FIFO order.

222
Q

Putting @FunctionalInterface above an Interface declaration designates to the compiler that it is a Functional Interface. t/f

A

True

223
Q

CheckedException and RuntimeException are two classes that inherit from the Exception class. t/f

A

False

224
Q

Even in the waiting state a thread is still running

A

False

225
Q

Is it possible to start a thread multiple times?

A

False

226
Q

A static method can be synchronized

A

True

227
Q

What is synchronization?

A

The capability to control the access of multiple threads to shared resources.

228
Q

What is this piece of code doing?

(byte i) -> 10+i;

A

Passes a byte argument i, and returns 10+i

229
Q

(double x, y) -> x - y; is this a valid lambda expression? t/f

A

False.

230
Q

Functional interfaces have a single functionality to exhibit. t/f?

A

True

231
Q

What is a Set in jAva?

A

The set is an interface from the Collection hierarchyl.

232
Q

What are some methods that we can use on a Set in Java? (Choose all options that are correct)

.add()

.length()

.contains()

.remove()

A

.add()

.contains()

.remove()

233
Q

A set can contain duplicate values. t/f?

A

False.

234
Q

A set is sorted t/f

A

False

235
Q

What are some methods that we can use on a List in Java? (Choose all options that are correct)

.add()

.size()

.isEmpty()

.length()

A

.add()

.size()

.isEmpty()

236
Q

Which PriorityQueue method specifically returns the item at the head but does not remove it from the queue?

A

peek()

237
Q

Why would you want to use a PriorityQueue?

A

To store potentially duplicate objects by insertion order.

238
Q

What are some advantages and disadvantages of using multithreading in an application?

A

Advantages: improve performance & efficiency for parallel processing

Disadvantages: deadlocking threads, race conditions, hard to debug & maintain

239
Q

What are Lamda expressions primary use?

A

to define inline implementation of a functional interface.

240
Q

Lambda expressions fulfills the need for anonymous classes in java? t/f

A

True

241
Q

What is a thread?

A

A representation of a path of execution, allowing for concurrent processing

242
Q

Which Thread method is used to wait for the thread to finish execution?

A

Thread.join()

243
Q

Threads can be created by extending the Runnable class. t/f

A

false

244
Q

Threads can be created by…

A

passing a Runnable into the constructor of Thread: new Thread(Runnable)

245
Q

The run() method comes from the Thread class. t/f

A

False

246
Q

What happens when thread’s sleep() method is called?

A

Thread returns to the waiting state.

247
Q

What is currentThread()?

A

It is a Thread public static method used to obtain a reference to the current thread.

248
Q

Which method must be implemented by all threads?

A

run()

249
Q

Explain the final keyword.

A

The final keyword is a non-access modifier which can be used for class, method, and variables.

250
Q

Explain a final variable

A

final variable’s value can’t be modified. You must initialize a final variable.

251
Q

Three ways to initialize a final variable.

A
  1. You can initialize a final variable when it is declared. if not initialized when declared, it is called a blank final variable.
  2. a blank final variable can be initialized inside an instance-initializer block or inside the constructor. If you have more than one constructor in your class then it must be initialized in all of them.
  3. A blank final static variable can be initialized inside a static block.
252
Q
A