Pages

Wednesday 27 July 2016

Create an annotation in Java

CustomAnnotation.java
importjava.lang.annotation.ElementType;
importjava.lang.annotation.Retention;
importjava.lang.annotation.RetentionPolicy;
importjava.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
     int studentAge() default 21;
     String studentName();
     String stuAddress();
     String stuStream() default "CS";
}

How to use the field of Annotation in Java?

TestCustomAnnotation.java
package annotations;
import java.lang.reflect.Method;
public class TestCustomAnnotation {
     public static void main(String[] args) {
           newTestCustomAnnotation().testAnnotation();
     }
     @CustomAnnotation(
                studentName="Rajesh",
                stuAddress="Mathura, India"
     )
     public voidtestAnnotation() {
           try {
                Class<? extends TestCustomAnnotation> cls = this.getClass();
                Method method = cls.getMethod("testAnnotation");
               
                CustomAnnotation myAnno = method.getAnnotation(CustomAnnotation.class);
               
                System.out.println("Name: "+myAnno.studentName());
                System.out.println("Address: "+myAnno.stuAddress());
                System.out.println("Age: "+myAnno.studentAge());
                System.out.println("Stream: "+myAnno.stuStream());
               
           } catch(NoSuchMethodException e) {
           }
     }
}
Output:
Name: Rajesh
Address: Mathura, India
Age: 21
Stream: CS

Java Annotations

Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.

Uses of Annotations:
Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
Runtime processing — some annotations are available to be examined at runtime.

Example of Java annotations:
To describe constraints or usage of an element: e.g. @Deprecated, @Override, or @NotNull.
To describe the "nature" of an element: e.g. @Entity, @TestCase, @WebService.
To describe the behavior of an element: @Statefull, @Transaction.
To describe how to process the element:  @Column, @XmlElement.

In all the above cases, annotations are used to describe the element and clarify its meaning.

Note:
Prior to JDK5, information that is now expressed with annotations needed to be stored somewhere else, and XML files were frequently used. However it is more convenient to use annotations because they will belong to the Java code itself, and are hence much easier to manipulate than XML.

Advantages of the annotation:
1) All the information is in a single file (no need to open two files to configure a given behavior).
2) When the class changes, no need to modify the xml file.

Tuesday 19 July 2016

Longest Palindromic Substring

    Brute force

Time complexity: O ( n^3 )
Auxiliary complexity: O ( 1 ).

    Dynamic programming

Time complexity: O ( n^2 )
Auxiliary complexity: O ( n^2)

package geeks.dp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class LongestPalindromeSubstring {
       private static int max = 0;

       public static void main(String[] argsthrows IOException {
           BufferedReader buffReader = new BufferedReader(
                                         new InputStreamReader(System.in));
           System.out.println("Input String !!");
           char[] inputChars = buffReader.readLine().toCharArray();
             
           int length = inputChars.length;
             
           int[][] dp = new int[length+1][length+1];
             
           for (int i = 1; i <= lengthi++) {
               for (int j = 1; j <=lengthj++) {
                   if(inputChars[i-1]==inputChars[length-j]) {
                        dp[i][j] = dp[i-1][j-1]+1;
                   } else {
                        dp[i][j] = 0;
                   }
                   max = Math.max(dp[i][j], max );
               }
          }
          System.out.println(max);
       }
}

Output:
Input String !!
geeksskeeggeeksskeeg
20

Tuesday 12 July 2016

Design Principle vs.Design Pattern

Object Oriented Programming
OOP is a programming paradigm that represents concepts as “objects” that have data fields (attributes that describe the object) and associated methods. Objects (instances of classes) are used to interact with one another to design applications and computer programs.

OO basics principles:
Polymorphism
Abstraction
Encapsulation
Inheritance


Design Principles:
Design principles are core abstract principles which we are supposed to follow while designing software architect. Remember they aren't concrete; rather abstract.

OO principle is a set of guidelines that ensures OOP concept.Based on the OOP concept, this defines ways to design better way, a better design.

Examples:
1. Single Responsibility Principle
2. Open Close Principle
3. Liskov’s Substitution Principle
4. Interface Segregation Principle
5. Dependency Inversion Principle


Design Patterns:
They are solutions to real world problems that pop up time and again, so instead of reinventing the wheel, we follow the design patterns that are well-proven, tested by others, and safe to follow. Now, design patterns are specific, there are terms and conditions only in which they can be applied.

OO design patterns (OODPs) are those which provide a general solution to object oriented design based OO principle.

Design patterns are discovered, not invented.

Examples:
Singleton Pattern
Factory pattern.

Saturday 9 July 2016

Nth maximum salary in MySQL using LIMIT clause

MySQL supports a LIMIT keyword, which provides pagination capability. We can find the nth highest salary in MySQL without using sub query.


SELECT salary FROM Employee ORDER BY salary DESC LIMIT N-1, 1;


4rth highest salary in MySQL with LIMIT clause: 
-- use database
use abusecore;

-- creating Employee table in mysql
CREATE TABLE Employee (name varchar(10), salary int);

-- inserting sample data into Employee table
INSERT INTO Employee VALUES ('Mill', 3000);
INSERT INTO Employee VALUES ('Sham', 4000);
INSERT INTO Employee VALUES ('Jack', 3000);
INSERT INTO Employee VALUES ('Pats', 5000);
INSERT INTO Employee VALUES ('Rock', 7000);

-- 4rth highest salary in MySQL
SELECT salary FROM Employee ORDER BY Salary DESC LIMIT 3,1

-- Output:
3000

Nth highest salary in MySQL with LIMIT clause:

SELECT salary FROM Employee ORDER BY Salary DESC LIMIT n-1,1;



This approach is faster than correlated query approach but its vendor dependent.

What does persistence object means in Hibernate architecture?

Persistent object is nothing but an instance of POJO class that we create to represent rows in the table in the database.

According to hibernate-doc an instance of POJO class representing table in database goes through 3 states.

Transient
Persistent
Detached

When a POJO instance is in session scope, it is said to be persistent i.e hibernate detects any changes made to that object and synchronizes it with database when we close or flush the session.

Friday 8 July 2016

What is database deadlock? How can we avoid them?

Database deadlock
When multiple external resources are trying to access the DB locks and runs into cyclic wait, it may make the DB unresponsive.

Avoid Database deadlock
1. Can make a queue wherein we can verify and order the request to DB (To run the operations in FIFO order).
2. Less use of cursors as they lock the tables for long time (slow down the DML executions).
3. Keeping the transaction smaller (process query relation operation before start the transactions).

What algorithm is used in modern day elevators?

Knuth's Elevator algorithm
The elevator algorithm, a simple algorithm by which a single elevator can decide where to stop, is summarised as follows:

1. Continue travelling in the same direction while there are remaining requests in that same direction.
2. If there are no further requests in that direction, then stop and become idle, or change direction if there are requests in the opposite direction.

The elevator algorithm has found an application in computer operating systems as an algorithm for scheduling hard disk requests.

Modern elevators use more complex heuristic algorithms to decide which request to service next.

Parallelism vs Concurrency

Parallelism
Parallelism means that an application splits its tasks up into smaller subtasks which can be processed in parallel, for instance on multiple CPUs at the exact same time.



Example:If a person is listening to music while writing an assignment then work done is in parallel way.

Concurrency
A condition that exists when at least two threads are making progress. A more generalized form of parallelism that can include time-slicing as a form of virtual parallelism.

If the computer only has one CPU the application may not make progress on more than one task at exactly the same time, but more than one task is being processed at a time inside the application. It does not completely finish one task before it begins the next.




Example:If a person is watching TV while writing an assignment then work done is in concurrent way.

Pizza Factory design in Java

Design patterns used:

1.     Abstract Factory,
2.     Template method pattern (to define the preparation sequence).

VeggiePizza.java
package com.pizza.factory;
public class VeggiePizza extends Pizza {

     public VeggiePizza() {
           name = "Veggie Pizza";
           dough = "Crust";
           sauce = "Marinara sauce";
           toppings.add("Shredded mozzarella");
           toppings.add("Grated parmesan");
           toppings.add("Diced onion");
           toppings.add("Sliced mushrooms");
           toppings.add("Sliced red pepper");
           toppings.add("Sliced black olives");
     }

     @Override
     public voidprepare() {
           System.out.println("Add Veggie !!");

     }

     @Override
     public voidbake() {
           System.out.println("Bake Veggie Pizza !!");

     }

     @Override
     public voidcut() {
           System.out.println("Cut Veggie Pizza !!");

     }

     @Override
     public voidpack() {
           System.out.println("Pack Veggie Pizza !!");

     }
}

CheesePizza.java
package com.pizza.factory;
public class CheesePizza extends Pizza {
    
     public CheesePizza() {
           name = "Cheese Pizza";
           dough = "Regular Crust";
           sauce = "Marinara Pizza Sauce";
           toppings.add("Fresh Mozzarella");
           toppings.add("Parmesan");
     }

     @Override
     public voidprepare() {
           System.out.println("Add Cheese !!");
          
     }

     @Override
     public voidbake() {
           System.out.println("Bake Cheese Pizza !!");
          
     }

     @Override
     public voidcut() {
           System.out.println("Cut Cheese Pizza !!");
          
     }

     @Override
     public voidpack() {
           System.out.println("Pack Cheese Pizza !!");
     }
}

Pizza.java
package com.pizza.factory;
import java.util.ArrayList;

public abstract class Pizza {
     
      String name;
      String dough;
      String sauce;
      ArrayList<String> toppings = new ArrayList<String>();
     
     
    /**
     * Template method Pattern - Sequence of processes.
     * To define the sequence to prepare Pizza.
     */
    public finalvoidtemplatePizzaPrepare() {
     
      /*Step#1. prepare Pizza integrants */
      prepare();
     
      /*Step#2. bake the Pizza. */
      bake();
     
      /*Step#3. cut the slice of Pizza. */
      cut();
     
      /*Step#4. pack the Pizza. */
      pack();
    }

      public abstract void prepare();
     
      public abstract void bake();
     
      public abstract void cut();
     
      public abstract void pack();
}

SimplePizzaFactory.java
package com.pizza.factory;
public class SimplePizzaFactory {
    
     public static Pizza orderPizza(String type) {
          
           Pizza pizza = null;
          
           if("cheese".equals(type)) {
                pizza = new CheesePizza();
           } else if("veggie".equals(type)) {
                pizza = new VeggiePizza();
           }
          
           pizza.templatePizzaPrepare();
           return pizza;
     }
}

PizzaStore.java

package com.pizza.factory;
public class PizzaStore {

     public static void main(String[] args) {

           Pizza pizza  = SimplePizzaFactory.orderPizza("cheese");
          
           System.out.println("\nPizza ready : "+ pizza.name);
          
           /*pizza  = SimplePizzaFactory.createPizza("veggie");
           System.out.println("Pizza type : "+ pizza);*/
     }
}