0% found this document useful (0 votes)
7 views

From Basic To Master Java Core Concepts With Examples + Theory

Uploaded by

saqlaindange27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

From Basic To Master Java Core Concepts With Examples + Theory

Uploaded by

saqlaindange27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Java 8 Features :-the maoin objective is we can write concise code or easy code in

java
-the main advantage of java 8 is java has enabled functional programming like other
language

Lambda Expressions :-the main objective of Lamda Expression is to bring benefits of


functional programming in java
-it is nothing but anonymous function
Example 1:
() -> { System .out.println("Hello"); } //here before java 8 without lamda
expression public void m1() { sop("hello") }
-if there is only one line code in anonymous function then there is no need of
using {} brackets its optional for one line code but mandatory if their are
multiple lines

-Example 2:-
public void m1(int a,int b)
{
SOP(a+b);
}
........converting into anonymous function/Lamda Expression.....
(a,b) -> SOP(a+b);
here we also removed Datatype because compiler will by himself guess datatype
automatically

.................
-Example 3:-
public int squareIt(int n)
{
return n*n;
}
........converting into anonymous function/Lamda Expression....
(int n) -> {return n*n; }
Points to remember :-if we are writing return keyword then mandaotory we have to
use {} brackets for single line also
-we can also write above example 3 without return keyword as follow
(int n) -> n*n; // no nned to write ruturn keyword compiler will automatically
conclude it
-if the compiler can guess datatype then we also dont need to mention datatype as
follows
(n)->n*n;
-if there is only one input parameter then no need to use parentatis(() brakets)
also.Now the big line method is converted into 1 line lamda expression
n->n*n;
.................
..............
-Example 4
public void m1(String s)
{
return s.length();
}
.............converting into Lamda Expression
s->s.length();
................
...................................................................................
..............
Functional Interface :-A interface which contains only one abstract method are
called as functional Interface for
-Functional Interface can be used to call lamda Expression
-Functional Interface should contain only one abstract method but there is no
restriction for default and static method, functional Interfcae can contain
numerious default and static method there is no restriction
-@FuntionalInterface :-just to specify explicitly that an Interface is functional
interface
-this @FuntionalInterface annotation is optional the advantage of using this
annoataion is if we do any mistake compiler will give compile time error
-declaring @FuntionalInterface is optional. if our interface containing only one
abstract method then is automatically called as funtional interface
...................................................................................
................................
Functional Interface with respect to inheritance:

-Example1 :-if parent is functional interface then child is also functional


interface if the child doesnt define any new abstract method
interface A
{
public void m1();
}

interface B extends A
{
}
--Example2 :-if parent is functional interface then child is also functional
interface if the child doesnt define any new abstract method
interface A
{
public void m1();
}

interface B extends A
{
public void m1();
}
--Example 3:-it is invalid because now child interface contains 2 abstract method
one is from parent and one is defined in child which is m2()
interface A
{
public void m1();
}

interface B extends A
{
public void m2();
}

.................................................................................
Lamda Expression with Functional Interface:
-if we want to call lamda expression functional expression must be required
-to provide reference to lamba expression function inerface is required
-by using functional interface refernce we can call m1() method which internally
calls the pointed lamba expression

.........
Example1:-without lambda expression
interface Interf
{
public void m1();
}

class Demo implements Interf


{
SOP("Hello");
}
class Test
{
p s v main()
{
Interf i = new Demo();
i.m1();
}
}

Example 1:-with lamba expression

interface Interf
{
public void m1();
}
class Test
{
p s v main()
{
Interf i =()->SOP("Hello");
i.m1(); //whenever
}
}

Note : () is the argument to m1() method present in interf functional interface. As


functional interface contains only one method thats why everytime () will be
considered argument to that abstract method by compiler
Note : -by using functional interface refernce we can call m1() method which
internally calls the pointed lamba expression

............
Example 2:-wiyhout lamba expression
interface interf
{
public void add(int a,int b)
}

class Demo implements Interf


{
public void add(int a,int b)
{
sop("the sum:"+(a+b));
}
}
class test
{
p s v main(
{
Interf i = new demo();
i.add(10,20);
}
}

Example 2 :-with lambda


interface interf
{
public void add(int a,int b)
}
class test
{
publc s v main()
{
Interf i = (a,b)->SOP("the sum:"+(a+b))
i.add(10.20);
i.add(100,200);
}
}

Note :-here (a,b) argument will directly point to method present in interface
because functional interface contains only one abstract method
............................................................................

Q.What is Lamda Expression


->Lamda Expression is anonymous function

Q.What is anonymous function


->nameless,without return type and without modifiers are called anonymous function
...................................................................................
.......
NOTE***:for lamda expression no seperate .class file will be generated
.....................................................................
predefined functional interface:-present in java.util.function

...................................................................................

Q.Example of multi-threading using lamba expression


class test
{
public static void main()
{
Runnable r=()->{
for(int i=0;i<10;i++)
{
SOP("child Thread")
}
};
Thread t = new Thread(r);
t.start();
for(int i=0;i<10;i++)
{
SOP("main Thread")
}
}
}
..............................................................................
Q.using Labda expression on collection for sorting using comparator funtional
interface

class test
{
p s v m()
{
ArrayList<Integer> i= new ArrayList<Integer>();
i.add(20);
i.add(10);
i.add(25);
i.add(5);
SOP(l);
Comparator<Integer> c=(I1,I2)->(I1<I2)?-1:(I1>I2)?1:0;
Collections.sort(l,c);
}
}

................................................................................
Q.Sorting according to Employee number using Lamda Expression

class Employee
{
String name;
int eno;
Employee(String name,int eno)
{
this.name=name;
this.eno=eno;
}
public String toString()
{
return name+":";
}
}
class Test
{
public static void main()
{
Array:List<Employee> l= new ArrayList<Employee>();
l.add(new Employee("Durga",02));
l.add(new Employee("Sunny",05));
l.add(new Employee("Bunny",01));
l.add(new Employee(""chinny",10));
SOP(l);
collections.sort(l,(e1,e2)->(e1.eno<e2.no)?-1:(e1.eno>e2.eno)?1:0);
SOP(l);
}
}
......................................................

Q.Sorting according to Employee name using Lamda Expression

class Employee
{
String name;
int eno;
Employee(String name,int eno)
{
this.name=name;
this.eno=eno;
}
public String toString()
{
return name+":";
}
}
class Test
{
public static void main()
{
Array:List<Employee> l= new ArrayList<Employee>();
l.add(new Employee("Durga",02));
l.add(new Employee("Sunny",05));
l.add(new Employee("Bunny",01));
l.add(new Employee(""chinny",10));
SOP(l);
collections.sort(l,(e1,e2)->e1.name.compareTo(e2.name));
SOP(l);
}
}

............................................................................
Lamda Expression vs anonymous inner class

-Anonymous inner class is more powerful than lamda expression


-if anonymous inner class implements an interface that contains sngle abstract
method then only we can replace that anonymous inner class with lamda expression
-if interface conntains more then one abstract method we cant go with lamda
expression
-program is captured from phone camera
...............................................................................
Default Method | Virtual Extension Method | Defender Method :-
-Without effecting existing implementation classes if we want to add new method to
the interface then we should go for default Methods
-Default methods consists default implemetation thats why it is called default
method
Example :-
interface interf
{
default void m()
{
SOP("Default method")
}
class Test Implements interf
{
public void m1() line 5: // overrding this default m1() method is programmers
choice as it wont give any CE if we are not implementing it
{
SOP("overriding version of default method");
}
public static void main()
{
Test t = new test();
t.m1();
}
}

Note***:-observe line 5 while overriding default method we are writing 'public void
m1()' instead of 'default void m1()' because default method can only be written in
interface not in classes, as in classes meaning of default is different

Note***:-we cant write object class methods as defualt methods in interface if we


do so we will get CE:default method hashCode in interface Interf overrides a member
of java.lang.object

-Scenario where two interface having default method with same name and how
implementating class will call required default method without getting into
ambiguity stat
interface Left
{
default void m1()
{
SOP("Left interface m1 method");
}
}
interface Right
{
default void m1()
{
SOP("Right interface m1 method");
}
}
class test implements Left,Right
{
public void m1()
{
//SOP("our own m1 method");
Left.super.m1(); // this will call m1() default method of Left interface
}
p s v main()
{
Test t = new Test();
t.m1()
}
}
...................................................................................
.......................
static methods :-From 1.8v onwards interface provided support for static methods
but this static method by default not available to implementation class
-interface static method should be called using interface name only because
implementation class wont get interface static method automatically
-Example :-interface Interf
{
public static void m1()
{
SOP("Interface static method");
}
}
class Test implements Interf
{
p s v main()
{
Interf.m1(); //valid

m1(); //invalid interface static method should be called using interface name only

Test.m1(); //invalid interface static method should be called using interface name
only

Test t = new Test(); //invalid interface static method should be called using
interface name only
t.m1();
}
}

-from i.8v onwards we can decclare static method inside interface and happily we
can invoke interface directly from cmd because interface can contain main methods
also
-to define general utility methods inside interface static method concept can be
used
-static method which are declared inside interface by default noot avaiable to the
implementation classes compulsory we have to call by using interface name only
-interface static method can be called only by using interface name
...................................................................................
...............
Q.just an example

public boolean test(Integer I)


{
if(i%2==0)
{
return true;
}
else
{
return false;
}
}
......converting into lamda expression....
i->i%2==0
...................................................................................
...........
Predefined Functional Interfaces(1.8v) :-can be used to call Lamda expression.
Compulsory functional interface reference is required to call Lamda Expression

1)Predicate Functional Interfaces:- if our programming wherever some conditional


checks are required happily we can use predicate concept with lamda expression to
achive concise code
-Predicate funtional interface consists only one method which returns boolean value

-predicate returns always boolean


-predicate is nothing but boolean value function
-Example 1:- to check even numbers
class test
{
public static void main()
{
Predicate<Integer> p1=i->i%2==0;
sop(p1.test(10)) //true
sop(p1.test(11)) //false
}
}

-Example 2:-write a predicate to check whether length of string is > 5 or not


import kava.util.function.*;
class Test
{
p s v main()
{
String[] s =("Nag","chiranjeevi","kismat")
Predicate<String> p=s1->s.length()>5;
for(String s1 : s)
{
if(p.test(s1))
{
SOP(s1);
}
}
}
}

Example 3:-to find employee salary greater than 3000


class Employee
{
String name;
double salary;
Employee(String name,double salary)
{
this.name=name;
this.salary=salary;
}
}
class Test
{
p s v main()
{
ArrayList<Employee> i = new ArrayList<Employee>();
l.add(new Employee("durga",1000));
l.add(new Employee("mahesh",20033));
l.add(new Employee("pritam",600000));
l.add(new Employee("rakesh",564880));
l.add(new Employee("kiran",443230));

Predicate<Employee> p=e->e.salary>3000;
for(Employee e1 : l)
{
if(p.test(e1))
{
SOP(e1.name+':'+e1.salary);
}
}
}
}

.......
Q.when to use predicate?
->if you want conditional checking in our programming with using lamda expression
then predicate finctional interface is best choice
........

Predicate Joining :-and(),or(),negate() by using these 3 methods we can able to


implement predicate joining
-Example 1:-
class test
{
p s v main()
{
int[] x=(0,5,10,15,20,25,30,35)
Predicate<Integer> p1=i->i%2==0
Precidate<Integer> p2=i->i>10;
SOP("displaying numbers which are even and greater than 10")
for(int x1 : x)
{
if(p1.and(p2).test(x1)
{
SOP(x1);
}
}
}
}

...................................................................................
...................................

2)Function Functional Interface :-Programmer can use this interface when expecting
return type is not only boolean.
-it takes two argument 1.input type and 2.return type
-Example 1:-wap to get length if given input string
-it also consist only one astract method i.e apply()
class Test
{
public static void main)
{
function<String,Integer> f=s->s.lenght();
SOP(f.apply("durga"));
}
}
-Example 2:-
class Student
{
String name;
int marks;
Student(String name,int marks)
{
this.name=name;
this.marks-marks;
}
}
class Test
{
p s v main()
{
Function<Student,String> f=s->{
int marks=s.marks;
String grade="";
if(marks>=80) grade="A";
else if(marks>=60) grade="B";
ELSE if(marks>=50) grade="C";
else if(marks>=30) grade="D";
else grade=-"E"
return grade;
};
Student[] s ={ new Student ("durga"),80),new Student ("vishal"),70),
new Student ("samadan"),43),
new Student ("harshal"),15)
};
for(Student s1 : s)
{
SOP("student Name:"+s1.name);
SOP("student marks:"+s1.marks);
SOP("student grade:"+f.apply(s1));
}
}
}

Function chaining:-this can we achived by provided two methods


1).andThen()
2).compose()

...................................................................................
................

3)Consumer<T> :-this functional interface takes input, performs several operation


and doesnt return anything(void)
-it also consist one abstract method i.e accept()
-it can be used for printing purpose
-consumer chaining is alos possible. consumer also have .andthen() for chaining
(for prog example refer phone ss)
Example:-
---
---
----
Cousumer<Student> c=s1->
{
SOP("student Name:"+s1.name);
SOP("student marks:"+s1.marks);
SOP("student grade:"+f.apply(s1));

}
for(Student s1 : s)
{
c.accept(s1);
}

Example 2:-
class test
{
p s v main()
{
Consumer<Movie> c1=m->SOP(m.name+"ready to release");
Consumer<Movie> c1=m->SOP(m.name+"released but flop");
Consumer<Movie> c1=m->SOP(m.name+"storing into CD");
Consumer<Movie> cc=c1.andThen(c2).andThen(c3); //consumer chaining
Mpovie m = new Movie("Spider");
cc.accept(m);
}
}

.....................................................................

.................................................
Primitives Predicate Types:

1)IntPredicates :-Its always gonna take some one* int value and returns boolean
value
-advatages of this interface is therre will be no internal autoboxing/autounboxing

2)DoublePredicates :-Its always gonna take some one* Double value and returns
boolean value
-advatages of this interface is therre will be no internal autoboxing/autounboxing

3)LongPredicates:-Its always gonna take some one Long value and returns boolean
value
-advatages of this interface is therre will be no internal autoboxing/autounboxing

Primitives Fubction Types:-

1)DoubleFunction : it can take input type as double primitve but return type can be
anytime
-it contains only one method i.e apply() no method chaining methods are available
like andThen etc

2)IntFunction :: it can take input type as int primitve but return type can be
anytime
-it contains only one method i.e apply() no method chaining methods are available
like andThen etc

3)LongFunction :: it can take input type as Long primitve but return type can be
anytype
-it contains only one method i.e apply() no method chaining methods are available
like andThen etc

4)DoubleToIntFunction :-it can take input type as double primitve but return type
is int
-it contains only one method i.e applyAsInt(double value)

5)DoubleToLongFunction :-it can take input type as double primitve but return type
is long
-it contains only one method i.e applyAsInt(double value)

6)IntToDoubleFunction :-it can ake int type as double primitive but return type is
long
-it contains only one method i.s applyAsInt()

7)IntToLongFunction :-

8)LongToIntFunction :-

9)LongToDoubleFunction :-

10)ToIntFunction :-it can take input of any type but it will return int type
-contain int applyAsInt(T value)

11)ToLongFunction :

12)ToDoubleFunction

13)ToIntBiFunction :--it takes two value as input return type must be int type but
input can ne anytype
-contains int apply (T t,U u)

14)ToLongBiFunction :-

15)ToDoubleBiFunction :-

Primitives consumer Types :-

1)IntConsumer :-It accept int value


. It conatains void accept(int value)

2)DoubleConsumer

3)LongConsumer :-

4)ObjDoubleConsumer :-:-it takes one arugument of any type and osecond argument as
double value
-void accept (T t,double value)

5)ObIntConsumer :-

6)ObjLongConsumer:-
Primitives Supplier Types :-

1)BooleanSupplier :-
boolean getAsBoolean()

2)IntSupplier:-
int getAsInt()

3)LongSupplier

4)DoubleSupplier() :-

...................................................................................
...............................
UnaryOprator :-if the input and output is same type then we can use UnaryOpertaor
-it is a child class of function Functional Interface abd has appply(Object) mwthod

IntUnaryOperator :-if the input and output is of int type we can use UnaryOperator
-it contains public int applyAsInt(int)
)
LongUnaryOperator :-

DoubleUnaryOperator :-

...................................................................................
.............
BinaryOperator :-if both inputs and return type is same then go for BinaryOperator
-public T apply(T,T)
-its a child interface of BiFunctonal functional interface

Primitive types of Binary Operator :

1)IntBinaryOperator :-if both input primitive types are same and return tpe is also
same then go for intBinaryOperator
-contains int applyAsInt(int n, int n1);

2)LongBinaryOperator :-

3)DoubleBinaryOperator :-

...................................................................................
.............................

Method and Constructor Reference :-


Method and Constructor Reference (::) :-Functional Interface method(here in e.g
Runnable Interface) can be mapped with our specified method by using :: operator is
called method or constructor referencing
-The biggest advantage is already exising method we are reusing i.e code
reusibility
-Example :-
class Test
{
public static void m1()
{
for(int i=0;i<10;i++)
{
SOP("child thread")
}
}

public static vois main()


{
Runnable r = Test::m1; //Here run() method of Runnable interface referecing to Test
class m1() method

Thread r = new Thread(r);


t.start();
for(int i=0;i<10;i++)
{
SOP("main thread")
}
}
}

Note :-Method and Constructor Reference Are alternative to lamda expression. In


java purpose of :: is method reference or constructor reference
Note***:Here run() method referencing to Test class m1() method
Note :- for reusing static method syntax classname::methodname
Note:-for reusing instance method syntax is objectname::mehodname
Note*****: While mapping Functional Interface method with our existing usable
method we only should take care about that both the methods should have same
argument type. Return type and modifier can be different. if using dufferent
argument type CE:incompatable types

Example 2 :
interface Interf
{
public void add(int a,int b)
}
class Test
{
public static void m1(int x,int y)
{
SOP("the sum:"+(x+y));
}

public static vois main()


{
Interf i1=Test::m1;
i1.add(100,200);
}
}

Note :-if implementation is already available we should go for method reference and
if implementation is not available then go for lamda expression.

...................................................................................
..........................................
Constructur reference :-
class Sample
{
Sample()
{
SOP("sample class constructor Execution");
}
}
Interface Interf
{
public Sample get();
}
class Test
{
p s v main()
{
Interf i=Sample::new;
Samle s1=i.get();
}
}

Note***:-Here we mapped Interf i get() method with Sample class constructor.


basically with concise code we implemented method of interf interface and also
created a object
Note :- here also argument type should be same

...................................................................................
..........................................

Stream :- If we want to process Objects from the collection then we should go for
Stream present in java.util.Stream
-Stream is an inteface present in java.util.stream pkg
-using stream we can process obj inside collection
-Creating Stream by calling steam() method on collection i.e: Stream s = c.stream()
-if we want to filter then we should go for filter() method for e.g like filter
even object or filter odd objects.
-filter() is always based on some boolean condition thats why filter() takes
Predicate as input arg
-if there is a group of object and we have to filter some object then we should go
for filter() method
-map() method means to do some operation and return some results so return type can
to anytype so in takes funtion is input arg
-for every object do some functionality or operation generate a new object then
automatically we should go for map()
-Now after filter and map collect this result to List then we have to use
.collect(Collectors.toList()) method
-count() method is used to count how many object are thier in stream. Return type
is long
-sorted() method is called on stream to sort objects according to default natural
sorting order and returns List of processed object
-sorted(Comparator) ->customized sorting
-sorted()->natural sorting order

-Example:-Desending order using comparator


class Test
{
p s v main()
{
ArrayList<> ,arks = new Array:ist<>();
marks.add(20);
marks.add(30);
marks.add(60);
marks.add(40);
marks.add(50);

List<Integer>
sortedList=marks.stream().sorted((i1,i2)->(i1<i2)?1:(i1>i2)?-1:0).collect(collector
s.ToList())
SOP(sortedList);
}
}

-Example 2:-Desending order using comparable


class Test
{
p s v main()
{
ArrayList<> ,arks = new Array:ist<>();
marks.add(20);
marks.add(30);
marks.add(60);
marks.add(40);
marks.add(50);

List<Integer>
sortedList=marks.stream().sorted((i1,i2)->i2.compare(i1)).collect(collectors.ToList
())
SOP(sortedList);
}
}

.............................
Note***:
(s1,s2)->s1,compareTo(s2)->natural sorting order
(s1,s2)->s2.compare(s1)->recerse of natural sorting order
(s1,s2)->s1.compare(s2)->recerse of natural sorting order
.....................

-Example 3:-sorting of string according to thier length (ascending)


class Test
{
p s v main()
{
ArrayList<> ,arks = new Array:ist<>();
marks.add(""sunny);
marks.add("kalyug");
marks.add("pyaare");
marks.add("misunderstood");
marks.add("hi");
Comparator<> c=(s1,s2)->{
int l1=s1.lenght();
int l2=s2.lenght();
if(i1<i2) return -1;
else if(l1>l2) return +1;
else return s1.compare(s2);
};
List<Integer> sortedList=marks.stream().sorted(c).collect(collectors.ToList())
SOP(sortedList);
}
}

..............................
min() & max() method:-
-
-compulsory we have to pass comparator interface as argument in min &max method or
it will not work
-Example 1:-
class Test
{
p s v main()
{
ArrayList<> marks = new Array:ist<>();
marks.add(20);
marks.add(30);
marks.add(60);
marks.add(40);
marks.add(50);

int min=marks.stream().min((i1,i2)->i2.compare(i1)).get();
//int min will give min value after sorting
sop(min)
int max=marks.stream().max((i1,i2)->i2.compare(i1)).get();
//int max will give max value after sorting(sorting depends on what logic prog. is
using)
SOP(max);
}
}
......................................
forEach :-need to learn 1:51:00 durga stream

.................................................................................
toArray() : to convert stream of objects into Array
-Example 1:-
class Test
{
p s v main()
{
ArrayList<> marks = new Array:ist<>();
marks.add(20);
marks.add(30);
marks.add(60);
marks.add(40);
marks.add(50);
(5)Integer[] i=marks.stream().toArray(Integer[]::new); // this line is example of
constructor reference where Sample::new returned new object of Sample type
for(Integer i1 : i)
{
sop(i1);
}
}
Note : here line 5 is creating new object of Integer[] Array

...................................................................................
........................................
Stream.of() :- to convert Array or group of elements together into stream

Note******: stream concept is not applicable only for collection .it is apllicable
on Array alos.It is applicable for evevry group of elements present together

p s v main()
{
Stream s=Stream.of(9,99,41,85,35,888)
s.forEach(System.out::Println);
}
}

You might also like