Sunday 30 September 2018

                                                Internal concept of Hashset in java



package govind;

public class Employee
{
  private String name;

 public Employee(String name) {
super();
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Employee Name="+name;
}

@Override
public int hashCode() {
System.out.println("Hashcode="+name);
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
System.out.println("equals="+name);
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}

==========================================================================================================================================
package govind;

import java.util.HashSet;

public class HashsetEmployeeMain
{
public static void main(String[] args)
{
HashSet<Employee> employee=new HashSet<>();
employee.add(new Employee("god"));
employee.add(new Employee("god"));
System.out.println(employee);
}

}


===========================================================================================================================================

o/p:--------------------------------------


Hashcode=god
Hashcode=god
equals=god
[Employee Name=god]










Saturday 29 September 2018


                                    enum in java



package govind;

public enum Beer
{
KF,RC,KO,FO;
}


package govind;

public class Test {
public static void main(String[] args) {
Beer b=Beer.KF;
System.out.println(b);
}

}


o/p:--------------------------------------------

KF

============================================================================================================================================

package govind;

public enum Beer
{
KF,RC,KO,FO;
}


package govind;

public class Test {
public static void main(String[] args) {
Beer b=Beer.KF;
switch (b) {
case KF:
System.out.println("it is children's brand");
break;

case KO:
System.out.println("it's too light");
break;
case FO:
System.out.println("bye one get one free");
break;
case RC:
System.out.println("it is not that much kick");
break;
               
                /*case IB:
System.out.println("I m error because i m not define inside enum ");
break;*/

default:
System.out.println("other brans are not recommended");
break;
}

}

}


o/p:----------------------

it is children's brand

=========================================================================================================================================


package govind;

public enum Beer
{
KF,RC,KO,FO;
}


package govind;

public class Test {
public static void main(String[] args) {
Beer[] b = Beer.values();
for(Beer b1:b)
{
System.out.println(b1+"......."+b1.ordinal());


}

}

}


o/p:--------------------------------------------
KF.......0
RC.......1
KO.......2
FO.......3

Friday 28 September 2018

                           exception with respect  to inheritance


case 1:- If base class doesn’t throw any exception but child class throws an unchecked exception.


package govind;

public class Parent {

public void viewName()
{
System.out.println("Govind Ballabh Khan");
}

}


package govind;

public class Child extends Parent
{
public void viewName() throws RuntimeException
{
System.out.println("Java Technology");
}
public static void main(String[] args) {
Parent p=new Child();
p.viewName();
}
}

o/p:-----------------------------------
Java Technology


===============================================================================================================================
case 2: If base class doesn’t throw any exception but child class throws an checked exception

package govind;

public class Parent {

public void viewName()
{
System.out.println("Govind Ballabh Khan");
}

}



package govind;

public class Child extends Parent
{
public void viewName() throws  InterruptedException
System.out.println("Java Technology");
}
public static void main(String[] args) {
Parent p=new Child();
p.viewName();
}
}


o/p:------------------------
compile time error

==========================================================================================================================================
case 3:- When base class and child class both throws a checked exception

package govind;

public class Parent {

public void viewName() throws InterruptedException
{
System.out.println("Govind Ballabh Khan");
}

}


package govind;

public class Child extends Parent
{
public void viewName() throws InterruptedException
{
System.out.println("Java Technology");
}
public static void main(String[] args) {
Parent p=new Child();
try {
p.viewName();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}



o/p:-----------------------------
Java Technology



==========================================================================================================================================
case :-4 When child class method is throwing border checked exception compared to the same method of base class
package govind;

public class Parent {

public void viewName() throws InterruptedException
{
System.out.println("Govind Ballabh Khan");
}

}


package govind;

public class Child extends Parent
{
public void viewName() throws Exception
{
System.out.println("Java Technology");
}
public static void main(String[] args) {
Parent p=new Child();
try {
p.viewName();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}



o/p:---------------------
compile time error

==========================================================================================================================================

Monday 24 September 2018

Sql join

                                                 


Inner Join
-------------------
Inner Join returns only the matching rows in both the tables(i.e. returns only those rows for which the join condition satisfies).

Left Join 
------------------
Left Outer Join/Left Join returns all the rows from the LEFT table and the corresponding matching rows from the right table. If right
 table doesn’t have the matching record then for such records right table column will have NULL value in the result.

Right Join
-------------------
Right Outer Join/Right Join returns all the rows from the RIGHT table and the corresponding matching rows from the left table. If left 
table doesn’t have the matching record then for such records left table column will have NULL value in the result.

Full Join
------------------
It returns all the rows from both the tables, if there is no matching row in either of the sides then it displays NULL values in the result
for that table columns in such rows.

Cross join 
-------------------

Cross join is also referred to as Cartesian Product. For every row in the LEFT Table of the CROSS JOIN all the rows from the RIGHT table are 
returned and Vice-Versa (i.e.result will have the Cartesian product of the rows from join tables).


SELF JOIN
-------------------


If a Table is joined to itself using one of the join types explained above, then such a type of join is called SELF JOIN.















                                                                  



Sunday 23 September 2018


                                           Date & Time API in JAVA-8 (Joda Time Api)

package dateandtimeapi;

import java.time.LocalDate;
import java.time.LocalTime;

public class CurrentTimeDate {
public static void main(String[] args) {
LocalDate date=LocalDate.now();
System.out.println(date);
LocalTime time=LocalTime.now();
System.out.println(time);
}

}


o/p:---------------------------------------------------------------
2018-09-23
22:49:42.580

===================================================================================================================================
package dateandtimeapi;

import java.time.LocalDateTime;

public class LocalDateTimeClassExample {
public static void main(String[] args) {
LocalDateTime dt=LocalDateTime.now();
int dd=dt.getDayOfMonth();
int mm=dt.getMonthValue();
int yyyy=dt.getYear();
System.out.printf("Date:%d-%d-%d",dd,mm,yyyy);
int h=dt.getHour();
int m=dt.getMinute();
int s=dt.getSecond();
int n=dt.getNano();
System.out.printf("\nTime:%d:%d:%d:%d",h,m,s,n);
}
}


o/p:---------------
Date:23-9-2018
Time:22:50:28:52000000


==================================================================================================================================

package dateandtimeapi;

import java.time.LocalDate;

public class DayMonthYearExample {
public static void main(String[] args) {
LocalDate date=LocalDate.now();
int dd=date.getDayOfMonth();
int mm=date.getMonthValue();
int yyyy=date.getYear();
System.out.println(dd+"----"+mm+"----"+yyyy);
System.out.printf("%d-%d-%d",dd,mm,yyyy);
}

}


o/p:-----------
23----9----2018
23-9-2018



==========================================================================================================================================


package dateandtimeapi;

import java.time.LocalTime;

public class HourMinuteSecondNanoSecondExample {
public static void main(String[] args) {
LocalTime time=LocalTime.now();
System.out.println(time);
int h=time.getHour();
int m=time.getMinute();
int s=time.getSecond();
int n=time.getNano();
System.out.printf("%d:%d:%d:%d",h,m,s,n);
}

}

o/p:----------------------------------
22:56:42.767
22:56:42:767000000

===========================================================================================================================================

package dateandtimeapi;

import java.time.Year;
import java.util.Scanner;

public class LeapYearCheck {
public static void main(String[] args) {
Scanner s1=new Scanner(System.in);
System.out.println("Enter Year");
int n=s1.nextInt();
Year y=Year.of(n);
if(y.isLeap())
{
System.out.printf("%d year is leap year",n);
}
else
{
System.out.printf("%d year is not a leap year",n);
}
}

}



o/p:--------------------------------------------------------------------------------------------------------
Enter Year
2004
2004 year is leap year

============================================================================================================================================


package dateandtimeapi;

import java.time.LocalDate;
import java.time.Period;


public class PeriodClassExample {
public static void main(String[] args) {
LocalDate birthday=LocalDate.of(1989, 8, 28);
LocalDate today=LocalDate.now();
Period p=Period.between(birthday,today);
System.out.printf("Your age is %d years %d months and %d days",p.getYears(),p.getMonths(),p.getDays());
LocalDate deathday=LocalDate.of(1989+60, 8, 28);
Period p1=Period.between(today,deathday);
int d=p1.getYears()*365+p1.getMonths()*30+p1.getDays();
System.out.printf("\n You will be on earth only %d days...Hurry up to do more important things",d);

}
}

o/p:--------------------------------------------------------------------------------------------

 Your age is 29 years 0 months and 26 days
 You will be on earth only 11285 days...Hurry up to do more important things




==========================================================================================================================================

package dateandtimeapi;

import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ZonedIdClassExample {
public static void main(String[] args) {
ZoneId zone=ZoneId.systemDefault();
System.out.println(zone);
ZoneId la=ZoneId.of("America/Los_Angeles");
ZonedDateTime dt=ZonedDateTime.now(la);
System.out.println(dt);
}

}

o/p:----------------------------------------------------------------------
Asia/Calcutta
2018-09-23T10:36:17.053-07:00[America/Los_Angeles]


===================================================================================================================================

                                                                    Stream Api in java 8
--------------------------------------------------------------------------------------------------------------------------
collect() method example in java 8

package streamconcept;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class CollectMethodExample {
public static void main(String[] args) {
ArrayList<String> l=new ArrayList<>();
l.add("govind");
l.add("ballabh");
l.add("khan");
l.add("java");
l.add("technology");
System.out.println(l);
List<String> l1 = l.stream().filter(s->s.length()>=5).collect(Collectors.toList());
System.out.println(l1);
List<String> l2 = l.stream().map(s->s.toUpperCase()).collect(Collectors.toList());
System.out.println(l2);
}

}

o/p:-----------------------------------------------------
[govind, ballabh, khan, java, technology]
[govind, ballabh, technology]
[GOVIND, BALLABH, KHAN, JAVA, TECHNOLOGY]

================================================================================================================================
//count() method example.....................
package streamconcept;

import java.util.ArrayList;


public class CountMethodExample {

public static void main(String[] args) {
ArrayList<String> l=new ArrayList<>();
l.add("govind");
l.add("ballabh");
l.add("khan");
l.add("java");
l.add("technology");
System.out.println(l);
    long count = l.stream().filter(s->s.length()>=5).count();
System.out.println("The Length of strings whose length>=5="+count);
}

}
o/p:-----------------------------------------------
[govind, ballabh, khan, java, technology]
The Length of strings whose length>=5=3

=====================================================================================================================================

 Sorted()
 Sorted(comparator c) example in java:---------------------------

package streamconcept;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class SortedMethodExample {
public static void main(String[] args) {
ArrayList<Integer> l=new ArrayList<>();
l.add(0);
l.add(10);
l.add(20);
l.add(5);
l.add(15);
l.add(25);
System.out.println(l);
List<Integer> l1 = l.stream().sorted().collect(Collectors.toList());
System.out.println(l1);
        List<Integer> l2 = l.stream().sorted((i1,i2)->-i1.compareTo(i2)).collect(Collectors.toList());
        System.out.println(l2);

}

}

o/p:-----------------------------------------------
[0, 10, 20, 5, 15, 25]
[0, 5, 10, 15, 20, 25]
[25, 20, 15, 10, 5, 0]


=====================================================================================================================================
foreach() method in java 8 ........................
package streamconcept;

import java.util.ArrayList;

public class ForEachMtehodExample {
public static void main(String[] args) {
ArrayList<String> l=new ArrayList<>();
l.add("govind");
l.add("ballabh");
l.add("khan");
l.add("java");
l.add("technology");
l.forEach(s->System.out.println(s));
}
}


o/p:----------------------
govind
ballabh
khan
java
technology
========================================================================================================================================
min( )
max( ) method in java 8:---------------------------------
package streamconcept;

import java.util.ArrayList;


public class MinMaxMethodExample {
public static void main(String[] args) {
ArrayList<Integer> l=new ArrayList<>();
l.add(0);
l.add(10);
l.add(20);
l.add(5);
l.add(15);
l.add(25);
System.out.println(l);
Integer min = l.stream().min((i1,i2)->i1.compareTo(i2)).get();
System.out.println("Minimum value="+min);
Integer max = l.stream().max((i1,i2)->i1.compareTo(i2)).get();
System.out.println("Maximum Value="+max);
}
}

o/p:--------------------------------------------

[0, 10, 20, 5, 15, 25]
Minimum value=0
Maximum Value=25

======================================================================================================================================
//toArray() method example in java8


package streamconcept;

import java.util.ArrayList;

public class ToArrayMethodExample {

public static void main(String[] args) {
ArrayList<Integer> l=new ArrayList<>();
l.add(0);
l.add(10);
l.add(20);
l.add(5);
l.add(15);
l.add(25);
System.out.println(l);
Integer[] array = l.stream().toArray(Integer []::new);
for(Integer x:array)
{
System.out.println(x);
}
}

}




o/p:-----------------------

[0, 10, 20, 5, 15, 25]
0
10
20
5
15
25

========================================================================================================================================
//Stream.of() method in java 8

package streamconcept;

import java.util.stream.Stream;

public class StreamDotOfMethodExample {

public static void main(String[] args) {
Stream<Integer> s=Stream.of(9,99,999,9999,99999);
s.forEach(System.out::println);

Double d[]= {10.0,10.1,10.2,10.3,10.4,10.5};
Stream<Double> s1=Stream.of(d);
s1.forEach(System.out::println);
}

}


o/p:------------------------------------
9
99
999
9999
99999
10.0
10.1
10.2
10.3
10.4
10.5


Stream concept in java 8:----------------------------------
filter( )
map( )

package streamconcept;

import java.util.ArrayList;
import java.util.List;

public class StreamExampleEvenWithoutStream{
public static void main(String[] args) {
ArrayList<Integer> l=new ArrayList<>();
l.add(0);
l.add(10);
l.add(20);
l.add(5);
l.add(15);
l.add(25);
System.out.println(l);
List<Integer> l1=new ArrayList<>();
for(Integer I1:l)
{
if(I1%2==0)
{
l1.add(I1);
}
}

System.out.println(l1);




}

}

o/p:------------------------------------------------------------------------------------------
[0, 10, 20, 5, 15, 25]
[0, 10, 20]

=======================================================================================================================================

package streamconcept;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExampleEvenWithStream {
public static void main(String[] args) {
ArrayList<Integer> l=new ArrayList<>();
l.add(0);
l.add(10);
l.add(20);
l.add(5);
l.add(15);
l.add(25);
System.out.println(l);
List<Integer> l1=l.stream().filter(i->i%2==0).collect(Collectors.toList());
    System.out.println(l1);
}

}

o/p:------------------------------------------------------------------------------------------
[0, 10, 20, 5, 15, 25]
[0, 10, 20]

=========================================================================================================================================

package streamconcept;

import java.util.ArrayList;
import java.util.List;

public class StreamExampleDoubleValueWithoutStream {

public static void main(String[] args) {
ArrayList<Integer> l=new ArrayList<>();
l.add(0);
l.add(10);
l.add(20);
l.add(5);
l.add(15);
l.add(25);
System.out.println(l);
List<Integer> l1=new ArrayList<>();
for(Integer I1:l)
{
l1.add(I1*2);
}
System.out.println(l1);
}

}


===========================================================================================================================================

package streamconcept;

import java.util.ArrayList;
import java.util.List;

public class StreamExampleDoubleValueWithoutStream {

public static void main(String[] args) {
ArrayList<Integer> l=new ArrayList<>();
l.add(0);
l.add(10);
l.add(20);
l.add(5);
l.add(15);
l.add(25);
System.out.println(l);
List<Integer> l1=new ArrayList<>();
for(Integer I1:l)
{
l1.add(I1*2);
}
System.out.println(l1);
}

}

o/p:-----------------------------------------
[0, 10, 20, 5, 15, 25]
[0, 20, 40, 10, 30, 50]
==================================================================================================================================
package streamconcept;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExampleDoubleValueWithStream {
public static void main(String[] args) {
ArrayList<Integer> l=new ArrayList<>();
l.add(0);
l.add(10);
l.add(20);
l.add(5);
l.add(15);
l.add(25);
System.out.println(l);
List<Integer> l1=l.stream().map(i->i*2).collect(Collectors.toList());
System.out.println(l1);
}

}


o/p:-----------------------------------------
[0, 10, 20, 5, 15, 25]
[0, 20, 40, 10, 30, 50]
==================================================================================================================================
                     //Method Reference Example(Alternative Approach of Lambda Expression)

package methodconstructorreference;

public interface Interf
{
public void m1();
}



package methodconstructorreference;

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

//m1() implementation provide through lambda expression
Interf i=()->
{
System.out.println("lambda implementation");
};
i.m1();
}
}


o/p:-------------------------------------

lambda implementation




=======================================================================================================================

package methodconstructorreference;

public interface InterfMethodReference {
public void m1();
}


package methodconstructorreference;

public class TestMethodRef {


public static  void m2()
{
System.out.println("method reference");
}
public static void main(String[] args) {

InterfMethodReference imr=TestMethodRef::m2;
imr.m1();
}


}


o/p:------------------------
method reference


=========================================================================================================================================

package methodconstructorreference;

public class TestRunnable {
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");
}
}

}


o/p:------------
mixed output


==========================================================================================================================================


package methodconstructorreference;

public class TestRunnableMethodReference {



public void m1()
{
for(int i=0;i<10;i++)
{
System.out.println("child Thread");
}
}
public static void main(String[] args) {
TestRunnableMethodReference trm=new TestRunnableMethodReference();
Runnable r=trm::m1;
Thread t=new Thread(r);
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main Thread");
}
}

}


o/p:-------
mixed output
========================================================================
                                                //Constructor Reference Example

package methodconstructorreference;

public class Sample {
Sample()
{
System.out.println("sample constructor execution and object creation");
}
      }


package methodconstructorreference;

public interface ConstructorReferenceInterf {

public Sample get();

}




package methodconstructorreference;

public class ConstructorReferenceDemo {
public static void main(String[] args) {
//Through lambda expression
/* ConstructorReferenceInterf cri=()->
{
Sample s=new Sample();
return s;
};
Sample s1=cri.get();*/

     //Through Constructor Reference
ConstructorReferenceInterf cri=Sample::new;
Sample s=cri.get();


}

}



o/p:---------------------

sample constructor execution and object creation

Saturday 22 September 2018



Predicate Functional Interface--------------------------------------------------------------------------

package govind;

import java.util.function.Predicate;

public class PredicateExample {

public static void main(String[] args) {
Predicate<Integer> p=I->I>10;
System.out.println(p.test(100));
System.out.println(p.test(5));
//System.out.println(p.test("govind ballabh khan"));//compile time error
}

}

o/p:------------------------

true
false

package govind;

import java.util.function.Predicate;

public class PredicateExampleStringLength {
public static void main(String[] args) {
Predicate<String> p=I->I.length()>5;
System.out.println(p.test("govind"));
System.out.println(p.test("khan"));
}

}
o/p:------------------------
true
false



package govind;

import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Predicate;

public class PredicateExampleCollectionEmpty {

public static void main(String[] args) {
Predicate<Collection> p=c->c.isEmpty();
ArrayList l1=new ArrayList<>();
l1.add("govind");
System.out.println(p.test(l1));
ArrayList l2=new ArrayList<>();
System.out.println(p.test(l2));


}

}


false
true


Function  FunctionalInterface example:--------------------------------------------------------------------------

govind;

import java.util.function.Function;

public class FunctionFunctionalInterface {
public static void main(String[] args) {
//calculate the length of String using Function functional interface
Function<String, Integer> f=s->s.length();
System.out.println(f.apply("govindkhan"));
System.out.println(f.apply("java"));
//calculate the square using Function functional interface
Function<Integer, Integer> k=i->i*i;
System.out.println(k.apply(10));
System.out.println(k.apply(5));


}

}


o/p:-----------------------------------


10
4
100
25


//Consumer FunctionalInterface example------------------------------------------------

package govind;

import java.util.function.Consumer;

public class ConsumerExample {

public static void main(String[] args) {
Consumer<String> p=c->System.out.println(c);
    p.accept("govind ballabh khan");
}

}


o/p:----------------------------------
govind ballabh khan


//Supplier FunctionalInterface example------------------------------------------------

package govind;

import java.util.function.Supplier;

public class SupplierExampleJava8 {
public static void main(String[] args) {
Supplier<String> s1=()->"govind ballabh Khan";
System.out.println(s1.get());
}
}



o/p:----------------------------------
govind ballabh khan

Supplier Example---------------------------------------------------------------------

package govind;

import java.util.function.Supplier;

public class SupplierExample {
public static void main(String[] args) {
Supplier<String> s=()->{String [] s1= {"govind","ballabh","khan","java"};
int x=(int)(Math.random()*3+1);
return s1[x];
};
System.out.println(s.get());
System.out.println(s.get());
System.out.println(s.get());
System.out.println(s.get());

}


}


o/p:----------------------------------------------------------------------------------------------------
khan
khan
ballabh
ballabh

Friday 21 September 2018




                                            FunctionalInterface Vs Lambda Expressions:

Once we write Lambda expressions to invoke it’s functionality, then FunctionalInterface is required. We can use FunctionalInterface reference to refer Lambda Expression.Where ever FunctionalInterface concept is applicable there we can use Lambda Expressions




                                          
                                             Anonymous inner classes vs Lambda Expressions

Wherever we are using anonymous inner classes there may be a chance of using Lambda expression to reduce length of the code and to resolve complexity.


                                         What are the advantages of Lambda expression?

We can reduce length of the code so that readability of the code will be improved.

We can resolve complexity of anonymous inner classes.

We can provide Lambda expression in the place of object.

We can pass lambda expression as argument to methods.
Note:
1. Anonymous inner class can extend concrete class, can extend abstract class,can implement interface with any number of methods but Lambda expression can implement an interface with only single abstract method(FunctionalInterface).

2. Hence if anonymous inner class implements functionalinterface in that particular case only we can replace with lambda expressions.hence wherever anonymous inner class concept is there,it may not possible to replace with Lambda expressions.

3. Anonymous inner class! = Lambda Expression

4. Inside anonymous inner class we can declare instance variables.Inside lambda expression we can’t declare instance variables. Whatever the variables declare inside lambda expression are simply acts as local variables.

5. Inside anonymous inner class “this” always refers current inner class object(anonymous inner class) but not related outer class object.Within lambda expression ‘this” keyword represents current outer class object reference (that is current enclosing class reference in which we declare lambda expression)


Example:






From lambda expression we can access enclosing class variables and enclosing method variables directly.

The local variables referenced from lambda expression are implicitly final and hence we can’t perform re-assignment for those local variables otherwise we get compile time error



                                                                Functional Interfaces:

if an interface contain only one abstract method, such type of interfaces are called functional interfaces and the method is called functional method or single abstract method(SAM).

Example:
1) Runnable : It contains only run() method
2) Comparable : It contains only compareTo() method
3) ActionListener : It contains only actionPerformed()
4) Callable : It contains only call()method

Inside functional interface in addition to single Abstract method(SAM) we can write any number of default and static methods.





In Java 8 , SunMicroSystem introduced @FunctionalInterface annotation to specify that the interface is FunctionalInterface.





InsideFunctionalInterface we can take only one abstract method,if we take more than one abstract method then , we will get compilation error.



Inside FunctionalInterface we have to take exactly only one abstract method.If we are not declaring that abstract method then compiler gives an error message.


                                            FunctionalInterface with respect to Inheritance:

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




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



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




                                                         Lambda (λ) Expression  Java 8:

Lambda calculus is a big change in mathematical world which has been introduced in 1930. Because of benefits of Lambda calculus slowly this concepts started using in programming world. “LISP” is the first programming which uses Lambda Expression.

The Main Objective of λLambda Expression is to bring benefits of functional programming into java.



What is Lambda Expression (λ):

Lambda Expression is just an anonymous(nameless) function. That means the function which doesn’t have the name,
return type and access modifiers.


Lambda Expression also known as anonymous functions or closures.


Example 1: Normal Java method

public void m1() {
 System.out.println(“Hello Java”);
}

Above Normal Java method, you can write using Lambda Expression (λ) in Following way:

( ) -> {
sop(“Hello Java”);
}
or

( ) -> { sop(“Hello Java”); }
or

() -> sop(“Hello Java”);



Example 2 : Normal Java Method with argument

public void add(int a, int b) {
 System.out.println(a + b);
}
Above Normal Java method you can write using Lambda Expression (λ) in Following way:

(int a, int b) -> sop(a+b);

note 1: If the type of the parameter can be decided by compiler automatically based on the context then we can remove types also.

note 2 : The above Lambda expression we can rewrite as (a,b) -> sop (a+b);




Example 3: Normal Java Method with return

public String m1(String str) {
 return str;
}
Above Normal Java method, you can write using Lambda Expression (λ) in Following way:

(String str) -> return str;
or

(str) -> str;






Conclusions :

1. A lambda expression can have zero or more number of parameters(arguments).
Example:
( ) -> sop(“Hello Java”);
(int a ) -> sop(a);
(inta, int b) -> return a+b;
2. Usually we can specify type of parameter.If the compiler expect the type based on the context then we can remove type.
Example:
(int a, int b) -> sop(a+b);
(a,b) -> sop(a+b);
3. If multiple parameters present then these parameters should be separated with comma(,).
4. If zero number of parameters available then we have to use empty parameter [ like ()].
Example:
( ) -> sop(“Hello Java”);
5. If only one parameter is available and if the compiler can expect the type then we can remove the type and parenthesis also.
example:--
(int a ) -> sop(a);
(a) -> sop(a);
 a->  sop(a);

6. Similar to method body lambda expression body also can contain multiple statements.if more than one statements present then we have
to enclose inside within curly braces. if one statement present then curly braces are optional.

Once we write lambda expression we can call that expression just like a method, for this functional interfaces are required.

Thursday 20 September 2018

Lambda Expression Concept With Runnable Interface(Functional Interface)

//Without Lambda Expression package govind; public class MyThread implements Runnable{ @Override public void run() { for(int i=0;i<10;i++) { System.out.println("Child Thread"); } } } package govind; public class MythreadTest { public static void main(String[] args) { Runnable r=new MyThread(); Thread t=new Thread(r); t.start(); for(int i=0;i<10;i++) { System.out.println("Main Thread"); } } } o/p:----------------------------------------------------------ist time-------------------------------------------------------------- Main Thread Main Thread Main Thread Main Thread Main Thread Main Thread Main Thread Main Thread Child Thread Child Thread Child Thread Child Thread Child Thread Child Thread Child Thread Child Thread Child Thread Child Thread Main Thread Main Thread -------------------------------------------------------------2nd time----------------------------------------------------------------------- Child Thread Child Thread Child Thread Child Thread Child Thread Child Thread Child Thread Child Thread Child Thread Child Thread Main Thread Main Thread Main Thread Main Thread Main Thread Main Thread Main Thread Main Thread Main Thread Main Thread Random o/p (dont expect) ================================================================================================================================================================================= //With Lambda Expression package govind; public class MyLambdaThread { public static void main(String[] args) { Runnable r=()->{ for(int i=0;i<10;i++) { System.out.println("Lambda Child Thread"); } }; Thread t=new Thread(r); t.start(); for(int i=0;i<10;i++) { System.out.println("Lambda Main Thread"); } } } o/p:-----------------------------------------------------------ist time------------------------------ Lambda Main Thread Lambda Main Thread Lambda Main Thread Lambda Main Thread Lambda Main Thread Lambda Main Thread Lambda Main Thread Lambda Main Thread Lambda Main Thread Lambda Main Thread Lambda Child Thread Lambda Child Thread Lambda Child Thread Lambda Child Thread Lambda Child Thread Lambda Child Thread Lambda Child Thread Lambda Child Thread Lambda Child Thread Lambda Child Thread ------------------------------------------------------------2nd time---------------------------------------------- Lambda Child Thread Lambda Child Thread Lambda Child Thread Lambda Child Thread Lambda Child Thread Lambda Child Thread Lambda Child Thread Lambda Child Thread Lambda Child Thread Lambda Child Thread Lambda Main Thread Lambda Main Thread Lambda Main Thread Lambda Main Thread Lambda Main Thread Lambda Main Thread Lambda Main Thread Lambda Main Thread Lambda Main Thread Lambda Main Thread Random o/p (dont expect)

                                                      Lambda Expression Example


//Without Lambda Expression 

package govind;

public interface SumInterface
{

public void sum(int a,int b);

}


 class Demo implements SumInterface
{

@Override
public void sum(int a, int b) {
System.out.println("Sum="+(a+b));

}


}



package govind;

class Test
{
public static void main(String[] args) {
SumInterface si=new Demo();
si.sum(40, 60);
                si.sum(400, 500);
}
}
o/p:--------------------------------
Sum=100
Sum=900
=======================================================================================================================================


//with lambda expression


package govind;

public interface AddInterface {


public void add(int a,int b);

}





package govind;

public class TestAddInterface {

public static void main(String[] args) {

    AddInterface ai=(a,b)->System.out.println("Sum="+(a+b));
    ai.add(40, 60);
    ai.add(400, 500);

}

}


==========================================================================================================================================

o/p:-------------------------

Sum=100
Sum=900

Monday 17 September 2018

interface inside default methods in java 8 ?

package govind;


interface inside default method in Java 8

public class DefaultMethodTest {
public static void main(String args[]) {
Printer printer = new PrinterAndScanner();
printer.print();
}
}
interface Printer {
default void print() {
System.out.println("I can print!");
}
}
interface Scanner {
default void scan() {
System.out.println("I can scan!");
}
}
class PrinterAndScanner implements Printer, Scanner {
public void print() {
Scanner.super.scan();
Printer.super.print();
}
}



o/p:--------------------------
I can scan!
I can print!