Java 8 Features - TOP8

Java 8 features is very frequenctly asked question in advance java iterviews.
  • Lambda expression − Adds functional processing capability to Java.

  • Method references − Referencing functions by their names instead of invoking them directly. Using functions as parameter.

  • Default method − Interface to have default method implementation.

  • New tools − New compiler tools and utilities are added like ‘jdeps’ to figure out dependencies.

  • Stream API − New stream API to facilitate pipeline processing.

  • Date Time API − Improved date time API.

  • Optional − Emphasis on best practices to handle null values properly.

  • Nashorn, JavaScript Engine − A Java-based engine to execute JavaScript code.


1) Interface Static method:


Interfaces can now define static methods. This is example for natural order static method in Comparator interface

public static >
    Comparator naturalOrder() { 
   return (Comparator)       
 Comparators.NaturalOrderComparator.INSTANCE;
}


2) Functional interfaces


This enhancement is core of Java 8 changes. An interface is a functional interface if it defines exactly one abstract method. For instance, 
java.lang.Runnable is a functional interface because it only defines one abstract method:

public abstract void run();



3 ) Lambda expressions

A lambda expression is characterized by the following syntax.

parameter -> expression body

Following are the important characteristics of a lambda expression.

  • Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.

  • Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.

  • Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.

  • Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.


4) Method references
   Java 8 Method reference is used to refer method of functional interface . It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.

5) Stream API,

Java 8 java.util.stream package consists of classes, interfaces and an enum to allow functional-style operations on the elements. It performs lazy computation. So, it executes only when it requires.

6) Default methods,

Java provides a facility to create default methods inside the interface. Methods which are defined inside the interface and tagged with default keyword are known as default methods. These methods are non-abstract methods and can have method body.

7)Base64 Encode Decode,

Java provides a class Base64 to deal with encryption and decryption. You need to import java.util.Base64 class in your source file to use its methods.

This class provides three different encoders and decoders to encrypt information at each level.


8) Optional class,
introduced a new class Optional in Java 8. It is a public final class which is used to deal with NullPointerException in Java application. We must import java.util package to use this class. It provides methods to check the presence of value for particular variable.

Java 8 Security Enhancements

1) The Java Secure Socket Extension(JSSE) provider enables the protocols Transport Layer Security (TLS) 1.1 and TLS 1.2 by default on the client side.

2) A improved method AccessController.doPrivileged has been added which enables code to assert a subset of its privileges, without preventing the full traversal of the stack to check for other permissions.

3) Advanced Encryption Standard (AES) and Password-Based Encryption (PBE) algorithms, such as PBEWithSHA256AndAES_128 and PBEWithSHA512AndAES_256 has been added to the SunJCE provider.





Design Pattern - Structural Patterns

<< Creational Patterns : Previous blog 

Structural Patterns

Structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities. These design patterns help us on similar programming structure in application and help us in application wide coding standard. 
Adapter:
the adapter pattern (often referred to as the wrapper pattern or simply a wrapper) is a design pattern that translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface. The adapter translates calls to its interface into calls to the original interface, and the amount of code necessary to do this is typically small. The adapter is also responsible for transforming data into appropriate forms. For instance, if multiple boolean values are stored as a single integer (i.e. flags) but the client requires individual boolean values, the adapter would be responsible for extracting the appropriate values from the integer value. Another example is transforming the format of dates (e.g. YYYYMMDD to MM/DD/YYYY or DD/MM/YYYY).
Example: Adapter Pattern is useful where we want to do integration from one format to another
  > java.util.Arrays#asList()
  > java.io.InputStreamReader(InputStream) (returns a Reader)
  > java.io.OutputStreamWriter(OutputStream) (returns a Writer)


Facade:
A facade Pattern is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:
  • make a software library easier to use, understand and test, since the facade has convenient methods for common tasks;
  • make the library more readable, for the same reason;
  • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
  • wrap a poorly designed collection of APIs with a single well-designed API (as per task needs).
Example: Facade pattern is used to make any library classes and It help us to build module as service. 
  > javax.servlet.http.HttpSession
 > javax.servlet.http.HttpServletRequest
 > javax.servlet.http.HttpServletResponse
 > javax.faces.context.ExternalContext


Proxy:
A proxy, in its most general form, is a class functioning as an interface to do something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.
A well-known example of the proxy pattern is a reference counting pointer object.
In situations where multiple copies of a complex object must exist, the proxy pattern can be adapted to incorporate the flyweight pattern in order to reduce the application's memory footprint. Typically, one instance of the complex object and multiple proxy objects are created, all of which contain a reference to the single original complex object. Any operations performed on the proxies are forwarded to the original object. Once all instances of the proxy are out of scope, the complex object's memory may be deallocated.
Example: This pattern is useful to create surrogate service, where client does not know about actual implementation.  java.rmi.* service uses Proxy pattern to communicate on network.

Bridge:
The bridge pattern is meant to "decouple an abstraction from its implementation so that the two can vary independently". The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.
When a class varies often, the features of object-oriented programming become very useful because changes to a program's code can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when both the class as well as what it does vary often. The class itself can be thought of as the implementation and what the class can do as the abstraction. The bridge pattern can also be thought of as two layers of abstraction.
The bridge pattern is often confused with the adapter pattern. In fact, the bridge pattern is often implemented using the class "adapter pattern", e.g. in the Java code below.
Example: The Bridge pattern is an application of the old advice, "prefer composition over inheritance". It becomes handy when you must subclass different times in ways that are orthogonal with one another. Say you must implement a hierarchy of colored shapes. You wouldn't subclass Shape with Rectangle and Circle and then subclass Rectangle with RedRectangle, BlueRectangle and GreenRectangle and the same for Circle, would you? You would prefer to say that each Shape has a Color and to implement a hierarchy of colors, and that is the Bridge Pattern.

Composite:
Composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

Component
  • is the abstraction for all components, including composite ones
  • declares the interface for objects in the composition
  • (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate
Leaf
  • represents leaf objects in the composition .
  • implements all Component methods
Composite
  • represents a composite Component (component having children)
  • implements methods to manipulate children
  • implements all Component methods, generally by delegating them to its children
Example: This pattern is used in making Rule engine or validation pattern, where composite and single rule can be used in same way.

    Decorator:
    the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases at run-time, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class. This wrapping could be achieved by the following sequence of steps:
    1. Subclass the original "Decorator" class into a "Component" class (see UML diagram);
    2. In the Decorator class, add a Component pointer as a field;
    3. Pass a Component to the Decorator constructor to initialize the Component pointer;
    4. In the Decorator class, redirect all "Component" methods to the "Component" pointer; and
    5. In the ConcreteDecorator class, override any Component method(s) whose behavior needs to be modified.
    This pattern is designed so that multiple decorators can be stacked on top of each other, each time adding a new functionality to the overridden method(s).
    The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at run-time for individual objects.
    This difference becomes most important when there are several independent ways of extending functionality. In some object-oriented programming languages, classes cannot be created at runtime, and it is typically not possible to predict, at design time, what combinations of extensions will be needed. This would mean that a new class would have to be made for every possible combination. By contrast, decorators are objects, created at runtime, and can be combined on a per-use basis. The I/O Streams implementations of both Java and the .NET Framework incorporate the decorator pattern.
    Example for this: Java collections object using Collections.synchronized() method to synchronize the collection at run time. All subclasses of java.io.InputStreamOutputStreamReader and Writer have a constructor taking an instance of same type. Another good example is javax.servlet.http.HttpServletRequestWrapper and HttpServletResponseWrapper.

    Flyweight:
    A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.
    A classic example usage of the flyweight pattern is the data structures for graphical representation of characters in a word processor. It might be desirable to have, for each character in a document, a glyph object containing its font outline, font metrics, and other formatting data, but this would amount to hundreds or thousands of bytes for each character. Instead, for every character there might be a reference to a flyweight glyph object shared by every instance of the same character in the document; only the position of each character (in the document and/or the page) would need to be stored internally. Another example is string interning.
    In other contexts the idea of sharing identical data structures is called hash consing.
    Sample Code for Fly weight pattern.
    Example :  This pattern is used with method overloading and  java.lang.Integer#valueOf(int) (also on BooleanByteCharacterShort and Long) is example of this.

    Next >>  Behavioural Patterns.

    Database fundamentals pratice

     As starting preparation for another technical role. I have started brushing my basic skills.

    DB is also core of our business application. so starting practice basic sql 

    Main application component for same

    > DB User

    > DB Schema

    > DB Data

    This is these 3 steps for Oracle or any other RDBMS for basic SQL practice -

    User Creation -

    -- script to create 
    DROP user learning;
    CREATE USER learning IDENTIFIED BY learning;
    GRANT CONNECT TO learning;
    GRANT CONNECT, RESOURCE, DBA TO learning;
    GRANT CREATE SESSION GRANT ANY PRIVILEGE TO learning;
    GRANT UNLIMITED TABLESPACE TO learning;


    -- Schema creation - DDL 

    Drop table dept cascade constraints

    Create or replace  table dept( deptno number(2,0), dname varchar2(14), loc varchar2(13), constraint pk_dept primary key (deptno) )

    Drop table emp cascade constraints;

    create  or replace table emp

    ( empno number(4,0),

     ename varchar2(10), 

    job varchar2(9), 

    mgr number(4,0), 

    hiredate date,

    sal number(7,2), 

    comm number(7,2),

    deptno number(2,0), 

    constraint pk_emp primary key (empno) 

    );



    DML 

    --Insert row into DEPT table using named columns.

    insert into DEPT (DEPTNO, DNAME, LOC) values(10, 'ACCOUNTING', 'NEW YORK');

    insert into dept  values(20, 'RESEARCH', 'DALLAS');

    insert into dept  values(30, 'SALES', 'CHICAGO');

    insert into dept  values(40, 'OPERATIONS', 'BOSTON');


    Pasted from <https://livesql.oracle.com/apex/livesql/file/content_O5AEB2HE08PYEPTGCFLZU9YCV.html> 


    insert into emp  values(   7839, 'KING', 'PRESIDENT', null,   to_date('17-11-1981','dd-mm-yyyy'),   5000, null, 10  );


    insert into emp  values(   7698, 'BLAKE', 'MANAGER', 7839,   to_date('1-5-1981','dd-mm-yyyy'),   2850, null, 30  );


    insert into emp  values(   7782, 'CLARK', 'MANAGER', 7839,   to_date('9-6-1981','dd-mm-yyyy'),   2450, null, 10  );


    insert into emp  values(   7566, 'JONES', 'MANAGER', 7839,   to_date('2-4-1981','dd-mm-yyyy'),   2975, null, 20  );