Java_advanced Flashcards

1
Q

What does this course cover?

A

Topics advanced Java developers use a daily basis.

Designed as a step by step guide and reference.

Each section builds on top of itself.

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

What are the requirements?

A

Should know the basics of OOP in Java!

Start from part 1 or part 2 of the series!

Or you’ll find the topics difficult to understand!

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

What is covered in the exceptions section?

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

What is the root cause of many problems in Java programs?

A

NullPointerException

A class declared in java.lang package

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

What is an exception?

A

An object that contains information about an error

Several exception classes

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

What should a good Java developer anticipate?

A

Exceptions and handle them!

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

What are the three types of exceptions in Java?

A

Checked Exceptions :

Exceptions we as developers should anticipate and handle

Exceptions forced to handle by Java compiler

Checked at compile time by java compiler (red underline)

Ex. Handle edge cases vs. runtime terminating program

Unchecked (runtime exceptions) :

not checked during compile time by Java Compiler

due to programming errors

Ex. NullPointerException due to trying to pass a null value as an object reference

Error

error external to our application

Ex. memory error, stack overflow error

Solution?

identify source like infinite recursion or problem with JVM itself

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

What are checked exceptions?

A

Exceptions we should anticipate and recover from vs. runtime terminating program​

Exceptions we as developers should anticipate and handle

Exceptions forced to handle by Java compiler

Checked at compile time by java compiler (red underline)

Ex. Java compiler knows constructor will throw an exception if file is not present, must handle this edge case

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

What are unchecked exceptions (run time exceptions)?

A

Programming errors

not checked during compile time by Java Compiler

NullPointerException - due to trying to pass a null value as an object reference

ArithmeticException - attempt to divide by zero

IllegalArgumentException - argument passed to method not accepted

IndexOutOfBoundsException - access an array, list, string invalid index

IllegalStateExceptions - call a method, object not in correct state

Solve?

Automated Testing, lots of testing

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

What are errors?

A

errors resulting from problems external to our application

Ex.

StackOverFlowError

OutOfMemoryError

Source?

Infinite looping, JVM issues

Solve?

Let application crash, identify error source

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

What is the stack trace?

A

Shows the methods that have been called (in reverse order) that resulted in an exception

Why?

Useful in solving problems & identifiying sources of exceptions, errors

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

What can throw an exception?

A

A method can throw an exception

or cause of chain of exceptions

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

What is the exceptions hierarchy?

A

Classes that represent different types of exceptions

Top of Hierarchy:

Throwable Class - defines common characteristics for all exceptions and errors like an error message and stack trace

Next Level:

Exception Class - parent class for all checked and unchecked errors, if not RunTimeException it’s a checked error

Error Class - + all children classes represent errors external to our application errors

Below Exception Class:

RunTimeException Class - unchecked exceptions

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

What will Java run time compiler do when a method throws an exception?

A

Look for an exception handler

If the method doesn’t have a method to handle the exception, will look at other methods

if none are present, Java Run Time will terminate the program and deliver exception message

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

E What is the proper way to handled checked exceptions?

A

Catch exceptions using try-catch blocks!

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

How can we use IntelliJ to generate a catch for a checked error?

A

Option + enter

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

How do we catch multiple types of exceptions?

A

Multiple catch blocks

each catch block targets a specific exception

if method throws an exception

catch block will catch exception and handle it

Sometimes order matters!

Why?

A parent object might get called first, resulting in absence of polymorphism (child object not getting called)

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

How can we refactor these exceptions?

A

Combine the two exceptions using a vertical bar

block will catch exceptions of type IOException or ParseException and handle them the same

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

What is the finally block?

A

Comes after catch statement

always gets excuted (whether there is an exception or not)

allows us to release external resouces

Release:

File Handles - reader.close ( );

Network connections

Database connections

Why?

If we don’t release these ext. resources other methods may not be able to access them!

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

What is a better way to release resources (than finally block)?

A

use try-with-resources statement

a try statement with one or more resources

We don’t need to explicitly close resources

Syntax?

initialize external resources after try statement before block using ( )

Why?

JavaCompiler will automatically create finally block (at runtime, under the hood, close resources)

But?

Objects initialized in try-with-resource statement must implement the auto-closeable interface

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

How can we throw an exception?

A

Use the throw keyword!

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

What is defensive programming?

A

validating an argument, throwing an exception if outside of valid range

Why?

stopping code from running is better than letting a serious problem occur later in our application

When?

if an error could occur that causes problems with the rest of our code

Do?

Throw an exception to prevent rest of code from running if an error occurs

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

When is it better to use defensive programming?

A
  1. When building a library for others to use
  2. When recieving data from external sources outside of application

Why?

Defensive programming makes your code verbose

If building an application, methods should trust each other, don’t need to pollute your code with tons of data validation

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

How do we specify that our method may throw an exception so that the receiving class can handle this exception?

A

Add the throws keyword after parameter declaration

details represent API of this method

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

Why and how do we re-throw an exception?

A

Why?

Our application handles the exception BUT we want to log it somewhere else so we can handle it and re-throw it

How?

add throw keyword in catch block

add throws to the method signature after parameter declaration

IntelliJ can also shortcut do this!

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

What are custom exceptions?

A

Java provides a lot of generic exceptions class BUT sometimes we want to create custom exceptions

Why?

Sometimes we need to create exceptions specific to our application domain

When?

Creating libraries or frameworks that have custom exceptions to help users and other developers understand intent and actual problem

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

What is the naming convention for Exceptions Classes?

A

Exceptions -suffix to name our Exceptions Classes

Ex. InsufficientFundsException

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

How do we create a custom exception?

A

Naming -Exceptions for suffix

add extends + parent class name

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

What is chainining exceptons?

A

Wrapping a more specific exception object inside a general exception object

Why?

Find out specific details on what caused the general exception

Ex.

AccountException caused by InsufficientFundsException

How?

Create Parent Exception Class

pass detailed exception object in the constructor of this wrapper object

When?

Used in building libraries and frameworks

Used in building large, enterprise applications

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

What is a simpler way to chain exceptions?

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

What are generics?

A

One of the most important topics in Java

Why?

Many collection classes are implemented using Generics

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

What problem do generics solve?

A

Duplicate code

Why?

Having to create data structures for each data type (integer, objects, Strings) is tedious!!

Causes lots of duplicate code!!

Solution?

Generics - They offer polymorphism to collections

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

Why is using the base Object class a problematic implementation?

A

To store values in return variable

have to explicitly cast result to specific data type

if accidently try to cast data to the wrong type, get a runtime exception (ClassCastException)

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

How do we specify generic type?

A

After class name add

T for type or template

E for element (collections)

Method Return Type = T

Method Parameter Type = T

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

What are the benefits of generics?

A
  1. Compile Time, Type Safety - provides compile time errors that ensure all objects are of the specified data type
  2. Cleaner code - don’t have to explicitly cast return types
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

How do we use primitives with generic classes?

A

Cannot use primititve type directly

Must wrapper classes around primitive types

int -> Integer

boolean -> Boolean

float -> Float

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

What is boxing?

A

Java run time compiler will take a primitive value and wrap it in a wrapper class (reference type)

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

What is unboxing?

A

Java compiler extracts value stored in Integer reference type

can be then stored in a primitive type variable

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

How do we implement type constraints in a generic class?

A

add extends keyword + type

Ex. extends Number>

Can only use generic with Number class or any derivative classes (Integer, Float, etc.)

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

How can we restrict our generic class using interfaces (bounded type parameter)?

A

Create a bounded type parameter:

add extends + interfaces

<T extends Comparable & Cloneable>

only allow types that implement interface

Ex. Generic list can only store objects that are comparable and clonable

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

What is a bounded type parameter?

A

A generic that only accepts certain classes or classes that implement specific interfaces

Ex. GenericList

only accepts classes that implement both interfaces

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

How are generics executed?

A

Java Compiler converts generic type to instance of the Object class

Why not use Object class then?

using the generic type gives us compile time, type safety!

But at compile time,

generic is converted back to Object class instance

under the hood

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

What is type erasure?

A

Java compiler replacing all generic types at run time with Object class or constraining classes / interfaces specified at run time!

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

How does generic w/ constraint get executed by Java?

A

All instances of generic type are replaced by the constraint class or interface

this is called type erasure.

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

What is the comparable interface?

A

A generic interface

takes an generic type, compares to another

Ex. Pass type User to comparable and implement compareTo method

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

How can we rewrite this code for the comparable interface?

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

What is a generic method?

A

A generic method inside a non-generic class

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

How can we declare a class with multiple type parameters?

A

add after class name declaration

add private fields using K and V

add method parameters using K and V

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

How can we implement multiple type parameters?

A

Use K for first generic parameter

Use V for second generic parameter

Why?

We want to pass two different type parameters at compile time

Not the same parameter type at compile time

Ex. Key could be integer, value a string

Or key could be character, value an integer

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

What is the ”?” symbol?

A

Wildcard character

represents unknown type

Java Compiler

creates an anonymous type under the hood

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

How can we restrict a wildcard?

A

add <? extends User>

Now we can only pass a type of User or derivatives!

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

What does adding the super keyword after a wildcard allow us to do?

A

add to a list

GenericList super User>

JavaCompiler

treats unknown type like parent of User class, Object class

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

When we use the extends keyword with a wildcard, how does the Java compiler treat it?

A

treats the class after extends as the parent class

Ex. GenericList extends User>

We don’t have access to Capture class (?)

So

we can only read from this list, cannot add

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

What is in the collections hierarchy?

A

Green are interfaces

Blue are classes that implement interfaces

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

What problem does the iterable interface solve?

A

Problem:

w/o making items in a class public, cannot iterate over them outside of the class

Poor solution:

Expose items field to outside (public)

Why not good?

exposing internal implementation of a class to the outside causes breaking changes in future class changes

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

What is the iterable interface?

A

An interface with a few methods

Why?

clients code against iterable interface (buttons)

Solves?

Can iterate over an object without knowing internal implementation preventing class dependency

How?

add implements Iterable to class declaration

iterator ( ) - returns an iterator object (can iterate this object)

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

What is the forreach loop?

A

Syntactical sugar over iterator object

java compiler converts code to use an iterator object!

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

How do we implement our list iterator?

A
  1. Make list iterable by implementing iterable iterface (add to class declaration signature)
  2. Implement the iterator ( ) method - returns an iterable object
  3. Create the private class of type Iterator - the object returned by the iterator ( ) method

Why?

has intimate knowledge of the internal elements

implement hasNext() , next ( ) methods!

knows how to iterate over our GenericList list

Can access private fields within our GenericList class

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

How can we pass multiple elements to be added in a collection?

A

Use Collections interface static method addAll

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

What is the collection interface?

A

A collection represents an object that acts as a collection or container for other objects!

represents a group of objects, known as its elements.

Some collections allow duplicate elements and others do not. Some are ordered and others unordered.

The collection interface doesn’t implement indexing!

Operations:

add - ensures collection contains the specific element

remove - removes a single instance of a specific element from collection

size - returns number of elements in collection

contains - returns true if collection contains specific element

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

How can we convert a collection to a regular array?

A

.toArray( T [] )

pass array type

or

default returns Object []

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

How can we check if two collections are equal?

A

Use the .equals method

Why?

== operator will compare hashCode not values

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

What is the list interface?

A

implements the collection interface but allows us to access objects by index!

list interface represents an ordered collection (sequence)

can access objects by indexes

Parent

Collection Interface - don’t care about indexes, only adding and removing objects

List interfaces:

allows us to work with ordered collection, access objects using index

Implementing Classes:

ArrayList - dynamic array

LinkedList - linked list

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

What is the error with this implementation?

A

We have not implemented the Comparable Interface in our customers class!

To use the Collections static sort method, we must implement the Comparable Interface in the Objects (Customer Class)

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

How do we implement the comparable interface to use the static sort method in the Collections Interface?

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

How can we use a comparator object to sort data using the Collections interface?

A

Collections.sort parameter is overloaded

pass a list that implements the comparable interface and a comparator object

Why?

A comparator object can tell us how to sort two objects!

Ex. Sort by email

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

What is the queue interface?

A

extends collection interface

used to process jobs based on order recieved

Ex. Printers receive jobs, process one by one

Implementation?

ArrayDeque - double ended queue

PriorityQueue - each item gets priority, determines position

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

How can we use the Queue interface?

A

select an implementing class (ArrayDequeue)

use it’s methods:

.add / .offer

.remove / .poll

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

What is unique about the Set interface?

A

only allows unique entries (guarantees uniqueness)

does not guarantee order! (do not rely on for order)

remove duplicates?

put a collection into a set, only unique value remain

parameters?

overloaded - can pass collection of strings!

Implementation?

HashSet<>( ) - 90% of the time

operations?

.union - combination of two sets

.retainAll - gives common items found in both sets

.removeAll - gives items found in set1 that are not in set2

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

How can we use the Set Interface to remove duplicates in a collection?

A

add them to the set!

HashSet<>( ) overloaded parameters = can take a collection of strings!

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

How do we combine two sets?

A

use the .addAll method

called a “union” combines two sets and removes duplicates

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

C How do we find the intersection between two sets?

A

use the .retainAll method

gives items common in both sets

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

How do we get all the items only found within one set and not in another?

A

use the .removeAll method

returns all the items only present in the first set

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

What is the Map interface?

A

Part of collections framework but not part of the hierarchy

has two generic type parameters

Implementing class?

HashMap class

Ex. Use customer’s email as key, customer object as value

Not an iterable object!

.keySet ( ) - returns list of keys

.entrySet ( ) - returns of Set of entries (key, value) pairs

.values ( ) - returns collection of customers

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

What’s covered in this section?

A

Lambda expressions - functional programming (2014 Java *)

Functional Interfaces - consumers, suppliers, functions, predicates

Extremely important

Master these

used in real world applications!

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

What is a functional Interface?

A

An interface with only a single abstract method

Used to represent functions

Ex. Comparable Interface - .compareTo method

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

What is an anonymous inner class?

A

A class without a name, inside a method

Why?

Sometimes, we don’t want to create a separate class to implement an interface, this annonymous inner class is used

Lambda Expressions are SE 8 cleaner implementation of this concept!

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

What is a lambda expression?

A

Objects that we can use to represent anonymous functions

Lambda expression:

( ) parameters

-> lambda operator

{ } body of function

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

How can we make our lambda expression cleaner?

A

Exclude type of parameters, Java Compiler will fill it in!

remove parameter parentheses (if single parameter)

remove braces (if single line in body)

Why?

Lambda expression will be checked based on the signature of the functional interface

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

What can we access within our lambda expressions?

A

local variables in enclosing method

static fields in enclosing class

Ex.

prefix is a local variable of the enclosing method

suffix is a static field of the enclosing class

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

What else can we access in a lambda expression?

A

instance fields (non static fields)

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

What are the differences between Annonymous inner classes and lambda expressions?

A

Lambda expression:

.this refrences the current instance of the enclosing class

references the enclosing object

no instance fields (state)

can only access static/instance fields in enclosing class

Annonymous:

.this references current instance of annonymous inner class

can have fields to store data

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

How can we reference a consumer directly using a lambda expression?

A

Class/Object :: methodName

Ex.

greet(LambdasDemo::new);

references constructor of LambdaDemo class

greet(LambdasDemo::print)

references static method of LambdaDemo class

greet(demo::printAnother)

references instance method of demo object

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

What methods can we reference with a lambda method reference?

A

Static and instance methods and constructors!

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

How many types of functional interfaces do we have in Java?

A

Four types used to perform common tasks:

Consumer - void - operation that takes single operation, returns no result (consumes a value)

Supplier - value - akes no input, returns a value (supplies a value)

Function - map - maps a value to a different value

Predicate - boolean - takes an object, checks if it fulfills a criteria

**defined in Java.util.function

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

What are consumers?

A

functions that take arguments, do some logic but do not return a value (void return type)

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

What are other consumer interfaces?

A

takes args, returns void

BiConsumer - takes two arguments

IntConsumer - takes integer consumer

DoubleConsumer - takes double consumer

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

How do we write this imperative programming in declarative programing paradigm?

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

What is Imperative programming?

A

A style or programming that specifies how logic should be implemented.

Ex. using for, if/else, switch/case

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

FI What is declarative programming?

A

A programming style that specifies what needs to be done and omits how it should be done

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

What does chaining consumers mean?

A

running one function after the next in series (sequence)!

Ex. .andThen

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

What is a supplier?

A

Function that doesn’t take an input but returns a value!

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

What is lazy evaluation?

A

function not executed until we specifically call it

value is not generated until specifically asked

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

What is the function interface?

A

3 Arguments and Return are types

represents a function!

Takes a parameter, returns a value

#1 arguments have type, return is generic

ex. IntFunction - takes integer, returns R

#2 arguments are generic, return has type

ex. ToIntFunction - takes generic, returns integer

ex. IntToLongFunction - takes integer, returns long

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

What is one way to build a multi-step function using the Functional interface?

A

use the .andThen

96
Q

What is another way to write this declarative statement?

A
97
Q

What is the predicate interface?

A

extremely useful

tons of real world applications

used to filter data!

give generic args, returns boolean

Ex. give Customer obj, check if have a balance

Specialization?

BiPredicate - takes two args, returns boolean

intPredicate - takes integer, returns boolean

98
Q

How can we combine predicates to test multiple conditions?

A

.or = || operator

.and = && operator

.negate = ! operator

99
Q

What is the BinaryOperator Interface?

A

A special type of function

takes two generic args, returns two generic args

Specializations?

IntBinaryOperator - takes two integers

100
Q

What is the UnaryOperator Interface?

A

a function that takes generic arg, returns generic result

101
Q

What is covered in the stream section?

A

streams = ways to access collections declaratively!

Stream operations used to create sophisticated queries like…

mapping, filtering, slicing, sorting, reducing

102
Q

What are the key differences between Imperative and Declarative programming paradigms?

A

Imperative:

statements specify “how” to do something

stated clearly and in detail, leaving no room for confusion or doubt

Declarative:

statiements specify “what” to do

without requiring the programmer to specify an exact procedure to be followed.

Ex.

SQL - Declarative Language - SQL Queries specify “what” we to do, but we don’t write logic for “How”

103
Q

Why were streams built in Java?

A

To allow us to process collections in a functional (declarative) way!

Allows us to build data processing lines

Makes our code cleaner!

Makes our code easier to read!

104
Q

What is functional programming?

A

A special type of declarative programming with a few special features!

105
Q

What two types of stream operations are there?

A

Intermediate and Terminal

Intermediate Operations:

Return a new stream

can continually transform stream

Terminal Operations:

if don’t call terminal operation, nothing happens

actual operation happens after calling method

106
Q

How can we build data processing lines using streams?

A
107
Q

What are intermediate operations?

A

allow us to build and customize processing pipelines!

108
Q

What are reducers?

A

Reduce a stream of objects to a single object (answer)

These are terminal operations!

Count - count elements in a stream

matchers - can see if any or all elements satisfy a condition

find - get element in stream

max/min - find element based on comparision

109
Q

What are the four methods for slicing a stream?

A

limit(n) - limit number of elements in stream

skip(n) - can skip elements in stream, paginatino

takeWhile(predicate) - as long as condition, keep taking elements

110
Q

How can we create streams?

A

Collections have .stream ( ) method

+ derivative classes (List, Queue)

Arrays util class has .stream ( ) method

111
Q

What does every stream have?

A

.forEach method

iterates over items

112
Q

How can we create an infinite number of streams?

A

create a stream

call methods on the stream

terminate the stream

Ex.

give the .generate method a Supplier

113
Q

What does .flatMap allow us to do?

A

Allows us to work with individual items in a stream

allows us to flatten a stream

Ex.

We want to flatten lists to work with individual numbers

114
Q

How can we make this code cleaner?

A

extract predicate to a separate method

115
Q

How does the .limit method work?

A

allows us to limit number of items in our stream

116
Q

How does the .skip method work?

A

can skip elements in our collection that come out in our stream

117
Q

How can we use streams to create pagination?

A
118
Q

How is the .takeWhile (predicate) method different than the .filter method?

A

.takeWhile stops the moment predicate condition is not true, even if elements after would fit condition

.filter iterates our entire collection before stopping

119
Q

What is the .dropWhile(predicate) method?

A

escapes all elements that match predicate criteria

120
Q

When do we use the Comparator interface vs the Comparable Interface?

A

Implementing a comparable Interface couples the compare method to the implementing class

This has limitations!

if we want to sort by a different parameter, we should implement comparator interface (using lambda expression)

why?

extract the compareTo method by using a comparator object! (annonymous object, lamda expression)

121
Q

How can we use streams to sort data?

A
  1. Rely on type class to implement comparable interface
  2. Pass a comparator object to the sort method (use lambda expression)
122
Q

How can we re-write this code?

A
123
Q

How can we reverse the order of elements in our stream using the Comparator interface?

A

Comparator has a default method called reversed!

124
Q

How do we get unique values in a Stream?

A

map( )

distinct ( )

.forEach ( )

125
Q

How do we trouble shoot complex query issues with streams?

A

use the peek method to get output of each operation

126
Q

What are the matcher operations?

A
127
Q

What are the find operations?

A
128
Q

S How does the general purpose reducer work?

A

reduces a stream to a single value

129
Q

How can we re-write this lambda expression?

A
130
Q

How else can we re-write this lamdba expression?

A

.reduce method

includes an option to pass an identity value (initial value)

Why?

don’t have to work with an Optional object (if stream is empty)

131
Q

How do we collect the result of a stream into a list, set or hash map?

A

.collect method

takes a collector object (Collector is an interface)

132
Q

How can we rewrite this lambda using a method reference?

A
133
Q

How can we return movie objects as the values in our collector hashmap?

A

Function.identity ( ) takes an object and returns the object

134
Q

How can we get the sum of values in a collection?

A

Collector.summingInt

135
Q

What is Mosh’s favorite collector and why?

A

.summarizingInt

Why?

gives us statistics about values in stream

it’s very useful in buidling real world applications

136
Q

What is the joining collector?

A

used to concatinate values in a stream based on a delimiter

137
Q

S How do we classify or group our data using streams?

A

Collectors interface has a groupingBy ( ) method

groupingBy takes a classifer

classifer is a lambda function

returns Hashmap w/ key = genre : value = List

138
Q

How can we map our groupingBy method to a list, set or map?

A

Collectors.groupingBy is overloaded

can pass another argument

Collectors.toSet / Collectors.toList / Collectors.toMap

139
Q

How can we get the number of movies in each genre using lambdas?

A
140
Q

How can we using groupingBy to display the titles of all movies within each genre?

A

Collectors.mapping

is overloaded

takes two args :

mapping function, Collectors.joining

141
Q

How do we partition (separate) data using streams?

A

2 - Collectors.mapping

partitioningBy can take two arguments:

#1 Predicate - condition function

142
Q

How do we work with primitive type streams?

A

Use specialized streams:

IntStream, LongStream, DoubleStream

Useful methods:

rangeClosed - upper bound is included

range - upper bound is excluded

143
Q

What is concurrency?

A

leveraging multi-core processors

Why?

Most devices have multiple cores

make applications faster, more responsive

144
Q

What is covered in the concurrency section?

A

Processes/threads

starting, stopping, pausing threads

race conditions, visibility challenges

solns.

synchronization, volatile fields, atomic objects

145
Q

What is a process?

A

an instance of a program / application

OS loads application inside a process

Process:

contains resources, memory and image of the applications code

146
Q

How many processes can your operating system execute at the same time?

A

Many!

run antivirus, play music!

Process level concurrency!

147
Q

What is a thread?

A

A sequence of instructions!

That thing that executes your code

Can build many threads!

Each process can have additional threads to run tasks concurrently!

148
Q

What is an example of currency using threads?

A

A web application that has multiple threads for concurrently dowloading images

149
Q

What does multi-threaded applications leverage?

A

Multiple cores each device now contains!

without multiple threads essentially using only one core!

Wasting three other cores for concurrent processing!

150
Q

How many cores does my MacBook Pro have?

A

have two cores available

each core can run two threads

Program is using two threads:

main thread, garbage collector

151
Q

What is the most important thing we need to know how to do with threads?

A

Safely share data between threads

Why?

if two threads try to change data at the same time, crazy things happen

152
Q

Why should we learn about threads and concurrency?

A

To exploit parallel hardware

multiple cores in each machine

153
Q

What is the interface Runnable?

A

Represents a task to be run on a thread

abstract method:.run

154
Q

What happens after a thread excutes a task?

A

it dies - we don’t need to worry about it

155
Q

How do threads start and run?

A

In parallel

Ex. Downloading 10 files concurrently using 10 threads!

156
Q

What does multi-threading make our applications?

A

Faster and more responsive!

Ex. each task takes 5 seconds, run concurrently

vs. one after the other takes 50 seconds!

157
Q

What is a thread scheduler?

A

if there are more threads to be executed than processors!

thread scheduler toggles threads w/ CPU time

158
Q

What problem does joining threads solve?

A

running threads sequentially

how to know when one thread finishes?

thread execution time is variable!

cannot use thread.sleep!

Soln:

wait for completion of prior thread

blocks next thread until prior thread finished

159
Q

What is the problem with the .join method?

A

causes current thread to wait

during wait time, thread cannot perform tasks!

Ex. if Main thread is paused, cannot respond to UI events

160
Q

What problem does interrupting a thread solve?

A

allow user to cancel a long lived thread

161
Q

What does the interupt thread actually do?

A

sends a request to the thread to stop

it’s up to the thread whether to respond or not!

Soln:

Check for interupt request, handle accordingly!

162
Q

What happens if we try to interupt a thread that is sleeping?

A

it throws an exception

Soln:

handle the exception

163
Q

What happens with thread in real life?

A

They may need to access or modify the same resource

164
Q

What happens when multiple threads try to update data at the same time?

A

It’s not going to work!

We get wrong results, applications may crash!

This is called race condition!

165
Q

What is a race condition?

A

When multiple threads try to modify a shared resource (data) at the same time!

Why?

Threads are racing to update data first

166
Q

What is a visibility problem?

A

When one thread updates a shared resource and the changes are not visible to other threads who may need to access this data!

Reading from shared resources is fine!

167
Q

How should our multi-threaded systems be designed?

A

using thread safe code:

code that can be safely executed by multiple threads in parallel

Ex. some classes are thread safe!

They can be executed across multiple threads in parallel

168
Q

What is a non-atomic operation?

A

an operation that involves multiple steps.

ex. totalBytes++

Step 1 - fetch value, move to CPU

Step 2 - increment value

Step 3 - store value in memory

169
Q

What are strategies for thread safe code?

A
  1. Confinement - don’t share data across threads, restrict each thread to it’s own data, after process, combine results
  2. Immutable - sharing immutable data is fine, can only read data in threads, data cannot be changed after object is created
  3. Synchronization - prevent multiple threads from accessing objects concurrently using locks, forces code to run sequencially
  4. Atomic objects - allow us to avoid locks, increment atomic operation into one step
  5. Partitioning - partition data so multiple threads can access only a specific segment in the collection.
170
Q

What is an example of a race condition?

A

Each download file updating the status data object

171
Q

What is a lock?

A

Synchronization technique:

lock certain parts of code

only one thread at a time can execute locked code

other threads have to wait

172
Q

What are the problems with synchronization?

A
  1. Locks force code to run sequentially - not concurrently
  2. It’s challenging and error prone
  3. Deadlocks - one thread waiting for another thread forever

Synchronization is bad (generally)!

avoid it!

173
Q

How can we use confinment to prevent race conditions?

A

remove global status object

each thread works with own status object

instead of each thread working with a single global status object (incrementTotalBytes( ) )

-remove status object parameter from DownloadFileTask ( )

-add new DownloadStatus ( ) to constructor of DownloadFileTask

-ask each thread for total bytes, combine them across objects

174
Q

How do we prevent multiple threads from accessing objects at the same time?

A

Using locks!

Coordinate access to critical section

code is executed sequentially

this is synchronization

175
Q

What is Lock interface and what are the implementing classes?

A

Java.concurrent.locks package

176
Q

How can we use locks to prevent race conditions?

A
177
Q

What is the synchronize keyword?

A

Allows us to achieve synchronization

without explicitly locking and unlocking resources

code is simpler!

178
Q

What is the problem with using .this as the monitor object in our synchronized code block?

A

every object has a lock method (under hood)

.this uses the current objects lock method

Why?

both methods are using the same monitor object

only one object can access synchronization on object

prevents us from accessing other fields that are not being executed

reduces throughput of this API

Soln?

Dedicated monitor objects

179
Q

What are dedicated monitor objects?

A

Best approach

Used with synchronization codeblock

Instances of Object class

used to lock data

180
Q

What is another way to use the synchronized keyword?

A

Problems:

uses the .this lock method

this causes issues with accessing other fields

Soln:

Use dedicated monitor objects

181
Q

What is a best practice for synchronization?

A

Don’t use it in new code

understand it for legacy applications

Why?

It causes issues, reduces concurrency

182
Q

What is the volatile keyword?

A

Solves visibility problem NOT race condition

It ensures if one thread changes data, other threads can see changes

183
Q

What is the visibility problem?

A

New threads cannot see changes of a shared resource (peice of data)

Ex. Thread2 cannot see that the isDone variable in the status object was updated to true, so it hangs indefinetly waiting

184
Q

What is underlying the visibility problem?

A

Two cores each running a thread

each core contains local cache memory

RAM values are read into each core’s cache memory

one core updates value locally, other cannot see cache value

even if it returns cache value to RAM

second core has a previous copy in cache

185
Q

What does the volatile keyword tell the Java Virtual Machine?

A

Always read value from RAM memory

Don’t rely on cache value

Update RAM memory immediately

the field is volatile

186
Q

How can we implement wait ( ) and notify ( ) in Java?

A

Every object has the .wait and .notify methods!

Inherited from Object class

Wrap in synchronized block

BUT

Don’t use these in new code!!

We have better implementations currently

187
Q

What is the problem with this wait ( ) state implementation using a while loop?

A

Empty while loop!

While loop is continuously running, until condition is true

could run millions or trillions of times

wastes CPU cycles

188
Q

What are atomic objects?

A

allow us to update counter variables concurrently!

use these with counter variables!

189
Q

Which is better to use atomic types vs. adders?

A

adders are faster!

It’s better to use adders

190
Q

What are adders?

A

If you have multiple threads updating values frequently

Use adder classes:

LongAdder, DoubleAdder

Why?

they’re faster than atomic objects

store counter values in array cells!

191
Q

How do adders work?

A

keeps an array of counters that can grow on demand

array cells, each holding a counter value

threads can update cells concurrently

.intValue ( ) - adds all counter values and returns result

192
Q

What is the synchronized Collections?

A

Wrapper around collections class

static factory methods - creating synchronized Collections

Ex. Pass object that implements collections

method wraps ArrayList in synchornized collection

add ( ) , remove ( ), etc has synchronized code!

Makes a regular list synchronized

193
Q

How can multiple threads share a collection?

A

Collections.synchronizedCollection ( )

Pass lambda to Thread constructor:

Can use lambda expression to represent a runable object

Runable interface is a functional interface

194
Q

How do synchronized collections achieve thread safety?

A

Using locks

entire collection gets locks, other threads have to wait

can have negative impact on performance and scaleability!

195
Q

What are concurrent collections?

A

Faster than synchronized collections

use partition technique to allow thread safety

divide collection into segments

only one thread at a time can access a segment

196
Q

What is the Executor Framework?

A

Higher level abstractions used for building concurrent applications

released by Java SE 5

let’s java worry about handling thread manipulaton

197
Q

What is covered in the Executive Framework?

A

Thread pools

Executors

Callable and Future Interfaces

Asynchronous Programming

Completable Futures

198
Q

What are some of the challenges of working directly with Threads?

A

Availability - we have a limited number of threads. May end up creating too many threads lead to out of memory errors!

Costly - creating and removing threads is costly. If we have to repeatedly create new threads to execute many takes, this requires creating threads repeatedly!

199
Q

What is a Thread Pool?

A

Java 5 solution:

A pool of threads called worker threads

can we re-used to execute multiple tasks

not destroyed and recreated

after execution, they’re returned to the thread pool

thread pool assigns tasks to threads

additional tasks stored in queue until re-usable threads are available

200
Q

How are thread pools represented in Java?

A

Using the ExecutorService interface

Implementation:

ThreadPoolExecutor - most common use

ScheduledThreadPoolExecutor - schedule tasks

ForkJoinPool - divide and concur recursion

201
Q

What is the Executors class?

A

Static factory methods for creating instance of ExecutorService implementations

Better than creating instances directly.

Ex. Executors.newFixedThreadPool ( ) - will create an instance of ThreadPoolExecutor class

Ex. Executors.newScheduledThreadPool ( ) - creates instance of ScheduledThreadPoolExecutor

202
Q

How do we use the Executors class?

A

.submit ( ) task to thread pool

don’t have to explicitly assign task to a thread

203
Q

What must we explicitly do when working with thread pools?

A

Terminate them!

.shutdown ( )

.shutdownNow( )

Surround in Try Catch block

204
Q

What doesn’t the executor framework not protect us against?

A

Concurrency issues - race conditions, visibility conditions

It just simplifies thread manipulation!

205
Q

What is the best practice for shutting down ExecutorServices?

A

Try-catch with finally block

Why?

If our try code block throws an exception

We still shutdown the ExecutorService and allow our worker thread to continue with other tasks

206
Q

What is a future object?

A

Future Interface

Represents an operation that will complete in the future

Result of operation not calculated immediately with CPU

We can get the future result of an operation

Problem?

It’s a blocking operation

.get ( ) will block current thread until future operation is completed

207
Q

What is the callable interface?

A

Used to return a value from a thread

How?

Pass a callable to the Executor.submit method

208
Q

How does Java execute a future callable?

A

immediately returns a future object

future object represents result of operation

We can call method on this object

.get - get value of operation, time out operation

.cancel - cancel an operation

.isCanceled - check if cancelled

.isDone - check if done

209
Q

What is asynchronous programming?

A

Writing non-blocking code

Why?

Making current thread wait for the completion of another thread (future object) wastes our threads!

Ex. Android App - main thread handles UI events (clicks, keystrokes)

if main thread has to wait to completion of other threads, it cannot respond to UI events, application window will freeze!

210
Q

What is the Interface CompletionStage?

A

Allows us to sequence various operations in a declarative way

Ex. We can string declarative methods together like we did with filtering and mapping data in streams

Why?

Many asynchronous tasks may require multiple steps

Here was can string steps together using the CompletionStage interface!

211
Q

What is the CompletableFuture class?

A

2014 Release by Java

Handle Asynchronous applications

​Used to build complex, asynchronous applications!

Implements Future Interface

Can explicitly complete future object

.runAsynch - don’t have to create an executor, call the .submit and shut it down

.supplyAsych - function that returns a result

212
Q

What does the CompletableFuture class allow us to do?

A

Create threads asynchronously

Do not need to create an executor, submit task, shut down

.runAsynch - returns void future object

.supplyAsynch ( ) - pass suplier that returns a value, can also pass an executor object, if none common pool used

213
Q

How can we create a future completable object?

A

Use the CompletableFuture class

.supplysynch - takes a supplier function, returns a future object that we can .get value

.runAsynch - pass an instance of the Runable interface, returns a future void object

214
Q

What is a powerful technique that we should start using in our applications right away?

A

Asychronous API

How?

Wrap a synchronis method inside a CompletableFuture object

215
Q

When we are working with a long running operation like querying a database, calling a remote service, working with a file system how should we run them?

A

Run on a separate thread, not Main thread!

Asynchronously!

How?

Wrap a synchronis method inside a CompletableFuture object

216
Q

What is the convention for naming asynchronous operations?

A

add -asynch suffix

217
Q

How can we execute a code block after an asynchronous operation completes?

A

using the .thenRun or the .thenRunAsynch

provided by the CompletionStage interface in CompletableFuture class

.thenRunAsync - runs function on a separate thread

.thenRun - runs function on main thread

218
Q

How is this code going to be executed?

A

.submit method is going to start the task on a separate thread and return it as a future object.

then, when we call future.get ( ) we have to wait for this operation to complete on the separate thread

219
Q

How can we implement an asychronous API method?

A

Wrap it in a CompletableFuture object

why?

It’ll start on a separate thread and not block current thread

220
Q

What is the .thenAccept method in the CompletableFuture class?

A

get result of completable future

takes a consumer object

(takes obj. doesn’t return value)

.thenAcceptAsynch - runs new code on separate thread

.thenAccept - runs new code on main thread

221
Q

How can we recover and provide a default value when handling exceptions?

A

recover from an exception by transforming it into a value

Use the .exceptionally method!

222
Q

Where does the exception get thrown?

A

In a different thread

have to use get method of the future interface to get it and bring it into the main thread

223
Q

How can we map the result of a future object to a different data type?

A

.thenApply ( )

pass a map function

224
Q

How can we make this code better?

A

Benefits of CompletableFutures:

Complex async applications in declarative way!

225
Q

How do we start a task on the completion of another task?

A

CompletableFutures

.thenCompose ( ) - pass a function that represents a new completable future (async task)

Ex. Have a user

  1. read user email from database
  2. pass email to music streaming website to get playlist
226
Q

How can we make this code better?

A

Extract getUserEmail into a separate method that returns a CompletableFuture

Can build complex asyc operations in a declarative way!

The beautfy of CompletableFutures

227
Q

In Mosh’s opinion what is one of the most powerful abilities of CompletableFutures?

A

The ability to start two tasks asychronously, then combine the results

.thenCombine - non-blocking method

Ex. Start two tasks concurrently, combine results

228
Q

How can we start two tasks concurrently then combine their results?

A

Build a processing pipeline declaratively using CompletableFutures!

229
Q

How can we wait for the completion of many tasks before doing something else?

A

CompletableFuture

.allOf() - pass var args, wait for completion for all tasks

.thenRun() - pass runable object

.get ( ) - get result of individual CompletableFuture obj

230
Q

How can we get the result of the first task that completes when running two tasks concurrently?

A

Call both services concurrently

CompletableFuture.anyOf ( ) - returns a new CompletableFuture as soon as any task completes

231
Q

When calling a remote service what do we want to have?

A

A limit for how long to wait

Don’t want to wait forever!

.orTimeout ( ) - returns a new completableFuture that times out after a specific time

.completeOnTimeout ( ) - returns a new completableFuture after specific time

232
Q

What is a better approach?

A

Recover with a default value

.completeOnTimeout ( ) - returns a new completableFuture after specific time

233
Q

How do we look at return types in IntelliJ?

A

F1

234
Q

How can we refactor this code?

A

Return a stream from FlightService!

235
Q

How can we create an asyc application that uses Streams and CompletableFutures to query an API and return flight prices?

A