Posts

Showing posts from October, 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.readVa...

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...

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.setAc...

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

Image
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

Image
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: @BeforeClass – Run once before any of the test methods in the class,  public static void @AfterClass – Run once after all the tests in the class have been run,  public static void @Before – Run before @Test,  public void @After – Run after @Test,  public void @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  ...

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;...

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 referre...

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()    ...

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 { ...

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(); ...

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;...

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 ...

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

Image

Collection Implementation

Image

String Features

Image

Exception hierarchy

Image