Saturday, 10 February 2018

List Interface


List interface::

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iteratoraddremoveequals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.
The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.
The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

ArrayList::
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)
The sizeisEmptygetsetiterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

How to create Arraylist:

public class LstStrm {

public static void main(String args[]) {
         
      //declare both right and left generics in <> in java6
List<String> names=new ArrayList<String>();
names.add("one");
names.add("two");
names.add("three");
names.add("four");
names.add("five");
System.out.println(" display list of elements in java6 ::"+names);

         // in java7you can't declare generics in right side <> ,compiler infers the left hand generic which type it is.
               List<String> names=new ArrayList<>();
names.add("one");
names.add("two");
names.add("three");
names.add("four");
names.add("five");
System.out.println(" display list of elements in java7 ::"+names);
}
}

LinkedList::

Linked list implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface, the LinkedList class provides uniformly named methods to getremove and insert an element at the beginning and end of the list.By using this you can add elements in both forward and backward,also add elements using while iterating elements.

LinkedList<String> namesList=new LinkedList<>();
namesList.add("one");
namesList.add("two");
namesList.add("three");
namesList.add("four");
namesList.add("five");
namesList.addFirst("first");
namesList.addLast("lastele");

System.out.println(" display list of elements in java6 ::"+namesList);


Tuesday, 16 January 2018

Overriding in java


Overriding :: When a method in a sub class has same name, same number of arguments and same type signature as a method in its super class, then the method is known as overridden method. Method overriding is also referred to as runtime polymorphism. The key benefit of overriding is the abitility to define method that's specific to a particular subclass type.


  • The access level cannot be more restrictive than the overridden method’s access level. For example: if the super class method is declared public then the overridding method in the sub class cannot be either private or protected.
  • Instance methods can be overridden only if they are inherited by the subclass.
  • A method declared final cannot be overridden.
  • A method declared static cannot be overridden but can be re-declared.
  • A subclass within the same package as the instance’s superclass can override any superclass method that is not declared private or final.
  • Constructors cannot be overridden.
Example of override method:






output:


When we commnet Base baseSub=new Sub(); and copy below code exceute it will show classcastexception.Sub subBase=(Sub) new Base();
subBase.read();

O/p: 


Private and final methods cannot be overridden.
Can we override staticmethod?  think about it before scrolling down.
When you defines a static method with same signature as a static method in base class, it is known as method hiding.
The following table summarizes what happens when you define a method with the same signature as a method in a super-class.
 SUPERCLASS INSTANCE METHODSUPERCLASS STATIC METHOD
SUBCLASS INSTANCE METHODOverridesGenerates a compile-time error
SUBCLASS STATIC METHODGenerates a compile-time errorHides
Ans:No

in above base class you can add the  static keyword infront of void read method()And trying ot create instance method name(read) in sub  it will displays following error.


in above Sub class you can add the  static keyword infront of void read method()And trying ot create instance method name(read) in Base class it will displays following error.


Method overriding with Exception handling  ::1)If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.

Base class:

public class Base {

Base(){
System.out.println("from base class constructor");
}

public  void read() {
System.out.println("read method from base class");
}

}

Subclass:
public class Sub extends Base {
Sub(){
System.out.println("from Sub class constructor");
}
/*public void read() throws ClassCastException {
System.out.println("read method from Sub class");
}
*/
//it will show Exception IOException is not compatible with throws clause in Base.read()
public void read() throws IOException {
System.out.println("read method from Sub class");
}

public static void main(String args[]) {
Base base=new Base();
base.read();
Sub sub=new Sub();
sub.read();
Base baseSub=new Sub();
//Sub subBase=(Sub) new Base();
baseSub.read();
}

}

you can uncomment above commented lines and commented currently showing exception method.

2)  If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.


public class Base {
public  void read() throws IOException {
System.out.println("read method from base class");
}
}

public class Sub extends Base {
        //it does not throw any exception
public void read() throws EOFException { System.out.println("read method from Sub class"); }
}

public class Sub1 extends Base {
        //it does not throw any exception
public void read()  { System.out.println("read method from Sub class"); }
}

public class Sub2 extends Base {
        //it does throw compilation error as per above rule
public void read() throws Exception { System.out.println("read method from Sub class"); }
}

Sunday, 7 January 2018

Static block vs initialization block


Static Initialization blocks :: This is also referred as “static blocks” or “static initializer”.Static blocks are bundle of valid Java statements within {curly braces} prefixed with static keyword.
syntax: static { //your code goes here}
Static blocks are executed, at the time of class loading.Executed only once, at the time class loading.
Static blocks can be used to initialize static data members and invoke static methods only.
Since static blocks are belongs to class, this and super keywords are not allowed.
Order of execution: Static blocks are always executed first comparing with instance blocks, at the time class loading.

package utlfunc;

public class GraspStatc {

public GraspStatc() {
     System.out.println("from GraspStatc constructor ");
}

static {
System.out.println("from static blcok1");
}
{
System.out.println("from initialization block1");
}
static {
System.out.println("from static blcok2");
}
{
System.out.println("from initialization block2");
}
public static void main(String[] args) {
GraspStatc gs=new GraspStatc();
}


}

order of execution of blocks in class: 1)while classloading static block will execute first.
2) Second initialization block will execute.
3)constructor will execute.

Output:



Inheritance hierarchy::

SubClass as above example.Super class below

package utlfunc;

public class SubStatcInit {
public SubStatcInit() {
System.out.println(" From SubStatcInit() constructor");
}
static {
System.out.println("from static blcok1 from SubStatcInit");
}
{
System.out.println("from initialization block1 from SubStatcInit");
}
static {
System.out.println("from static blcok2 from SubStatcInit");
}
{
System.out.println("from initialization block2 from SubStatcInit");
}

}

Output::


Saturday, 6 January 2018

Function interface in util package


Function Interface::
Represents a function that accepts one argument and produces a result.
This is a functional interface whose functional method is apply(Object).

BiFunction<T,U,R>
Represents a function that accepts two arguments and produces a result. This is the two-arity specialization of Function.
This is a functional interface whose functional method is apply(Object, Object).

Please refer below link for more inforamation:
https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html



package utlfunc;

import java.util.function.BiFunction;
import java.util.function.DoubleFunction;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.LongFunction;

public class GraspFucnIntrface {

public static void main(String[] args) {

Function<Integer, Integer> fnction=(x)->checkInt(x);
System.out.println("Function:: checkInt() " + fnction.apply(6));

Function<Integer, Integer> fnctionExp=(x)-> {return x;};
fnctionExp.andThen(fnction).apply(8);

BiFunction<String, Integer,Boolean> biFucntion=(x,y)->checkStiringEmpty(x, y);
System.out.println("from BIFUNCTION() ::checkStiringEmpty():" + biFucntion.apply("functioninterface", 12));

IntFunction<Integer> fnctionInt=(x)->checkInt(x);
System.out.println("Function:: checkInt() " + fnctionInt.apply(6));
   
LongFunction<Long> fnctionLng=(x)->checkLng(x);
System.out.println("Function:: checkLng() " + fnctionLng.apply(6l));

DoubleFunction<Double> fnctionDbl=(x)->checkDbl(x);
System.out.println("Function:: checkLng() " + fnctionDbl.apply(6.0));
}
    
public static boolean checkStiringEmpty(String check,int b) {
return check.length()>0 && b>0?true:false;
}
public static int checkInt(int b) {
return b;
}
public static Long checkLng(long b) {
return b;
}
public static Double checkDbl(Double b) {
return b;
}
}

Output ::



Supplier functional interface



Supplier Functional interface:Represents a supplier of results.
There is no requirement that a new or distinct result be returned each time the supplier is invoked.This is a functional interface whose functional method is get().

please refer below link for more inforamation:
https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html


import java.util.function.DoubleSupplier;
import java.util.function.IntSupplier;
import java.util.function.LongSupplier;
import java.util.function.Supplier;

public class GasapSuplier {

public static void main(String[] args) {
 
Supplier<String> splier=()->{ return display("from supplier");};
System.out.println("suign get() from supplier inteface" +splier.get());
IntSupplier splierInt=()->{return displayWihtInt(345);};
splierInt.getAsInt();
DoubleSupplier splierDble=()->{return displayWihtDble(345.00);};
splierDble.getAsDouble();
LongSupplier splierLng=()->{return displayWihtLng(345l);};
splierLng.getAsLong();
}

public static String display(String message) {
System.out.println(" dislayign messgae from ::display() "  + message);
return message;
}

public static int displayWihtInt(int abc) {
System.out.println(" dislayign messgae from ::displayWihtInt() "  +  abc);
return abc;
}
public static double displayWihtDble(double abc) {
System.out.println(" dislayign messgae from ::displayWihtDble() "  +  abc);
return abc;
}
   public static Long displayWihtLng(Long abc) {
System.out.println(" dislayign messgae from ::displayWihtLng()" + abc);
return abc;
}
}

Output: 


Predicate Interface


Predicate interface : 
Represents a predicate (boolean-valued function) of one argument.This is a functional interface whose functional method is test(Object).

please refer below link for more inforamation:
https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html

package utlfunc;

import java.util.function.BiPredicate;
import java.util.function.IntPredicate;
import java.util.function.LongPredicate;
import java.util.function.Predicate;

public class GraspPrdicate {

public static void main(String[] args) {
 
Predicate<String> prdcate= (check)->checkStiringEmpty(check);
System.out.println(prdcate.test("from predicate"));
BiPredicate<String , Integer> biPrdcate=(a,c)->checkStiringEmpty(a, c);
System.out.println(biPrdcate.test(" from Bipredicaate", 345));
BiPredicate<Integer,Integer> expBiPrdcate=(x,y)->x>y;
BiPredicate<Integer,Integer> expOnePrdcate=(x,y)->x-2>y;
System.out.println(expBiPrdcate.and(expOnePrdcate).test(10, 5));
System.out.println(expBiPrdcate.or(expOnePrdcate).test(6,7));
IntPredicate prdcateInt=(x)->checkInt(x);
prdcateInt.test(234);
IntPredicate prdciateTest=(y)->y>1;
System.out.println(prdciateTest.test(21));

System.out.println(prdciateTest.and(prdcateInt).test(23));
System.out.println(prdciateTest.or(prdcateInt).test(23));

LongPredicate lngPrdcate=(y)->checkLng(y);
System.out.println(lngPrdcate.test(21l));

}
public static boolean checkStiringEmpty(String check) {
return check.length()>0?true:false;
}

public static boolean checkStiringEmpty(String check,int b) {
return check.length()>0 && b>0?true:false;
}

public static boolean checkInt(int a) {
return a>0?true:false;
}

public static boolean checkLng(Long a) {
return a>0?true:false;
}
}


Lambda Expressions

Java8:Lambda Expressions

What is lambda expression:
A lambda expression is an unnamed block of code (or an unnamed function) with a list of formal parameters and abody. Sometimes a lambda expression is simply called a lambda. The body of a lambda expression can be a block statement or an expression. An arrow (->) is used to separate the list of parameters and the body. The term “lambda” in "lambda expression" has its origin in Lambda calculus that uses the Greek letter lambda (l) to denote a function abstraction.

Exmaples of lambda expressions:
// Takes an int parameter and returns the parameter value incremented by 1
(int x) -> x + 1

// Takes two int parameters and returns their sum
(int x, int y) -> x + y

// Takes two int parameters and returns the maximum of the two
(int x, int y) -> { int max = x > y ? x : y;
return max;
}

// Takes no parameters and returns a string "OK"
() -> "OK"
// Takes a String parameter and prints it on the standard output
(String msg) -> { System.out.println(msg); }
// Takes a parameter and prints it on the standard output
msg -> System.out.println(msg)
// Takes a String parameter and returns its length
(String str) -> str.length()

// Takes no parameters and returns void

() -> { }

Syntax of lambda expressions:: 
A lambda expression describes an anonymous function. The general syntax for using lambda expressions is very similar to declaring a method.
  The general syntax is (<LambdaParametersList>) -> { <LambdaBody> }

A lambda expression consists of a list of parameters and a body that are separated by an arrow (->). The list of parameters is declared the same way as the list of parameters for methods. The list of parameters is enclosed in parentheses, as is done for methods. The body of a lambda expression is a block of code enclosed in braces. Like a method's body, the body of a lambda expression may declare local variables; use statements including break, continue, and return; throw exceptions, etc.

Omitting Parameter Types ::
You can omit the declared type of the parameters. The compiler will infer the types of parameters from the context in which the lambda expression is used.
// Types of parameters are declared
(int x, int y) -> { return x + y; }
// Types of parameters are omitted
(x, y) -> { return x + y; }
If you omit the types of parameters, you must omit it for all parameters or for none. You cannot omit for some and not for others. The following lambda expression will not compile because it declares the type of one parameter and omits for the other:
// A compile-time error

(int x, y) -> { return x + y; }

Declaring a Single Parameter ::
Sometimes a lambda expression takes only one parameter. You can omit the parameter type for a single parameter lambda expression as you can do for a lambda expression with multiple parameters. You can also omit the parentheses if you omit the parameter type in a single parameter lambda expression. The following are three ways to declare a lambda expression with a single parameter:
// Declares the parameter type
(String msg) -> { System.out.println(msg); }
// Omits the parameter type
(msg) -> { System.out.println(msg); }
// Omits the parameter type and parentheses
msg -> { System.out.println(msg); }
The parentheses can be omitted only if the single parameter also omits its type. The following lambda expression
will not compile:
// Omits parentheses, but not the parameter type, which is not allowed.
String msg -> { System.out.println(msg); }

Declaring No Parameters ::
If a lambda expression does not take any parameters, you need to use empty parentheses.
// Takes no parameters
() -> { System.out.println("Hello"); }
It is not allowed to omit the parentheses when the lambda expression takes no parameter. The following declaration will not compile:
-> { System.out.println("Hello"); }

Parameters with Modifiers :
You can use modifiers, such as final, in the parameter declaration for explicit lambda expressions. The following two lambda expressions are valid:
(final int x, final int y) -> { return x + y; }
(int x, final int y) -> { return x + y; }

The following lambda expression will not compile because it uses the final modifier in parameter declarations,but omits the parameter type:
(final x, final y) -> { return x + y; }

Declaring Body of Lambda Expressions :
The body of a lambda expression can be a block statement or a single expression. A block statement is enclosed in braces; a single expression is not enclosed in braces.When a block statement is executed the same way as a method’s body. A return statement or the end of the body returns the control to the caller of the lambda expression.When an expression is used as the body, it is evaluated and returned to the caller. If the expression evaluates to void, nothing is returned to the caller.
The following two lambda expressions are the same; one uses a block statement and the other an expression:
// Uses a block statement. Takes two int parameters and returns their sum.
(int x, int y) -> { return x + y; }
// Uses an expression. Takes a two int parameters and returns their sum.
(int x, int y) -> x + y
The following two lambda expressions are the same; one uses a block statement as the body and the other an expression that evaluates to void:
// Uses a block statement
(String msg) -> { System.out.println(msg); }
// Uses an expression

(String msg) -> System.out.println(msg)

Commonly Used Functional Interfaces :
Java 8 has added many frequently used functional interfaces in the package java.util.function.

List of Functional Interfaces Declared in the Package java.util.function
Interface Name Method Description
Function<T,R> R apply(T t) Represents a function that takes an argument of type T

and returns a result of type R.

BiFunction<T,U,R> R apply(T t, U u) :Represents a function that takes two arguments of types T
and U, and returns a result of type R.

Predicate<T> boolean test(T t) In mathematics, a predicate is a boolean-valued function
that takes an argument and returns true or false. The function represents a condition that returns true or false for the specified argument.

BiPredicate<T,U> boolean test(T t, U u) Represents a predicate with two arguments.

Consumer<T> void accept(T t) Represents an operation that takes an argument, operates on it to produce some side effects, and returns no result.
BiConsumer<T,U> void accept(T t, U u) Represents an operation that takes two arguments,
operates on them to produce some side effects, and returns no result.

Supplier<T> T get() Represents a supplier that returns a value.

UnaryOperator<T> T apply(T t) Inherits from Function<T,T>. Represents a function that takes an argument and returns a result of the same type.
BinaryOperator<T> T apply(T t1, T t2) Inherits from BiFunction<T,T,T>. Represents a function
that takes two arguments of the same type and returns a result of the same.

Consumer functional interface:
Let take example of consumer  functional interface.

import java.util.function.BiConsumer;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
import java.util.function.Predicate;

public class GraspUtlFuncInterface {

public static void main(String[] args) {

//using java.util.function package using java8
Consumer<String> cnsmer=( s) ->display(s);
cnsmer.accept(" from consumer");

BiConsumer<String,Integer> biCnsmer=( s,a) ->displayWihtTwoargs(s,a);
biCnsmer.accept(" from biConsumer", 23);

Predicate<String> prdcate= (check)->checkStiringEmpty(check);
System.out.println(prdcate.test("from predicate"));
BiPredicate<String , Integer> biPrdcate=(a,c)->checkStiringEmpty(a, c);
System.out.println(biPrdcate.test(" from Bipredicaate", 345));
BiPredicate<Integer,Integer> expBiPrdcate=(x,y)->x>y;
BiPredicate<Integer,Integer> expOnePrdcate=(x,y)->x-2>y;
System.out.println(expBiPrdcate.and(expOnePrdcate).test(10, 5));
System.out.println(expBiPrdcate.or(expOnePrdcate).test(6,7));

IntConsumer intCnsmer=(a)->displayWihtInt(a);
intCnsmer.accept(12345);
DoubleConsumer dbCnsmer=(a)->displayWihtDble(a);
dbCnsmer.accept(123.00);
LongConsumer lngCnsmer=(a)->displayWihtLng(a);
lngCnsmer.accept(124l);

}

public static void display(String message) {
System.out.println(" dislayign messgae from ::display()" + message);
}

public static void displayWihtTwoargs(String message,int number) {
System.out.println(" dislayign messgae from ::displayWihtTwoargs()" + message + "  "+number);
}

public static boolean checkStiringEmpty(String check) {
return check.length()>0?true:false;
}

   public static boolean checkStiringEmpty(String check,int b) {
return check.length()>0 && b>0?true:false;
}
 
   public static void displayWihtInt(int abc) {
System.out.println(" dislayign messgae from ::displayWihtInt()" + abc);
}
 
   public static void displayWihtDble(double abc) {
System.out.println(" dislayign messgae from ::displayWihtDble()" + abc);
}
   public static void displayWihtLng(Long abc) {
System.out.println(" dislayign messgae from ::displayWihtLng()" + abc);
}
}

Output: