Java_advanced Flashcards
What does this course cover?
Topics advanced Java developers use a daily basis.
Designed as a step by step guide and reference.
Each section builds on top of itself.
What are the requirements?
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!
What is covered in the exceptions section?
What is the root cause of many problems in Java programs?
NullPointerException
A class declared in java.lang package
What is an exception?
An object that contains information about an error
Several exception classes
What should a good Java developer anticipate?
Exceptions and handle them!
What are the three types of exceptions in Java?
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
What are checked exceptions?
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
What are unchecked exceptions (run time exceptions)?
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
What are errors?
errors resulting from problems external to our application
Ex.
StackOverFlowError
OutOfMemoryError
Source?
Infinite looping, JVM issues
Solve?
Let application crash, identify error source
What is the stack trace?
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
What can throw an exception?
A method can throw an exception
or cause of chain of exceptions
What is the exceptions hierarchy?
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
What will Java run time compiler do when a method throws an exception?
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
E What is the proper way to handled checked exceptions?
Catch exceptions using try-catch blocks!
How can we use IntelliJ to generate a catch for a checked error?
Option + enter
How do we catch multiple types of exceptions?
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 can we refactor these exceptions?
Combine the two exceptions using a vertical bar
block will catch exceptions of type IOException or ParseException and handle them the same
What is the finally block?
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!
What is a better way to release resources (than finally block)?
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 can we throw an exception?
Use the throw keyword!
What is defensive programming?
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
When is it better to use defensive programming?
- When building a library for others to use
- 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 do we specify that our method may throw an exception so that the receiving class can handle this exception?
Add the throws keyword after parameter declaration
details represent API of this method
Why and how do we re-throw an exception?
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!
What are custom exceptions?
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
What is the naming convention for Exceptions Classes?
Exceptions -suffix to name our Exceptions Classes
Ex. InsufficientFundsException
How do we create a custom exception?
Naming -Exceptions for suffix
add extends + parent class name
What is chainining exceptons?
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
What is a simpler way to chain exceptions?
What are generics?
One of the most important topics in Java
Why?
Many collection classes are implemented using Generics
What problem do generics solve?
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
Why is using the base Object class a problematic implementation?
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 do we specify generic type?
After class name add
T for type or template
E for element (collections)
Method Return Type = T
Method Parameter Type = T
What are the benefits of generics?
- Compile Time, Type Safety - provides compile time errors that ensure all objects are of the specified data type
- Cleaner code - don’t have to explicitly cast return types
How do we use primitives with generic classes?
Cannot use primititve type directly
Must wrapper classes around primitive types
int -> Integer
boolean -> Boolean
float -> Float
What is boxing?
Java run time compiler will take a primitive value and wrap it in a wrapper class (reference type)
What is unboxing?
Java compiler extracts value stored in Integer reference type
can be then stored in a primitive type variable
How do we implement type constraints in a generic class?
add extends keyword + type
Ex. extends Number>
Can only use generic with Number class or any derivative classes (Integer, Float, etc.)
How can we restrict our generic class using interfaces (bounded type parameter)?
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
What is a bounded type parameter?
A generic that only accepts certain classes or classes that implement specific interfaces
Ex. GenericList
only accepts classes that implement both interfaces
How are generics executed?
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
What is type erasure?
Java compiler replacing all generic types at run time with Object class or constraining classes / interfaces specified at run time!
How does generic w/ constraint get executed by Java?
All instances of generic type are replaced by the constraint class or interface
this is called type erasure.
What is the comparable interface?
A generic interface
takes an generic type, compares to another
Ex. Pass type User to comparable and implement compareTo method
How can we rewrite this code for the comparable interface?
What is a generic method?
A generic method inside a non-generic class
How can we declare a class with multiple type parameters?
add after class name declaration
add private fields using K and V
add method parameters using K and V
How can we implement multiple type parameters?
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
What is the ”?” symbol?
Wildcard character
represents unknown type
Java Compiler
creates an anonymous type under the hood
How can we restrict a wildcard?
add <? extends User>
Now we can only pass a type of User or derivatives!
What does adding the super keyword after a wildcard allow us to do?
add to a list
GenericList super User>
JavaCompiler
treats unknown type like parent of User class, Object class
When we use the extends keyword with a wildcard, how does the Java compiler treat it?
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
What is in the collections hierarchy?
Green are interfaces
Blue are classes that implement interfaces
What problem does the iterable interface solve?
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
What is the iterable interface?
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)
What is the forreach loop?
Syntactical sugar over iterator object
java compiler converts code to use an iterator object!
How do we implement our list iterator?
- Make list iterable by implementing iterable iterface (add to class declaration signature)
- Implement the iterator ( ) method - returns an iterable object
- 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 can we pass multiple elements to be added in a collection?
Use Collections interface static method addAll
What is the collection interface?
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 can we convert a collection to a regular array?
.toArray( T [] )
pass array type
or
default returns Object []
How can we check if two collections are equal?
Use the .equals method
Why?
== operator will compare hashCode not values
What is the list interface?
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
What is the error with this implementation?
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 do we implement the comparable interface to use the static sort method in the Collections Interface?
How can we use a comparator object to sort data using the Collections interface?
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
What is the queue interface?
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 can we use the Queue interface?
select an implementing class (ArrayDequeue)
use it’s methods:
.add / .offer
.remove / .poll
What is unique about the Set interface?
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 can we use the Set Interface to remove duplicates in a collection?
add them to the set!
HashSet<>( ) overloaded parameters = can take a collection of strings!
How do we combine two sets?
use the .addAll method
called a “union” combines two sets and removes duplicates
C How do we find the intersection between two sets?
use the .retainAll method
gives items common in both sets
How do we get all the items only found within one set and not in another?
use the .removeAll method
returns all the items only present in the first set
What is the Map interface?
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
What’s covered in this section?
Lambda expressions - functional programming (2014 Java *)
Functional Interfaces - consumers, suppliers, functions, predicates
Extremely important
Master these
used in real world applications!
What is a functional Interface?
An interface with only a single abstract method
Used to represent functions
Ex. Comparable Interface - .compareTo method
What is an anonymous inner class?
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!
What is a lambda expression?
Objects that we can use to represent anonymous functions
Lambda expression:
( ) parameters
-> lambda operator
{ } body of function
How can we make our lambda expression cleaner?
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
What can we access within our lambda expressions?
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
What else can we access in a lambda expression?
instance fields (non static fields)
What are the differences between Annonymous inner classes and lambda expressions?
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 can we reference a consumer directly using a lambda expression?
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
What methods can we reference with a lambda method reference?
Static and instance methods and constructors!
How many types of functional interfaces do we have in Java?
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
What are consumers?
functions that take arguments, do some logic but do not return a value (void return type)
What are other consumer interfaces?
takes args, returns void
BiConsumer - takes two arguments
IntConsumer - takes integer consumer
DoubleConsumer - takes double consumer
How do we write this imperative programming in declarative programing paradigm?
What is Imperative programming?
A style or programming that specifies how logic should be implemented.
Ex. using for, if/else, switch/case
FI What is declarative programming?
A programming style that specifies what needs to be done and omits how it should be done
What does chaining consumers mean?
running one function after the next in series (sequence)!
Ex. .andThen
What is a supplier?
Function that doesn’t take an input but returns a value!
What is lazy evaluation?
function not executed until we specifically call it
value is not generated until specifically asked
What is the function interface?
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