Java Flashcard Flashcards ionicons-v5-c

Import vs Static import

import allows you to access a class without package qualification; static import allows you to access members of a static class without class qualification. e.g. System.out.println("x")vs out.println("x)

Generic Type vs Reference Type vs Primitive Type

any data type based on class (*T*) vs data type based on Class vs data type based on java lang

Generic Method

Create a generic method by passing *T* as a parameter type to the method. Example: class Test<T> { // An object of type T is declared T obj; Test(T obj) { this.obj = obj; } // constructor public T getObject() { return this.obj; } }

JShell (Java Shell)

Java 9. Interactive tool that executes java code from the shell and outputs the code directly

Factory Methods of Collection

Java 9. static methods that creates an unmodifiable instance of the collection. e.g. List<String> list = List.of("Java","JavaFX","Spring","Hibernate","JSP");

Anonymous Class

Java 9. This is when you define a class in another expression. Resulting type is the Interface. ABCD<String> a = new ABCD<>() { // diamond operator is empty, compiler infer type String show(String a, String b) { return a+b; } };

Private Interface Methods

Java 9. Interface can now include private methods; these are shared to non-abstract methods within the interface

Collector

Java 8. Used by Stream. Provides functions to accumulate elements into a Collection and perform operations. e.g. List<Float> productPriceList = productsList.stream() .map(x->x.price) // fetching price .collect(Collectors.toList()); // collecting as list

Interface vs Abstract

Interface uses Implements; Abstract uses extends. Interface can extend other interfaces; Abstract can extend another class and can implement many interfaces; Interface can only have abstract methods, default methods, static methods, final and static fields; Abstract can carry state; Members of an Interface are public by default;

Default Methods

Java 8. Default methods are used in an Interface. Signature includes "default" in the signature instead of a modifier and an implementation of the method. Method can be overridden by the implementing class. e.g. default void say()

Predicate

a functional interface where you can use lambda expressions; all lambda expressions in the example are predicates; e.g. productsList.stream() .filter(p ->p.price> 30000) // filtering price .map(pm ->pm.price) // fetching price .forEach(System.out::println); // iterating price

Functional Interface

Java 8. Interfaces with single abstract method; can have any number of default static methods; can have methods from Object class; @FunctionalInterface may be used;

Method References

Java 8. Alternative to lambda expressions. Allows use of method references instead of lambda expression on functional interfaces.

Stream

Java 8. Java.util.stream. Creates a sequence of elements from a collection (list.stream()) and apply operation to it

Comparator and lambda

Collections.sort(list,(p1,p2)->{ return p1.name.compareTo(p2.name); });

Collections.forEach method loop and lambda

You can use a lambda expression inside foreach loop. E.g. List<String> list = new ArrayList<>(); list.foreach(n->System.out.println(n));

Lambda

Provides implementation to a single-method interface (aka Functional Interface) in an expression; less code, more clear; Skips building a class that implements the interface, and just embedding the implementation into the lambda; an alternative to implementation is to pass only an expression; in this case it will use parentheses instead of braces;

StringJoiner

Java 8. Used to join a series of Strings using a delimiter specified; may also indicate a prefix and a suffix to wrap the series of Strings; StringJoiner joinNames = new StringJoiner(","); // passing comma(,) as delimiter // Adding values to StringJoiner joinNames.add("Rahul");

Optional

Java 8. New Java Type that returns Optional object to help with nullpointer exceptions; Used when calling a chain or embedded methods in an object; Allows clean handling in case of NPEs.

Arrays.parallelSort()

Java 8. Use parallelSort to sort large Arrays greater than 8192 or more than one core processor; Performs better;

String in Switch Statement

Java 7. May use String in Switch statement.

Catch Multiple Exceptions in Single Block

Java 7. More optimized way of coding multiple exceptions. Exceptions are separated by "|". If you listed a general exception, do not specify a specialized exception

Type Inference

Java 7 is smart enough to infer the type of the generic instance (Collection Parameter Type) and may use <> as argument type

Numeric Literals with underscore

Allows underscore to be used for numeric literals for readability.e.g. Int x = 10_000;

Multitenant Datasource configuration

(@Configuration -> initialize and store as @Bean) Initialize HikariDataSource instance for each DB connection properties in a map; Initialize MultiTenantDataSource (extension of Spring's AbstractRoutingDataSource) using the datasource map; Inside the multitenant datasource is an override lookupkey function where it returns the datasource object based on the computed key country_concept stored on ThreadLocal; the computed key is determined from the TenantInterceptor where it reads country and concept from Request Parameters (MultitenantConfiguration, MultiTenantDataSource, TenantContext, TenantInterceptor)

Try-with-resources

Java 7. Block that allows JDBC Connection, Statement, ResultSet to automatically close without a finally clause and close the resources when exiting the block e.g. try (<<resources that implements Closable or AutoClosale>>) { code-block} catch (Exception e);

JDBC

Provides Java universal data access; Java Database Connectivity; Allows connection to a database, flat file or spreadsheets

Assertion

Used to test an assumption in the code; if it fails JVM throws AssertionError; JVM recognizes assertions when -ea or enabled assertion is turned on; eg. assert value >= 18; assert expression; assert expression1:expression2;

For each loop

Traverses elements in an array, args or collection

Java static import

Allows access to any static member of the class directly without supplying the class name; e.g. import static java.lang.System.*; —> out.println("test")

Autoboxing and Unboxing

Autoboxing is the automatic conversion of Java primitive data type to its wrapper type; opposite operation is unboxing;

enum

Java data type with a fixed set of constants (implicitly final and static); can be used on switch statements;

Creating custom Annotation

@interface <<annotation name>> { String param1; String param2;}; You can retrieve the value of the annotation through reflection

Annotation

Metadata that gives additional information to the compiler and jvm; it can be attached to a class, interface, method or field (declarations); in java 8, annotation can be used anywhere where there is a type, e.g. @NonNull String test; Type checking is for improved analysis of java programs and stronger type checking

Generics

These are parameterized Types. Allows Types (Integer, String, etc.) to be a parameter to methods, class and interfaces. Without generics, a collection such as a List allows us to store any type of Object (String, Integer, etc); typecasting is not required; ClassOrInterface<Type>

Throw vs throws

Use throw to throw 3xceptions within a method or static block; use throws on method signatures to declare checked exceptions that can be thrown, may optionally use unchecked exceptions

SOLID Design Principle

S-Single Responsibility Principle. O-Open/Closed Principle. L-Liston Substitution Principle. I-Interface Segregation Principle. D-Dependency Inversion Principle.

DRY Design principle

Don't Repeat Yourself

Behavioral Patterns

1) Chain of Responsibility. 2) Command. 3) Interpreter. 4) Iterator. 5) Mediator. 6) Memento. 7) Observer. 8)State. 9) Strategy. 10) Template Method. 11) Visitor

Structural Patterns

1) Adapter. 2) Bridge. 3)Composite. 4) Decorator. 5) Facade. 6) Flyweight. 7) Proxy.

Creational Patterns

1) Abstract Factory. 2) Builder. 3) Factory method. 4) Prototype. 5) Singleton.

Three types of Design Patterns based on GOF

1) Creational Patterns. 2) Structural Patterns. 3) Behavioral Patterns.

Functional requirements vs non-functional requirements

Functional requirements - are features and capabilities; non-functional requirements - examples are performance, security, reliability, usability, supportsbility

OOP analysis and design

1) Gather requirements. 2) Describe the application. 3) identify the main actors/objects. 4) Describe the interactions through a sequence diagram. 5) Create a class diagram.

OOO concepts

APIE — Abstraction, Polymorphism, Inhertance and Encapsulation

Agile

Iterative approach to software development, meaning continuous analysis, design, integration

Waterfall

Strict linear approach to software management using distinct steps

Java source file structure

Package stmt, import stmt, one top-level class; no wild card imports

Javadoc

Implementation comments

DOM API

DocumentBuilderFactory > DocumentBuilder > Document. ——builder.parse("<url>"); Nodelist > elementItem > item.getFirstChild().getNodeValue()

File API

FileInoutStream and FileOutputStream; superclass is InputStream; or useApacheCommons FileUtil Library

Abstract methods

Methods inside an abstract. Lass which needs to be implemented by a subclass

Abstract class

Combination of concrete superclass and method signatures that are implemented by a subclass; cannot be inistantiated directly

Interface

Applies polymorphism and encapsulation; defines the structure of a class including signature; method should be public or abstract

Abstraction

OOO concept to think of an object in a more general approach. E.g Vehicle and car, truck, etc as sub class; allows the software to be reusable and customizable

Polymorphism

Ability to deal with with an object either as a subclass or it's super class; Classes with very high level of abstraction, like a contract. Low level abstraction deals with implementation details.

Constructor if not specified in a class

Java always add a constructor during compile time when it is not specified

Encapsulation

Hides implementation details of a fuction

URI

URI that uses URN scheme and does not imply availability of resource; e.g. <urn>::="<nid - namespace identifier>:<nss- namespace specific string>

URL

Identifies resource and location; subset of URI

URI

identifies a resource; broader terminology for URL and URN

Factory method of a class

Returns an instance of the class; e.g. DateFormat.getDateInstance()

Gregorian Calendar

Use this to manipulate dates, e.g. add dates or days to a date

StringBuffer

Helper API for strings; multi threaded; must use synchronized method to make it thread safe

StringBuilder

Helper API for Strings; single threaded

Pass by reference

Objects such as Arrays are passed by reference, meaning function can change and operate on the variable inside the function

Pass by copy

Primitive variables and String (complex objects -immutable)

Java method passing of the same type

Private static double addMultipkeValues (double … params) —- treats this as as an arg[] in the main method where it creates an array for each object; allows you to use "for each syntax"; aka varargs

Switch syntax

Can be used on Enum class java6, and on String values too in Java 7

Enum class

New on Java 6; values are constants; can be used to do switch conditions;

Stack memory

Memory were primitive variables and context are stored; faster memory;

Heap memory

Memory where new instances are kept; slower than stack memory

Inheritance on java

Single inheritance (class based); syntax is "extends"

Garbage collector

Java runs a thread that helps manage memory allocated by the JVM; it sweeps off memory on new instances that were de-referenced

JNI

Java Native Interface; allows Java to call native functions in the OS

JVM

Performance suffers on JVM because of indirection, this has been improved by JIT(just in time) compile that optimizes compiled code by predicting runtime code that are commonly executed

Java

Compiles to a byte code instead of machine language which allows it to be portable across different OS platforms; JVM isn a interpreter of a byte code; "write once, run everywhere"

Servlet

Extends Java servlet API; translates client requests; lifecycle (init(), service(), destroy())