Friday 30 August 2013

Servlet Life Cycle in Details

Servlet Life Cycle can be defined as the complete process from the servlet creation to the destroy of Servlet.

The Servlet life cycle goes through following steps,
1-Loading
2-Initialization
3-Service(Request Handling)
4-Destroying


Now we will look in to all the steps in details one by one,

Servlet Life Cycle Diagram
Pic-Servlet Life Lycle

1-Loading-
In this steps container or server will load the Servlet for further use.This step can be categories in two steps for better understanding.Lets look in to the Loading process,

a)Loading- Container will loads a servlet class by using normal java class loading option.

b)Initialization:

i)If servlet is not hosted in the distributed environment and it does not implements SingleThreadModel interface, the container will create only one instance.

ii)If servlet is hosted in the distributed environment the container will create one Servlet instance per JVM.

iii)If Servlet implements SingleThreadModel interface, the container may create multiple instance for Servlet, if in this case the servlet is hosted as distributed, the Servlet container may create multiple instance per JVM.

2-Initialization-
After the Servlet is instantiated successfully, the servlet container initializes the instantiated Servlet object. The container initialize object by invoking init(ServletConfig) method. Container creates one ServletConfig object per Servlet.Servlet container invokes init(ServletConfig) method once immediately after the Servlet object is instantiated successfully.

3-Service-
After initialization the servlet instance is ready to serve client request. The container performs the following operation when instance is located to service a request,

i)Container creates ServletRequest and ServletResponse object.

ii)After creating request, response object container invokes service(ServletRequest, ServletResponse) method. Following are cases occur while dealing with multiple request,

a)If Servlet does not implements SingleThreadModel interface container uses single instance of servlet to process multiple request at a time.
b)If Servlet does implements SingleThreadModel interface container uses single instance of servlet to process only one request at a time. If Servlet is marked as distributed then separate pool of Servlet instances in each JVM.

4-Destroying-
Container calls destroy() method where it release all resources which has allocated.The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.

Monday 12 August 2013

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

public class FizzBuzzProgramme {
    public static void main(String[] args) {
        boolean flag;
        for (int i = 1; i<=100;i++)
        {
            flag = false;
            if (i%3==0)
            {   
                System.out.print("Fizz");
                flag = true;
            }
            if (i%5==0)
            {
                System.out.print("Buzz");
                flag = true;
            }
            if (flag == false)
            {
                System.out.print(i);
            }
            System.out.println();
        }
    }
 
}

Wednesday 7 August 2013

Some Solution from---- http://www.betterprogrammer.com/


public class Program {

public static int getClosestToZero(int[] a) {
    /*
     Please implement this method to
     return the number in the array that is closest to zero.
     If there are two equally close to zero elements like 2 and -2
     - consider the positive element to be "closer" to zero.
    */
    int num = array[0];

  int absNum = Math.abs(num);

  for(int i = 1; i < array.length; ++i) {
    int newAbs = Math.abs(array[i]);

    if(newAbs < absNum) {
      absNum = newAbs;
      num = array[i];
    }
  }
  return num;
  }

public static int sumOfTwoLargestElements(int[] a) { /* Please implement this method to return the sum of the two largest numbers in a given array. */ int sum = Integer.MIN_VALUE; int maxsum = Integer.MIN_VALUE; for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) { sum = a[i] + a[i - 1]; if (sum > maxsum) { maxsum = sum; } } else { sum = a[i]; if (sum > maxsum) { maxsum = sum; } } } if (a.length == 0) { return Integer.MIN_VALUE; } else { return maxsum; } } public static List<Integer> getPrimeNumbers(int from, int to) { /* Please implement this method to return a list of all prime numbers in the given range (inclusively). A prime number is a natural number that has exactly two distinct natural number divisors, which are 1 and the prime number itself. The first prime numbers are: 2, 3, 5, 7, 11, 13 */ List<Integer> primeNumbers = new ArrayList<Integer>(); for(int i=from; i<=to; i++) { if(isPrime(i)) primeNumbers.add(i); } return primeNumbers; } static boolean isPrime(int n) { if(n==1) return false; for(int i=2;i<n;i++) { if(n%i==0) return false; } return true; } public static Object[] reverseArray(Object[] a) { /* Please implement this method to return a new array where the order of elements has been reversed from the original array. */ Object[] b = null; int o = 0; for (int i = a.length; i > 0; i--) { b[0] = a[i]; } return b; } public static int countWaysToProduceGivenAmountOfMoney(int cents) { int[] dp = new int[cents+1]; dp[0] = 1; for (int x : new int[] {1, 5, 10, 25, 50}) for (int i = 0; i+x <= cents; ++i) dp[i+x] += dp[i]; return dp[cents]; } public static int[] retainPositiveNumbers(int[] a) { /* Please implement this method to return a new array with only positive numbers from the given array. The elements in the resulting array shall be sorted in the ascending order. */ ArrayList<Integer> list = new ArrayList<Integer>(); for(int i : a){ if(i >= 0) list.add(i); } Integer[] posIntegers = list.toArray(new Integer[0]); int[] posInts = new int[posIntegers.length]; for (int i = 0; i < posInts.length; i++) { posInts[i] = posIntegers[i]; } Arrays.sort(posInts); return posInts; } public static class WriteOnceMap<K, V> extends HashMap<K, V> { public V put(K key, V value) { /* WriteOnceMap is a map that does not allow changing value for a particular key. It means that put() method should throw IllegalArgumentException if the key is already assosiated with some value in the map. Please implement this method to conform to the above description of WriteOnceMap. */ if (containsKey(key)) throw new IllegalArgumentException(key + " already in map"); return super.put(key, value); } public void putAll(Map<? extends K, ? extends V> m) { /* Pleaase implement this method to conform to the description of WriteOnceMap above. It should either (1) copy all of the mappings from the specified map to this map or (2) throw IllegalArgumentException and leave this map intact if the parameter already contains some keys from this map. */ for (K key : m.keySet()) if (containsKey(key)) throw new IllegalArgumentException(key + " already in map"); super.putAll(m); } } public static int countWords(String s) { /* Please implement this method to return the word count in a given String. Assume that the parameter String can only contain spaces and alphanumeric characters. */ String[] b = s.split(" "); return b.length; } public static boolean isPalindrome(String s) { /* Definition: A palindrome is a string that reads the same forward and backward. For example, "abcba" is a palindrome, "abab" is not. Please implement this method to return true if the parameter is a palindrome and false otherwise. */ int left = 0; int right = s.length() -1; while (left < right) { if (s.charAt(left) != s.charAt(right)) { return false; } left++; right--; } return true; }
public static double getAverage(Node root) { /* Please implement this method to return the average of all node values (Node.getValue()) in the tree. */ int total = 0; for (int i = 0; i < root.getChildren().size(); i++) { total += root.getChildren().get(i).getValue(); } return (total / root.getChildren().size()); } public static int getSumOfNumbers(String s) { /* Please implement this method to return the sum of all integers found in the parameter String. You can assume that integers are separated from other parts with one or more spaces (' ' symbol). For example, s="12 some text 3 7", result: 22 (12+3+7=22) */ int sum=0; String modifiedString = s.replaceAll("\\D+"," "); System.out.println(modifiedString); StringTokenizer st = new StringTokenizer(modifiedString, " "); while(st.hasMoreTokens()) { String numeric = st.nextToken(); sum+= Integer.parseInt(numeric); } return sum; } public static String capitalizeFirstLetters(String s) { StringBuilder res = new StringBuilder(); char prev = ' '; for (int i = 0; i < s.length(); ++i) { char ch = s.charAt(i); if (Character.isLetter(ch) && prev == ' ') res.append(Character.toUpperCase(ch)); else res.append(ch); prev = ch; } return res.toString(); } public static List<integer> getPerfectNumbers(int from, int to) { List<integer> res = new ArrayList<integer>(); for (int num = from; num <= to; ++num) { int sum = 0; for (int i = 1; i <= num/2; ++i) if (num%i == 0) sum += i; if (sum == num) res.add(num); } return res; } public static Change getCorrectChange(int cents) { int dol = cents/100; cents %= 100; int qua = cents/25; cents %= 25; int dim = cents/10; cents %= 10; int nic = cents/5; cents %= 5; return new Change(dol, qua, dim, nic, cents); } public static List<node> traverseTreeInDepth(Node root) { List<node> list = new ArrayList<node>(); depth(root, list); return list; } static void depth(Node root, List<node> list) { list.add(root); for (Node child : root.getChildren()) depth(child, list); } public static String getBinaryRepresentation(int n) { String res = ""; while (n > 0) { res = (char)('0'+n%2)+res; n /= 2; } if (res.length() == 0) res = "0"; return res; } public static List<string> transferFromAtoC(int n) { List<string> res = new ArrayList<string>(); hanoi(n, "A", "C", "B", res); return res; } static void hanoi(int n, String from, String to, String using, List<string> list) { if (n == 0) return; hanoi(n-1, from, using, to, list); list.add(from+to); hanoi(n-1, using, to, from, list); } public Node ReverseList(Node cur, Node prev) { if (cur == null) // if list is null return cur; Node n = cur.NextNode; cur.NextNode = prev; return (n == null) ? cur : ReverseList(n, cur); } }

Monday 5 August 2013

Singleton Pattern





For those who haven't heard of design patterns before, or who are familiar with the term but not its meaning, a design pattern is a template for software development. The purpose of the template is to define a particular behavior or technique that can be used as a building block for the construction of software - to solve universal problems that commonly face developers. Think of design code as a way of passing on some nifty piece of advice, just like your mother used to give. "Never wear your socks for more than one day" might be an old family adage, passed down from generation to generation. It's common sense solutions that are passed on to others. Consider a design pattern as a useful piece of advice for designing software.

Design patterns out of the way, let's look at the singleton. By now, you're probably wondering what a singleton is - isn't jargon terrible? A singleton is an object that cannot be instantiated. At first, that might seem counterintuitive - after all, we need an instance of an object before we can use it. Well yes a singleton can be created, but it can't be instantiated by developers - meaning that the singleton class has control over how it is created. The restriction on the singleton is that there can be only one instance of a singleton created by the Java Virtual Machine (JVM) - by prevent direct instantiation we can ensure that developers don't create a second copy.

So why would this be useful? Often in designing a system, we want to control how an object is used, and prevent others (ourselves included) from making copies of it or creating new instances. For example, a central configuration object that stores setup information should have one and one only instance - a global copy accessible from any part of the application, including any threads that are running. Creating a new configuration object and using it would be fairly useless, as other parts of the application might be looking at the old configuration object, and changes to application settings wouldn't always be acted upon. I'm sure you can think of a other situations where a singleton would be useful - perhaps you've even used one before without giving it a name. It's a common enough design criteria (not used everyday, but you'll come across it from time to time). The singleton pattern can be applied in any language, but since we're all Java programmers here (if you're not, shame!) let's look at how to implement the pattern using Java.

Preventing direct instantiation

We all know how objects are instantiated right? Maybe not everyone? Let's go through a quick refresher.

Objects are instantiated by using the new keyword. The new keyword allows you to create a new instance of an object, and to specify parameters to the class's constructor. You can specify no parameters, in which case the blank constructor (also known as the default constructor) is invoked. Constructors can have access modifiers, like public and private, which allow you to control which classes have access to a constructor. So to prevent direct instantiation, we create a private default constructor, so that other classes can't create a new instance.

We'll start with the class definition, for a SingletonObject class. Next, we provide a default constructor that is marked as private. No actual code needs to be written, but you're free to add some initialization code if you'd like.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
}
So far so good. But unless we add some further code, there'll be absolutely no way to use the class. We want to prevent direct instantiation, but we still need to allow a way to get a reference to an instance of the singleton object.

Getting an instance of the singleton

We need to provide an accessor method, that returns an instance of the SingletonObject class but doesn't allow more than one copy to be accessed. We can manually instantiate an object, but we need to keep a reference to the singleton so that subsequent calls to the accessor method can return the singleton (rather than creating a new one). To do this, provide a public static method called getSingletonObject(), and store a copy of the singleton in a private member variable.

public class SingletonObject
{
    private SingletonObject()
    {
        // no code req'd
    }

    public static SingletonObject getSingletonObject()
    {
      if (ref == null)
          // it's ok, we can call this constructor
          ref = new SingletonObject();
      return ref;
    }

    private static SingletonObject ref;
}
So far, so good. When first called, the getSingletonObject() method creates a singleton instance, assigns it to a member variable, and returns the singleton. Subsequent calls will return the same singleton, and all is well with the world. You could extend the functionality of the singleton object by adding new methods, to perform the types of tasks your singleton needs. So the singleton is done, right? Well almost.....

Preventing thread problems with your singleton

We need to make sure that threads calling the getSingletonObject() method don't cause problems, so it's advisable to mark the method as synchronized. This prevents two threads from calling the getSingletonObject() method at the same time. If one thread entered the method just after the other, you could end up calling the SingletonObject constructor twice and returning different values. To change the method, just add the synchronized keyword as follows to the method declaration :-

public static synchronized
SingletonObject getSingletonObject()
Are we finished yet?

There, finished. A singleton object that guarantees one instance of the class, and never more than one. Right? Well.... not quite. Where there's a will, there's a way - it is still possible to evade all our defensive programming and create more than one instance of the singleton class defined above. Here's where most articles on singletons fall down, because they forget about cloning. Examine the following code snippet, which clones a singleton object.

public class Clone
{
public static void main(String args[])
 throws Exception
{
 // Get a singleton
 SingletonObject obj =
 SingletonObject.getSingletonObject();

 // Buahahaha. Let's clone the object
 SingletonObject clone =
(SingletonObject) obj.clone();
}
}
Okay, we're cheating a little here. There isn't a clone() method defined in SingletonObject, but there is in the java.lang.Object class which it is inherited from. By default, the clone() method is marked as protected, but if your SingletonObject extends another class that does support cloning, it is possible to violate the design principles of the singleton.  So, to be absolutely positively 100% certain that a singleton really is a singleton, we must add a clone() method of our own, and throw a CloneNotSupportedException if anyone dares try!

Here's the final source code for a SingletonObject, which you can use as a template for your own singletons.

public class SingletonObject
{
  private SingletonObject()
  {
    // no code req'd
  }

  public static SingletonObject getSingletonObject()
  {
    if (ref == null)
        // it's ok, we can call this constructor
        ref = new SingletonObject();
    return ref;
  }

  public Object clone()
throws CloneNotSupportedException
  {
    throw new CloneNotSupportedException();
    // that'll teach 'em
  }

  private static SingletonObject ref;
}
Summary



#A singleton is an class that can be instantiated once, and only once. This is a fairly unique property, but useful in a wide range of object designs. Creating an implementation of the singleton pattern is fairly straightforward - simple block off access to all constructors, provide a static method for getting an instance of the singleton, and prevent cloning.


@Ref-Thinking in Java

calling one class main method from another class main method

Let's use these two classes to demonstrate:

public class MainIsCallingMain {

public static void main(String args[])
{
System.out.println("==INSIDE THE FIRST MAIN METHOD==");
String[] test = {"first", "second", "third"};

SecondMain.main(test);
}
}

public class SecondMain {

public  static void main(String args[])
{
System.out.println("==INSIDE THE SECOND TMAIN METHOD==");

for(String a: args)
{
System.out.println("Second Class===" + a);
}
}

}



MainIsCallingMain won't compile the way it is.Need to configure SecondMain  on the classpath or compile both Class at same time.

@In eclipse please add the SecondMain  in MainIsCallingMain's class path.

Friday 2 August 2013

Prepared Statement In java

PreparedStatement In Java
Prepared statement are more powerful than statement or we can say that its special kind of  Object with some useful features.

Creating a Prepared Statement-

Before using the prepared statement we must have to create it,as given below,

String sql = "select * from worker where id=?";

PreparedStatemnt ps=connection.prepareStatement(sql);

Value Insertion in Prepared Statement

Wherever you need to insert a parameter into your SQL query at run time, you have to write a question mark (?).
e.g, String sql = "select * from people where id=?";

While PreparedStatement is created (prepared) for the above SQL statement,
We can insert parameters at the location of the question mark. This is done by using the setter method,

ps.setLong(1, 123);

In the above line will dig then come to know that The first number (1) is the index of the parameter to insert the value for. The second number (123) is the value to insert into the SQL statement.
If you have more than one  parameter in a sql statement than you have to give the question marks as per parameter count.

Execution of PreparedStatement

Depend upon the requirement you may call executeQuery() or executeUpdate method.

e.g
String sql = "select * from worker where id=? and age=?";

 PreparedStatement ps =
         connection.prepareStatement(sql);

 ps.setString(1, "1001");
 ps.setString(2, "56");

 ResultSet result = ps.executeQuery();


Characteristics of PreparedStatement,



  • if you want to execute a query in a loop (more than 1 time), prepared statement can be faster.
  • Efficient for repeated executions
  • It is precompiled so it's faster.(Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches)
  • sql injection is ignored by prepared statement so security is increase in prepared statement
  • Easy to insert parameters into the SQL statement.
  • Easy to reuse the PreparedStatement with new parameters.
  • May increase performance of executed statements.
  • Enables easier batch updates.
  • inherits all methods from Statement. It inherits the addBatch method, and additionally allows a set of parameter values to be added to match the set of batched SQL commands via addBatch method.
  •  Prepared statements are normally executed through a non-SQL binary protocol. This means that there is less data in the packets, so communications to the server is faster. As a rule of thumb network operations are an order of magnitude faster than disk operations which are an order of magnitude faster than in-memory CPU operations. Hence, any reduction in amount of data sent over the network will have a good effect on overall performance.

Thursday 1 August 2013

Find the Duplicate element from ArrayList in Java

How To Find the Duplicate element in ArrayList(Simple Approach).

Here i am taking an simple approach to do this.

Car.java

public class Car {

public int model;
public String name;

public Car()
{

}

public int getModel() {
return model;
}
public void setModel(int model) {
this.model = model;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public boolean equals(Object obj) {  
Car carObj=null;  
if(obj instanceof Car){  
carObj=(Car)obj;  
}  
if(carObj!=null && (this.model==carObj.model) && (this.name.equals(carObj.name))){  
return true;  
}  
return false;  
}  

public String toString() {
       return ("Car Model: " + model + "and" +
       "Car Name: " + name);
   }

}



CarImpl.java
public class CarImpl{


public static void main(String[] args) {

System.out.println("Get the Duplicate Element in a list");
Car c=new Car();
c.setModel(1);
c.setName("Honda");

Car c1=new Car();
c.setModel(11);
c.setName("Hyundai");

List<Car> listcar=new ArrayList<Car>();
listcar.add(c);
listcar.add(c);
listcar.add(c);
listcar.add(c1);

for(int i=0;i<listcar.size();i++)
{
for(int j=0;j<i;j++)
{
if(listcar.get(j).equals(listcar.get(i)))
{
System.out.println("Dupliacte Object are" + listcar.get(i).toString());
}
}

}

/*Map<Car, Integer> counts = new HashMap<Car, Integer>();

for (Car str : listcar) {
   if (counts.containsKey(str)) {
       counts.put(str, counts.get(str) + 1);
   } else {
       counts.put(str, 1);
   }
}

for (Map.Entry<Car, Integer> entry : counts.entrySet()) {
   System.out.println(entry.getKey() + " = " + entry.getValue());
}

*/

}
}

This is very simple approach to find out the duplicate element in list.

# Commented code also worked.

@I hope you will like my Blog and post.Any suggestion must be appreciated.

Find Duplicate Characters In String using Java

package com.zia.test; import java.util.HashMap; import java.util.Map; import java.util.Set; public class findDuplicateCharacter { /**...