Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

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.





Functional Programming in Java

The Java 8 promotes functional programming and base is taken from Lamda Expression and they promote these -

Pure function - Completely Independent

Immutability – No change in internal state

First Class functions – use function as value

Higher-order functions – takes function as parameter

 

Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a clear and concise way to represent one method interface using an expression. It is very useful in collection library. It helps to iterate, filter and extract data from collection.

The Lambda expression is used to provide the implementation of an interface which has functional interface. It saves a lot of code. In case of lambda expression, we don't need to define the method again for providing the implementation. Here, we just write the implementation code.

Java lambda expression is treated as a function, so compiler does not create .class file.

Java lambda expression is consisted of three components and related to syntax

 

Argument-list: It can be empty or non-empty as well.

Arrow-token: It is used to link arguments-list and body of expression.

Body: It contains expressions and statements for lambda expression.

 

No Parameter Syntax

() -> {  

}  

 

One Parameter Syntax

(p1) -> {  

 

}  

 

Two Parameter Syntax

(p1,p2) -> {  

}  

 


Design Pattern : Part 2


Earlier in Design Pattern : part 1, We have seen how we can use creational and structural design patterns. In this blog we will cover behaviour design patterns. This design patterns are equally important compare to earlier two and that's the reason it is asked frequently in java interview. The important design patterns are Visitor, Strategy, Command and Observer. Personally I have faced these questions in interview- How we can perform new operation in class without any change in class? Which design pattern is used for undo and redo in text formatter? How to notify object property change to a number of classes? 


Chain of Responsibility:
   This is a way of passing a request between a chain of objects. In this pattern there is a single chain of passing a request with many handlers. Each sender keeps a single reference to the head of the chain, and each receiver keeps a single reference to its immediate successor in the chain. This pattern is used to process those requests that are varied.


Command:
   In this pattern we encapsulate a command request as an object. To call a method later we need some information like method name, its object and its values, to represent that information command pattern is used. It allows a request to be saved in a queue. The Command pattern has three main components: the Invoker, the Command, and the Receiver. 


Interpreter:
  This is a way to include language elements in a program. Interpreter pattern defines how the communication between the entities is controlled in a good manner and also defines the instructions grammar. The interpreter design pattern is useful for simple languages where performance is not critical.


Iterator :
  It helps us sequentially access the elements of a collection. This pattern is used to provide the way to access the aggregate object without any knowledge of Aggregate structure. The iterator object will maintain the state of the iteration, keeping track of the current item and having a way of identifying what elements are next to be iterated. This allows traversing of lists, trees and other structures in a standard manner.


Mediator :
  In this pattern we define simplified communication between classes. Mediator design pattern also deals with communication and defines an object to encapsulate that how the set of an object should interact. It promotes many-to-many relationships between interacting peers and thus defines simplifies communication between classes.


Memento :
  In this pattern we capture and restore an object's internal state. This pattern proves to be helpful in saving the internal state of the object in to external state and enabling us to restore the state later when needed means it easily restore an object to its previous state with minimal lines of coding. Memento pattern helps us to store a snapshot which can be reverted at any moment of time by the object. A word processor providing undo operation or Ctrl+Z is the example of this pattern.


Observer :
  In this we can find out a way of notifying change to a number of classes. This pattern allows us to plug objects into a framework at runtime, which allows for highly flexible, extensible, and reusable software. It is used when it is necessary to ensure that multiple components (called observers or subscribers) are kept in sync with a master set of data (the subject or publisher).



State:
  State Pattern allows an object to alter its behavior dynamically according to its internal state. For this we directly move the logic to property "State" which has method Handle() and call this method. 


Strategy:
  It is useful when we want to encapsulates an algorithm inside a classes. The strategy pattern is very useful when we are in a need of a dynamic formula or data. It is used to separate different types of algorithms that serve a similar purpose. It's a strategy of dealing with a code design with a purpose to decouple concrete code into separate classes, which promotes reusability. 



Template Method:
 The main intention of this This pattern helps us to improve code reusability. It lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. We cannot override the template method. Only the steps given in the skeleton of algorithm of template method need to be overridden in concrete classes.


Visitor :
With the help of visitor pattern the new operations are performed on an existing structure. The visitor pattern also specifies how iteration occurs over the object structure. It is a classic technique for recovering lost type information. 

  • We are covering here -'Java garbage collection interview questions' or 'Java memory interview questions' in d...
  • Java util.collections is one of the most important package in java and the important of this package can be understand by...
  • Java Concurrency interview question - In year 2004 when technology gurus said innovation in Java is gone down and Sun Microsystems [Now Or...
  • 'Java investment bank interview' generally contains 'Java Design Pattern' questions. If you want to be a professional Java ...