Monday 3 April 2017

Some important points of Abstract class


Some important points of Abstract class-

- We can't create the object of abstract class but abstract class have constructor.
- Abstract class constructor is called via super() call from child class constructor.
- Abstract class does not allow abstract method static. if you does it's abstract method static then compiler gives you compilation error message - 
     illegal combination of modifiers: 'abstract' and 'static' .
- We can apply static with non-abstract method inside Abstract class.

public class AbstarctionDemo extends  MarketChoice{
public AbstarctionDemo(String[] productName) {
super(productName);
// TODO Auto-generated constructor stub
}

public static void main(String[] args) {
// TODO Auto-generated method stub
        String[] productName= {"mouse","keyboard","desktop","cpu","speaker"};
MarketChoice marketChoice= new AbstarctionDemo(productName);
marketChoice.getDetails();
}

@Override
public void getMarketDetails() {
// TODO Auto-generated method stub
//marketChoice
}
}


abstract class MarketChoice {

protected String[] pName;
//Abstract class constructor  
public MarketChoice(String[] name){
pName=name;
}
public abstract void getMarketDetails();
 void getDetails(){
for (String string: pName) {
System.out.println(string);
}

}

Sunday 2 April 2017

Important features of java 8


Some important features of java 8 are listed below-

  • forEach() method in Iterable interface
  • default and static methods in Interfaces
  • Lambda Expressions
  • Java Time API
  • Java Stream API for Bulk Data Operations on Collections


1. forEach using Map and List interface

EXAMPLE-

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Java8Feature {

public static void main(String[] args) {
// TODO Auto-generated method stub
Java8Feature obj = new Java8Feature();
System.out.println("*** forEach with Map ***");
obj.myMapIterator();
System.out.println("*** forEach with List ***");
obj.myListIterator();
}

void myMapIterator() {
Map<String, Integer> items = new HashMap<>();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);

//1. Filter map using normal way
for (Map.Entry<String, Integer> entry : items.entrySet()) {
System.out.println("Item : " + entry.getKey() +" Count : "+ entry.getValue());
}

//2. Filter map using Lambda expression
items.forEach((k, v) -> System.out.println("Item : " +k +" Count : " + v));

//3. Filter map using Lambda expression
items.forEach((k, v) -> {
System.out.println("Item : " + k +" Count : " + v);
if ("E".equals(k)) {
System.out.println("Hello E");
}
});
}

void myListIterator() {
List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");

//1. Filter list using normal way
for (String string : items) {
System.out.println("Item : " + string);
}

//2. Filter list using Lambda expression
items.forEach(sanjay -> System.out.println(sanjay));

//3. Filter list using Lambda expression
items.forEach(aaa -> {
if ("C".equals(aaa)) {
System.out.println("Lambda expression");
}
});
//4. Filter using method reference 
items.forEach(System.out::print);   
              // Work like below 
              //items.forEach(i-> System.out.println(i));

//5. Stream and filter
items.stream()
.filter(s->s.contains("B"))
.forEach(System.out::println);
}
}

2. default and static methods in Interfaces


default method of java 8 gives a flexibility to modify or add new upcoming feature in future on existing interface. default method does not effect to all other implementer classes if something is changed on default method, because default method is optional for exiting implementer classes to use default method even not need to override it by all implementer classes.

default method does not create ambiguity if 2 interface having same default method name. its is accessed via interface name.

EXAMPLE-


public class Java8InterfaceDefaultMethod implements IConsumerUpdate ,IMarketProduct ,IMarketInventry{

public static void main(String[] args) {
// TODO Auto-generated method stub
Java8InterfaceDefaultMethod obj = new                                                                    Java8InterfaceDefaultMethod();
int saleCount = obj.getProductSaleCount(10);
System.out.println("Product sale count : " + saleCount);

String pName = obj.getProductName();
System.out.println("Product Name : " + pName);
obj.getConsumer();
String pQuality=IMarketProduct.getProductQuality();
System.out.println("product quality : " +pQuality);
}

@Override
public int getProductSaleCount(int saleCount) {
// TODO Auto-generated method stub
return saleCount;
}

@Override
public int getInventryCount() {
// TODO Auto-generated method stub
return 0;
}

interface IMarketProduct {
String productName = "MacBook pro";
String productQuality = "Normal";
int getProductSaleCount(int count);

default String getProduct() {
return productName;
}
static String getProductQuality() {
return productQuality;
}
}

interface IMarketInventry {
String name = "Windows laptop";

int getInventryCount();

default String getProductName() {
return name;
}
}

interface IConsumerUpdate {

default void getConsumer() {
System.out.println("I am Consumer");
}

}

3. Lambda Expressions


public class ThreadEvenOdd {

    int inputNum=13;

public ThreadEvenOdd(int a) {
super();
this.inputNum = a;
}

public static boolean checkPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return true;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
int inputNumber=13;
ThreadEvenOdd obj = new ThreadEvenOdd(inputNumber);

/**
* Using Lambda expression introduced in java 8
*/
Runnable runnable = () -> {
// TODO Auto-generated method stub
for (int i = 0; i < obj.inputNum; i++) {
try {
if (i % 2 == 0) {
   System.out.println("Even nuber is: " + i);
}
Thread.sleep(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

};
/**
* using java 7
*/
Runnable runnable2 = new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < obj.inputNum; i++) {
try {
if (i % 2 != 0) {
System.out.println("odd nuber is: " + i);
}
Thread.sleep(0);
} catch (Exception e) {
e.getMessage();
}
}
}
};

/**
*  Using Lambda expression introduced in java 8
*/
Runnable runnable3 = () -> {
// TODO Auto-generated method stub
for (int i = 2; i < obj.inputNum; i++) {
if (checkPrime(i)) {
System.out.println("Prime number " + i);
}
}

};
Thread t = new Thread(runnable);
Thread t1 = new Thread(runnable2);
Thread t2 = new Thread(runnable3);
t.start();
t1.start();
t2.start();
}


}

Monday 27 March 2017

Important features of java 7

There are a number of features in Java 7. 
Some of them are listed below-
  • diamond operator
  • strings in switch statements, 
  • multi-catch exception handling, 
 1. Diamond operator
// Old
way-

Map<String, List<Moments>> momentsList = new HashMap<String, List<Moments>>();


//New way-

Map<String, List<Moments>> momentsList = new HashMap<>();

2. Strings in switch statements

// Old way-

private void Show(Profile p) {
String status = p.getStatus();
if (status.equalsIgnoreCase(NEW)) {
newProfile(p);
} else if (status.equalsIgnoreCase(OLD)) {
validateProfile(p);
} else if (status.equalsIgnoreCase(PENDING)) {
pendingProfile(p);
}
}
// New Way-

private void Show(Profile p){
    String status = p.getStatus();
    switch(status) {
        caseNEW:
        newProfile(p);
        break;
        caseOLD:
        validateProfile(p);
        break;
        casePENDING:
        pendingProfile(p);
        break;
        default:
            break;
    }

}

3. Exception handling

// Old-
public void oldMultiCatch() {
try {
methodThrowsThreeExceptions();
} catch (Exception1 e) {
// e.getMessage();
} catch (Exception2 e) {
// e.getMessage();
} catch (Exception3 e) {
// e.getMessage();
}
}
// New-

public void newMultiCatch() {
try {
methodThrowsThreeExceptions();
} catch (Exception1 | Exception2 | Exception3 e) {
// log all Exceptions
// e.getMessage();

}
}

4. multi multi-catch

public void multiMultiCatch() {
  try{ 
   methodThrowsThreeExceptions(); 
  } catch(Exception1 e) { 
   // e.getMessage(); 
  } catch(Exception2 | Exception3 e) { 
   // log all Exceptions
   //e.getMessage(); 
   } 
}

Monday 9 January 2017

Difference between Set, List and Map java Collections


      Set (Interface)

  • Set is an un-ordered collection which doesn’t allows duplicate (no-duplicate) elements
  • We can iterate the values by calling iterator() method
    Set set=new HashSet();
    Iterator iter = set.iterator();
    List (Interface)

  • List is an ordered collection which allows duplicate elements
  • We can iterate the values by calling iterator() method
    List list = new ArrayList();
    Iterator iter = list.iterator();
    Map (Interface)

  • In Map we used to store the data in key and value pairs, we may have duplicate values but no duplicate keys
    In Map we don’t have iterator() method, but we can get the keys by calling the method keySet()
    Map m; // insert values
    Set s = m.keySet();
    // Get Map keys into the Set and then iterate this Set object normally
    // m.keySet() returns Set object with Map keys
    Iterator iter = s.iterator();