Sunday, October 23, 2016

JSON

Jackson

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;


ObjectMapper objectMapper = new ObjectMapper();
Car car = new Car();
car.brand = "BMW";
car.doors = 4;
String json = objectMapper.writeValueAsString(car);
System.out.println(json)


      String json = "{\n" +
                "    \"name\": \"Garima\",\n" +
                "    \"surname\": \"Joshi\",\n" +
                "    \"phone\": 9832734651}";
 User garima = new ObjectMapper().readValue(json, User.class);


jackson-xc-1.9.11.jar
jackson-core-asl-1.9.11.jar
jackson-mapper-asl-1.9.11.jar

String carJson =        "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
ObjectMapper objectMapper = new ObjectMapper();
 JsonNode node = objectMapper.readValue(carJson, JsonNode.class);


ObjectMapper objectMapper = new ObjectMapper();
File file = new File("data/car.json");
Car car = objectMapper.readValue(file, Car.class);

ObjectMapper objectMapper = new ObjectMapper();
URL url = new URL("file:data/car.json");
Car car = objectMapper.readValue(url, Car.class);


ObjectMapper objectMapper = new ObjectMapper();
InputStream input = new FileInputStream("data/car.json");
Car car = objectMapper.readValue(input, Car.class);


String carJson =
        "{ \"brand\" : \"Mercedes\", \"doors\" : 5," +
        "  \"owners\" : [\"John\", \"Jack\", \"Jill\"]," +
        "  \"nestedObject\" : { \"field\" : \"value\" } }";
ObjectMapper objectMapper = new ObjectMapper();
try {

    JsonNode node = objectMapper.readValue(carJson, JsonNode.class);

    JsonNode brandNode = node.get("brand");
    String brand = brandNode.asText();
    System.out.println("brand = " + brand);

    JsonNode doorsNode = node.get("doors");
    int doors = doorsNode.asInt();
    System.out.println("doors = " + doors);

    JsonNode array = node.get("owners");
    JsonNode jsonNode = array.get(0);
    String john = jsonNode.asText();
    System.out.println("john  = " + john);

    JsonNode child = node.get("nestedObject");
    JsonNode childField = child.get("field");
    String field = childField.asText();
    System.out.println("field = " + field);

} catch (IOException e) {
    e.printStackTrace();
}


GSON

Sunday, October 16, 2016

Java 8

   lambda expression is a function:

  (parameters) -> expression
or
    (parameters) -> { statements; }


1. (int x, int y) -> x + y                          // takes two integers and returns their sum

2. (x, y) -> x - y                                  // takes two numbers and returns their difference

3. () -> 42                                         // takes no values and returns 42

4. (String s) -> System.out.println(s)            
// takes a string, prints its value to the console, and returns nothing

5. x -> 2 * x                                       // takes a number and returns the result of doubling it

6. c -> { int s = c.size(); c.clear(); return s; }  // takes a collection, clears it, and returns its previous size

Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method 'compareTo' is used for comparison purpose. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions.

IntOperation is  a functional interface since it contain single method.

interface IntOperation { int operate(int i); }

 IntOperation iop = x -> x * 2;  
  System.out.println(iop.operate(5));

 class Bar { int i; Foo foo = i -> i * 2; }; //member variable - leagal

   void bar() { int i; Foo foo = i -> i * 2; }; // local variable Illegal: variable i is already defined


UnaryOperator factorial = i -> i == 0 ? 1 : i * factorial.apply( i - 1 );


   Runnable r = () -> {System.out.println("Hello World");};  
   new Thread(r).start();  

Referance : (::)
1. static method referance (Type :: Method Name)
2.instant method referance (Type :: Method Name)
2. construtor method referance (Type :: New)


Method references are handles to such existing methods.

String::valueOf
Integer::compare

ReferenceType::Identifier

Constructor references are created using syntax similar to that for method references, but with the method name replaced with the keyword new

     List strList = Arrays.asList("1","2","3");
    List intList = strList.stream().map(Integer::new).collect(Collectors.toList());
         System.out.println(intList);


Default Methods ::

declare concrete methods in the form of default implementations.

public interface Sized {
        public default boolean isEmpty() {
            return size() == 0;
        }
        public int size();
    }
 
most specific default-providing interface is selected. 
 interface A{  public default boolean isEmpty() { return true;  }  }
 interface B{ public default boolean isEmpty() { return true;  }  }
 public class HelloWorld implements A,B-> //Compilation Error


  interface A { default void hello() { System.out.println("Hello World from A"); }}
     interface B extends A { default void hello() { System.out.println("Hello World from B"); } //Override Here - since its most specific  }
public class HelloWorld implements B,A{ No Compilation error // B will be printed

Diamond problem // - No Compilation Error
 interface A { default void m() {} ;}
    interface B extends A {}
    interface C extends A {}
    public class HelloWorld implements B,C{


 interface A { default void m() {} ;}
    interface B extends A { default void m() {} ; }
    interface C extends A { default void m() {} ; }
    public class HelloWorld implements B,C{  // Compilation Error


 interface A { default void m() {} ;}
    interface B extends A { }
    interface C extends A { default void m() {} ; }
    public class HelloWorld implements B,C{    //No Compilation Error


 interface A { default void m() {} ;}
    interface B extends A { default void m() {} ; }
    interface C extends A { }
    public class HelloWorld implements B,C{ // No - Compilation Error


 interface A {default void m() { System.out.println("hello from A"); } }
 IntStream.range(0, 5(Count)).forEach(i -> A.m());  // 5 times m method will be printed


void repeat(int count, Runnable action) {
    IntStream.range(0, count).forEach(i -> action.run());
}
repeat(3, () -> System.out.println("Hello!"));


List list = new ArrayList<>();
iterator.forEachRemaining(list::add);

A stream is a sequence of values. The package java.util.stream


filter Predicate T ➞ boolean Stream stream containing input elements that satisfy the Predicate

map Function T ➞ R Stream stream of values, the result of applying the Function to each input element

sorted Comparator (T, T) ➞ int Stream stream containing the input elements, sorted by the Comparator

limit, skip Stream stream including only (resp. skipping) first n input elements
sample eager/terminal operations

reduce BinaryOperator (T, T) ➞ T Optional result of reduction of input elements (if any) using supplied BinaryOperator

findFirst Predicate T ➞ boolean Optional first input element satisfying Predicate (if any)

forEach Consumer T ➞ void void void, but applies the method of supplied Consumer to every input element

Saturday, October 15, 2016

Equals vs ==

1. == Is used to compare reference and equals is used to compare the contents.

2. == We can used with primitive type, when we used == with primitive types(data types) it will work as comparing two values. But equals we can not used for primitives type as it is method declared in object class. In short all the classes in java having own equals method.

3. If we call equals on reference variable who have null value, then we will get nullpointerexception.
Example
String s;
S.equals("Abc")
It will throw nullpointerexception.

4. Equals is a method which is in object class. Object class is extended by all the classes in java. So in short equals method is contained by all the classes in java.

Reflection method call

public class A
{
  private A(){
       System.out.println("This is A");
   }
}   ..........................................................................................................................import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;                                                                                                   public class Main {

public static void main(String[] args)

{
try
{
Class a = A.class;

Constructor c = a.getDeclaredConstructor((Class[])null);
c.setAccessible(true);
A obj = c.newInstance((Object[])null);

Method privateMethod = a.getDeclaredMethod("obj", (Class[])null);
privateMethod.setAccessible(true);
privateMethod.invoke(obj, (Object[])null);
}catch(Exception ex){
    ex.getMessage();
}
}

}

Friday, October 14, 2016

Up-Casting(Super Type Casting) vs Down Casting(SubType Casting)

Up-casting is casting to a supertype, while downcasting is casting to a subtype. Supercasting is always allowed, but subcasting involves a type check and can throw a ClassCastException.

In your case, a cast from from Dog to an Animal is a upcast, because a Dog is-a Animal. In general, you can upcast whenever there is an is-a relationship between two classes.

Downcasting would be something like this:

Animal animal = new Dog();
Dog castedDog = (Dog) animal;


HashMap Collision

public class Simple{
public static void main(String args[]){
Map map=new HashMap();
map.put(1, 11);
map.put(4, 11);
System.out.println(map.hashCode());
Map map1=new HashMap();
map1.put(1, 11);
map1.put(4, 11);
System.out.println(map1.hashCode());
if (map.equals(map1)) {
    System.out.println("equal ");
}
}}


25
25
equal 


rules for overriding


Rule #1: Only inherited methods can be overridden.

Rule #2: Final and static methods cannot be overridden.

Rule #3: The overriding method must have same argument list

Rule #4: The overriding method must have same return type (or subtype).

Rule #5: The overriding method must not have more restrictive access modifier.

Rule #6: The overriding method must not throw new or broader checked exceptions.

Rule #7: Use the super keyword to invoke the overridden method from a subclass

Rule #8: Constructors cannot be overridden.

Rule #10: A static method in a subclass may hide another static one in a superclass, and that’s called hiding.

Rule #11: The synchronized modifier has no effect on the rules of overriding.

Rule #12: The strictfp modifier has no effect on the rules of overriding.

Junit Annotations

Here’re some basic JUnit annotations you should understand:
  1. @BeforeClass – Run once before any of the test methods in the class, public static void
  2. @AfterClass – Run once after all the tests in the class have been run, public static void
  3. @Before – Run before @Test, public void
  4. @After – Run after @Test, public void
  5. @Test – This is the test method to run, public void

import org.junit.*;

public class BasicAnnotationTest {

    // Run once, e.g. Database connection, connection pool
    @BeforeClass
    public static void runOnceBeforeClass() {
        System.out.println("@BeforeClass - runOnceBeforeClass");
    }

    // Run once, e.g close connection, cleanup
    @AfterClass
    public static void runOnceAfterClass() {
        System.out.println("@AfterClass - runOnceAfterClass");
    }

    // Should rename to @BeforeTestMethod
    // e.g. Creating an similar object and share for all @Test
    @Before
    public void runBeforeTestMethod() {
        System.out.println("@Before - runBeforeTestMethod");
    }

    // Should rename to @AfterTestMethod
    @After
    public void runAfterTestMethod() {
        System.out.println("@After - runAfterTestMethod");
    }

    @Test
    public void test_method_1() {
        System.out.println("@Test - test_method_1");
    }

    @Test
    public void test_method_2() {
        System.out.println("@Test - test_method_2");
    }

}

@BeforeClass - runOnceBeforeClass

@Before - runBeforeTestMethod
@Test - test_method_1
@After - runAfterTestMethod

@Before - runBeforeTestMethod
@Test - test_method_2
@After - runAfterTestMethod

@AfterClass - runOnceAfterClass

Monday, October 10, 2016

Enum - Constant Class

Enum in java is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The java enum constants are static and final implicitly. It is available from JDK 1.5.

Java Enums can be thought of as classes that have fixed set of constants.

Points to remember for Java Enum

enum improves type safety
enum can be easily used in switch
enum can be traversed
enum can have fields, constructors and methods
enum may implement many interfaces but cannot extend any class because it internally extends Enum class

class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }
 
public static void main(String[] args) {
for (Season s : Season.values())
System.out.println(s);
 
}}


Java enum example: defined outside class
enum Season { WINTER, SPRING, SUMMER, FALL }
class EnumExample2{
public static void main(String[] args) {
Season s=Season.WINTER;
System.out.println(s);
}}  


Java enum example: defined inside class
class EnumExample3{
enum Season { WINTER, SPRING, SUMMER, FALL; }//semicolon(;) is optional here
public static void main(String[] args) {
Season s=Season.WINTER;//enum type is required to access WINTER
System.out.println(s);
}}


Initializing specific values to the enum constants
The enum constants have initial value that starts from 0, 1, 2, 3 and so on. But we can initialize the specific value to the enum constants by defining fields and constructors. As specified earlier, Enum can have fields, constructors and methods.

class EnumExample4{
enum Season{  
WINTER(5), SPRING(10), SUMMER(15), FALL(20);  
 
private int value;
private Season(int value){
this.value=value;
}
}
public static void main(String args[]){
for (Season s : Season.values())
System.out.println(s+" "+s.value);
 
}}

Constructor of enum type is private. If you don't declare private compiler internally creates private constructor.

class EnumExample5{
enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}
public static void main(String args[]){
Day day=Day.MONDAY;
 
switch(day){
case SUNDAY:  
 System.out.println("sunday");
 break;
case MONDAY:  
 System.out.println("monday");
 break;
default:
System.out.println("other day");
}

}}

Nested Interface

interface Showable{
  void show();
  interface Message{
   void msg();
  }
}
class TestNestedInterface1 implements Showable.Message{
 public void msg(){System.out.println("Hello nested interface");}
 
 public static void main(String args[]){
  Showable.Message message=new TestNestedInterface1();//upcasting here
  message.msg();
 }
}

class A{
  interface Message{
   void msg();
  }
}
 
class TestNestedInterface2 implements A.Message{
 public void msg(){System.out.println("Hello nested interface");}
 
 public static void main(String args[]){
  A.Message message=new TestNestedInterface2();//upcasting here
  message.msg();
 }
}


next →← prev
Java Nested Interface

An interface i.e. declared within another interface or class is known as nested interface. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface must be referred by the outer interface or class. It can't be accessed directly.

Points to remember for nested interfaces

There are given some points that should be remembered by the java programmer.

Nested interface must be public if it is declared inside the interface but it can have any access modifier if declared within the class.
Nested interfaces are declared static implicitely.
Syntax of nested interface which is declared within the interface

interface interface_name{
 ...
 interface nested_interface_name{
  ...
 }
}  
Syntax of nested interface which is declared within the class

class class_name{
 ...
 interface nested_interface_name{
  ...
 }
}  


Example of nested interface which is declared within the interface

In this example, we are going to learn how to declare the nested interface and how we can access it.
interface Showable{
  void show();
  interface Message{
   void msg();
  }
}
class TestNestedInterface1 implements Showable.Message{
 public void msg(){System.out.println("Hello nested interface");}
 
 public static void main(String args[]){
  Showable.Message message=new TestNestedInterface1();//upcasting here
  message.msg();
 }
}
Test it Now
download the example of nested interface
Output:hello nested interface
As you can see in the above example, we are acessing the Message interface by its outer interface Showable because it cannot be accessed directly. It is just like almirah inside the room, we cannot access the almirah directly because we must enter the room first. In collection frameword, sun microsystem has provided a nested interface Entry. Entry is the subinterface of Map i.e. accessed by Map.Entry.
Internal code generated by the java compiler for nested interface Message

The java compiler internally creates public and static interface as displayed below:.
public static interface Showable$Message
{
  public abstract void msg();
}
Example of nested interface which is declared within the class

Let's see how can we define an interface inside the class and how can we access it.
class A{
  interface Message{
   void msg();
  }
}
 
class TestNestedInterface2 implements A.Message{
 public void msg(){System.out.println("Hello nested interface");}
 
 public static void main(String args[]){
  A.Message message=new TestNestedInterface2();//upcasting here
  message.msg();
 }
}
Test it Now
Output:hello nested interface


Can we define a class inside the interface?

Yes, If we define a class inside the interface, java compiler creates a static nested class. Let's see how can we define a class within the interface:

interface M{
  class A{}
}



Local inner class

A class i.e. created inside a method is called local inner class in java. If you want to invoke the methods of local inner class, you must instantiate this class inside the method.

Java local inner class example

public class localInner1{
 private int data=30;//instance variable
 void display(){
  class Local{
   void msg(){System.out.println(data);}
  }
  Local l=new Local();
  l.msg();
 }
 public static void main(String args[]){
  localInner1 obj=new localInner1();
  obj.display();
 }
}

Internal class generated by the compiler

In such case, compiler creates a class named Simple$1Local that have the reference of the outer class.

import java.io.PrintStream;
class localInner1$Local
{
    final localInner1 this$0;
    localInner1$Local()
    {    
        super();
        this$0 = Simple.this;
    }
    void msg()
    {
        System.out.println(localInner1.access$000(localInner1.this));
    }
}



Rule: Local variable can't be private, public or protected.

Rules for Java Local Inner class

1) Local inner class cannot be invoked from outside the method.

2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access the non-final local variable in local inner class.

Example of local inner class with local variable

class localInner2{
 private int data=30;//instance variable
 void display(){
  int value=50;//local variable must be final till jdk 1.7 only
  class Local{
   void msg(){System.out.println(value);}
  }
  Local l=new Local();
  l.msg();
 }
 public static void main(String args[]){
  localInner2 obj=new localInner2();
  obj.display();
 }
}

Java Anonymous inner class

A class that have no name is known as anonymous inner class in java. It should be used if you have to override method of class or interface. Java Anonymous inner class can be created by two ways:

Class (may be abstract or concrete).
Interface
Java anonymous inner class example using class

abstract class Person{
  abstract void eat();
}
class TestAnonymousInner{
 public static void main(String args[]){
  Person p=new Person(){
  void eat(){System.out.println("nice fruits");}
  };
  p.eat();
 }
}

Internal working of given code

Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
A class is created but its name is decided by the compiler which extends the Person class and provides the implementation of the eat() method.
An object of Anonymous class is created that is referred by p reference variable of Person type.
Internal class generated by the compiler

import java.io.PrintStream;
static class TestAnonymousInner$1 extends Person
{
   TestAnonymousInner$1(){}
   void eat()
    {
        System.out.println("nice fruits");
    }
}
Java anonymous inner class example using interface

interface Eatable{
 void eat();
}
class TestAnnonymousInner1{
 public static void main(String args[]){
 Eatable e=new Eatable(){
  public void eat(){System.out.println("nice fruits");}
 };
 e.eat();
 }
}


import java.io.PrintStream;
static class TestAnonymousInner1$1 implements Eatable
{
TestAnonymousInner1$1(){}
void eat(){System.out.println("nice fruits");}
}

Member Inner Class

Member Inner Class A class created within class and outside method.
Anonymous Inner Class A class created for implementing interface or extending class. Its name is decided by the java compiler.
Local Inner Class A class created within method.
Static Nested Class A static class created within class.
Nested Interface An interface created within class or interface.


A non-static class that is created inside a class but outside a method is called member inner class.

Syntax:

class Outer{
 //code
 class Inner{
  //code
 }
}


class TestMemberOuter1{
 private int data=30;
 class Inner{
  void msg(){System.out.println("data is "+data);}
 }
 public static void main(String args[]){
  TestMemberOuter1 obj=new TestMemberOuter1();
  TestMemberOuter1.Inner in=obj.new Inner();
  in.msg();
 }
}

import java.io.PrintStream;
class Outer$Inner
{
    final Outer this$0;
    Outer$Inner()
    {   super();
        this$0 = Outer.this;
    }
    void msg()
    {
        System.out.println((new StringBuilder()).append("data is ")
                    .append(Outer.access$000(Outer.this)).toString());
    }
}

Static Class

Java static nested class

A static class i.e. created inside a class is called static nested class in java. It cannot access non-static data members and methods. It can be accessed by outer class name.

It can access static data members of outer class including private.
Static nested class cannot access non-static (instance) data member or method.

Outer classes cannot be static, but nested/inner classes can be.

Whenever we run a class JVM instantiates an object. JVM can create a number of objects, by definition Static means you have same set of copy to all objects.So, if top class is static then whenever you run a program it creates an Object and keeps over riding on to the same Memory Location.

class TestOuter1{
  static int data=30;
  static class Inner{
   void msg(){System.out.println("data is "+data);}
  }
  public static void main(String args[]){
  TestOuter1.Inner obj=new TestOuter1.Inner();
  obj.msg();
  }
}

import java.io.PrintStream;
static class TestOuter1$Inner
{
TestOuter1$Inner(){}
void msg(){
System.out.println((new StringBuilder()).append("data is ")
.append(TestOuter1.data).toString());
}  
}

class TestOuter2{
  static int data=30;
  static class Inner{
   static void msg(){System.out.println("data is "+data);}
  }
  public static void main(String args[]){
  TestOuter2.Inner.msg();//no need to create the instance of static nested class
  }
}


Sunday, October 9, 2016

ExecutorService

The java.util.concurrent.ExecutorService interface represents an asynchronous execution mechanism which is capable of executing tasks in the background. An ExecutorService is thus very similar to a thread pool. In fact, the implementation of ExecutorService present in the java.util.concurrent package is a thread pool implementation.

ExecutorService executorService = Executors.newFixedThreadPool(10);

executorService.execute(new Runnable() {
    public void run() {
        System.out.println("Asynchronous task");
    }
});

executorService.shutdown();
First an ExecutorService is created using the newFixedThreadPool() factory method. This creates a thread pool with 10 threads executing tasks.

Second, an anonymous implementation of the Runnable interface is passed to the execute() method. This causes the Runnable to be executed by one of the threads in the ExecutorService.

Since ExecutorService is an interface, you need to its implementations in order to make any use of it. The ExecutorService has the following implementation in the java.util.concurrent package:

ThreadPoolExecutor
ScheduledThreadPoolExecutor

Creating an ExecutorService
How you create an ExecutorService depends on the implementation you use. However, you can use the Executors factory class to create ExecutorService instances too. Here are a few examples of creating an ExecutorService:

ExecutorService executorService1 = Executors.newSingleThreadExecutor();

ExecutorService executorService2 = Executors.newFixedThreadPool(10);

ExecutorService executorService3 = Executors.newScheduledThreadPool(10);
ExecutorService Usage
There are a few different ways to delegate tasks for execution to an ExecutorService:

execute(Runnable)
submit(Runnable)
submit(Callable)
invokeAny(...)
invokeAll(...)

Armstrong Number

153 = (1*1*1)+(5*5*5)+(3*3*3)  
where:  
(1*1*1)=1  
(5*5*5)=125  
(3*3*3)=27  
So:  
1+125+27=153  

class ArmstrongExample{  
  public static void main(String[] args)  {  
    int c=0,a,temp;  
    int n=153;
    //It is the number to check armstrong  
    temp=n;  
    while(n>0)  
    {  
    a=n%10;  
    n=n/10;  
    c=c+(a*a*a);  
    }  
    if(temp==c)  
    System.out.println("armstrong number");   
    else  
        System.out.println("Not armstrong number");   
   }  
}  

Design Pattern

















Collection Implementation












String Features






Exception hierarchy


























உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...