Thursday, 24 October 2019

Functional Interface

Functional Interface(FI):-


Functional Interface  contains single abstract method is call functional interface or can have any number of default method or can contains any number of static method.
  1.    Runnable.    è run()
  2.    Comparable è compareTo()
  3.   ActionListener è actionPerformed()
  4.   Callable è call()
Default Method and Static method
Note:

  1.  Functional Interface can contains single abstract method cannot allow multiple abstract method.
  2.  Functional interface can contains any number of default method or static method.
  3.  Java 8, Sun Micro System introduced @Functional Interface annotation to specify that the interface           is Functional Interface.

Example 1.

                    @FunctionalInterface
                      interface A {

public void m1();
                                  default void m2();
public static void  m3()
                                  {
     
                                  }
                            }

Note:
This example interface contains single abstract method, one default method and one static method.



Functional interface with receipt to inheritance:

  •           Parent interface is Functional interface then child interface is also functional interface
  •         Parent interface method automatically available in child interface. It is not provide the method  through user
Example 2. This code gives compilation error.

@FuncationalInterface
   interface A
   {
       public void test1();
       public void test2();
   }
Above example Inside Functional Interface we can take only one abstract method, if we take more than one abstract method then compiler raise an error message that is called we will get compilation error.

Example 3.

If an interface extends Functional Interface and child interface doesn’t contain any abstract method then child interface is also Functional Interface

@Functional Interface
 interface A { 
       public void test(); 
} 
 @Functional Interface 
Interface B extends A
 {   } 

Example 4. In the child interface we can define exactly same parent interface abstract method.

@Functional Interface 
 interface A { 
    public void testOne(); 
}
 @Functional Interface 
 interface B extends A {                         
      public void testOne(); 
 }
Output :- Compile Successfully.

Example 5.

In the child interface we can’t define any new abstract methods otherwise child interface won’t be Functional Interface and if we are trying to use @Functional Interface annotation then compiler gives an error message.

@Functional Interface { 
interface A { 
       public void testOne(); 
 }                                                             
@Functional Interface 
  interface B extends A
  { 
        public void testTwo(); 
  }

Output:- Compile time Error.

Example 6.

@FunctionalInterface
   interface A
  {     
         public void testOne();
  }                                                                 
  interface B extends A
 {         
        public void testTwo(); 

  }

No compile time error

In the above example in both parent & child interface we can write any number of default methods and there are no restrictions. Restrictions are applicable only for abstract methods.


Example 7. Without Lamda Expression.

interface interf{
public void m1();
}
class Demo implements interf{

@Override
public void m1() {
System.out.println("m1() Method implementation");

}

}
public class WithoutLambdaTest {

public static void main(String[] args) {
interf in = new Demo();
in.m1();

}

}

Output:- m1() Method implementation


Example 8. With Lambda Expression.

interface Interfa{
public void m1();
}
public class WithLambdaTest {

public static void main(String[] args) {
Interfa in =()->System.out.println("m1() Method implementation");
in.m1();
}

}

Output :- m1() Method implementation

Example 9. Without Lambda Expression

interface interA{
public int square(int n);
}
class Demosq implements interA{

@Override
public int square(int n) {
return n * n;
}
}
public class Test2WithoutLambda {

public static void main(String[] args) {
interA a = new Demosq();
System.out.println(a.square(3));
}
}

Output:- 9

Example 10. With Lambda Expression

interface interTest{
public int square(int n);
}
public class Test2WithLambda {

public static void main(String[] args)
 {
interTest test = n -> n*n;
System.out.println("square is :"+test.square(3));
}
}

Output:- 9

Example 11. With Lambda Expression

interface Interfm
{
public void m1(int i);
}

public class Test3WithLambda
{
public static void main(String[] args)
     {

Interfm in = (i)-> System.out.println(i*i);
in.m1(10);
}
}

Output:-100

Example 12. Without Lambda Expression using Thread

class MyRunnable implements Runnable{

@Override
public void run() {
for(int i=0; i<10; i++){
System.out.println("Child Thraed");
}

}

}
public class ThreadDemo1 {

public static void main(String[] args) {

MyRunnable mr = new MyRunnable();
Thread t= new Thread(mr);
t.start();
for(int i=0; i< 10; i++){
System.out.println("Main Thread");
}
}
}

Example 13. With Lambda Expression using Thread

public class ThreadDemoWithLambda {

public static void main(String[] args) {

Runnable r = ()->{
for(int i=0; i<10; i++){
System.out.println("Child Thread");
}
};
Thread t = new Thread(r);
t.start();
for(int i=0; i<10; i++){
System.out.println("Main Thread");
}
}
}



Example :14. How to Convert Fahrenheit to Celsius using Lambda Expression.

Output:
37.0

4.970969537898672

Java 8 Features

Java 8 is the most powerful and is a major feature release of Java programming language. We explains the basic-to-advanced features of Java 8 and their usage in a simple and effective way.

Advantage of  java 8 (Why java change 1.8 version)

  1. To simplify the java programming.
  2. To utilize the functional programming benefits in java.
  3. To enable parallel programming.

Topic  java 8 new Features

  1. Lambda Expressions
  2. Functional interface
  3. Default Method interface and Static Method interface
  4. Predefined Functional Interface
    • Predicate
    • Function
    • Consumer
    • Supplier
  1. Double Colon Operator(::)
    • Method reference
    • Constructor reference
  1. Streams API
  2. Date and Time APIècoming form the joda.org
  3. Optional class
                9. Nashron JavaScript Engine

Monday, 21 October 2019

Default Method in Funcational Interface


Default Methods inside Functional interface.

  1.  Until 1.7 version onwards inside interface we can take only public abstract methods and public static final variables (every method present inside interface is always public and abstract whether we are declaring or not). 
  2.  Every variable declared inside interface is always public static final whether we are declaring or not. 
  3.  From 1.8 version onwards in addition to these,   we can declare default concrete methods also inside interface, which are also known as defender methods. 
  4.  We can declare default method with the keyword “default” as follows 

Syntex of Default Method of  Funcational Interface

     default void test1()
     {
         System.out.println("Default Method");
      }


Interface default methods are by-default available to all implementation classes. Based on requirement implementation class can use these default methods directly or can override.


Example 1. With Default method.

interface TestInterface{

default void m1(){

System.out.println("Default Method");
}
}
public class TestDefaultMethod implements TestInterface {

public static void main(String[] args)
{
TestDefaultMethod defaultMethod = new TestDefaultMethod();

defaultMethod.m1();
}
}

Output:- Default Method

  1. Default methods also known as defender methods or virtual extension methods.
  2. The main advantage of default methods is without effecting implementation classes we can add new functionality to the interface (backward compatibility).


Note: We can’t override object class methods as default methods inside interface otherwise we get compile time error.

Example 2

interface Interf { 
        default inthashCode() { 
            return 10; 
        } 
}
 Output:- Compile Time Error


Reason: Object class methods are by-default available to every Java class hence it’s not required to bring through default methods.


Default Method Vs multiple inheritance

Two interfaces can contain default method with same signature then there may be a chance of ambiguity problem (diamond problem) to the implementation class. To overcome this problem compulsory we should override default method in the implementation class otherwise we get compile time error.

 Example 1.1:   

interface Left { 
         default void m1() { 
               System.out.println("Left Default Method"); 
      } 
}   

Example 1.2: 

interface Right { 
         default void m1() { 
                 System.out.println("Right Default Method"); 
         } 
 } 

Example 1.3.

class Test implements Left, Right {}

How to override default method in the implementation class

In the implementation class we can provide complete new implementation or we can call any interface method as follows.

                                   interfacename.super.m1();

Example 3.

interface Left{
default void m1(){
System.out.println("Left default method implemention");
}

}
interface Right{
default void m1(){
System.out.println("Right default method implemention");
}
}
public class Test3DefaultMethod implements Left,Right{

public void m1(){
//System.out.println("My own Implemention");
Left.super.m1();
Right.super.m1();
}
public static void main(String[] args) {
Test3DefaultMethod method= new Test3DefaultMethod();
method.m1();

}
}

Output:- 

Left default method implemention
Right default method implemention

Example 4.

interface Test2Interface{

default void m1(){
System.out.println("Default Method");
}

}
public class Test2DefaultMethod implements Test2Interface{

   public void m1(){
System.out.println("My Own implementation");
}
public static void main(String[] args) {

Test2DefaultMethod defaultMethod = new Test2DefaultMethod();
defaultMethod.m1();
}
}

Output :- My Own implementation




Sunday, 20 October 2019

Lambda Expression

                                             
  1.  Lambda Expression is  a mathematical term and big change in calculus in mathematics. 
  2.  Lambda has been introduced in 1930.
  3.  Lambda expression is a new feature which is introduced in Java 8.
  4.  A lambda expression is an anonymous function. A function that doesn’t have a name   and  doesn’t belong to any class. 
  5. Lambda expression was first introduced in LISP programming language.

Lambda Expression is just anonymous function/nameless function, Which is not having any name, return type, modifiers.

It is anonymous function
Anonymousè 1. No name
  2. Without return type
  3. Without modifiers

Advantage of Lambda Expression

  1. We can enable functional programming in java.
  2. We can reduce length of the code so that readability will be improved.
  3. We can resolve complexity of anonymous inner class until some intent.
  4. We can handle procedures/function just like values.
  5. We can pass procedures/functions as arguments.
  6. Easier to use updated APIs and Libraries.
  7. Enable support for parallel processing.

Example 1: Without using Lambda expression with no parameter.

                                      public void test()
                                     {
                                           System.out.println("Hi Java");
                                     }

  Lambda Expressions: It is use special symbols (à) and curly braces are optional ({}) in this       example
             
                                     () -> {  System.out.println("Hi Java"); }

                                     () ->   System.out.println("Hi Java");
             
   Example 2: Without using Lambda expression with multiple parameter.
           
                                       public void test( int i , int j)
                                      {
                                            System.out.println(i+j);
                                       }     

  1. If the type of the parameter can be decided by compiler automatically based on the context then we can remove types also. 
  2. The above Lambda expression we can rewrite as (i,j) ->sop (i+j); 

    With Lambda Expression with multiple parameter.

                                     (int i , int j) -> {  System.out.println(i+j); }
                                                                or
                                     (i,j) ->   System.out.println(i+j);



     Example 3:  Without using Lambda expression to return.

                                     public int square(int n)
                                    {
                                           return n*n;
                                    }

       With Lambda Expression
     
                                          (int n) ->{return n*n;}
                                                       or
                                                (int n )->n*n;
                                                       or
                                                   (n)->n*n;
                                                        or
                                                    n->n*n;
     Note:

  1. Without curly braces we cannot use return keyword. Compiler will consider returned value automatically.
  2.  Within curly braces if we want to return some value compulsory we should use return statement.

      Example 4: With out using Lambda expression how to get length.

                                                  public void test(String s)
                                                  {
                                                         return s.length();
                                                  }

       With Lambda Expression

                                                  s-> s.length();


   Note:
  1.   We can see that the with Lambda expression code and without Lambda expression.
  2.   We can see that Lambda expression is less code
Lambda Expressions with Collections