Thursday 21 November 2013

Eclipse Shortcuts Key

By Using shortcuts key make a developer more productive. Eclipse provides keyboard shortcuts for the common actions. Using shortcuts is usually preferable as you can perform actions much faster.

FILE NAVIGATION – ECLIPSE SHORTCUTS

CTRL+SHIFT+R – Open a resource. You need not know the path and just part of the file name is enough.
CTRL +E – Open a file (editor) from within the list of all open files.
CTRL +PAGE UP or PAGE DOWN – Navigate to previous or next file from within the list of all open files.
ALT +Left Arrow or ALT+Right Arrow – Go to previous or next edit positions from editor history list.

Java Editing-

CTRL+SPACE – Type assist
CTRL+SHIFT+F – Format code.
CTRL+O – List all methods of the class and again CTRL O lists including inherited methods.
CTRL +SHIFT +O – Organize imports.
CTRL+SHIFT +U – Find reference in file.
CTRL+ / – Comment a line.
F3 – Go to the declaration of the variable.
F4 – Show type hierarchy of on a class.
CTRL +T – Show inheritance tree of current token.
SHIFT +F2 – Show Javadoc for current element.
ALT+ SHIFT +Z – Enclose block in try-catch.

GENERAL EDITING SHORTCUTS

F12 – Focus on current editor.
CTRL +L – Go to line number.
CTRL +D – Delete a line.
CTRL+<- or -> – Move one element left or

Search from an editor

Ctrl + . Go to the next problem / error
Ctrl + , Go to the previous problem / error
F4 on a variable Show type hierarchy
Ctrl + J Incremental search without popup dialog, just starting typing to search. Press Ctrl + J to find the next match
Ctrl + K Searches the selected text or if nothing is selected the last search from the Find dialog.
Ctrl + Shift + G In the Java editor, s\earch for references in the workspace
Ctrl + Shift + P Select the matching bracket. Cursor needs to be placed before or after a bracket.

Running programs
Ctrl + F11 Run last launched
Alt + Shift + X, J Run current selected class as Java application

Create new lines
Shift + Enter Adds a blank line below the current line and moves the cursor to the new line. The difference between a regular enter is that the currently line is unchanged, independently of the position of the cursor.
Ctrl+Shift+Enter Same as Shift + Enter but above

Variable assignment
Ctrl + 2, L Assign statement to new local variable
Ctrl + 2, F Assign statement to new field

Re-factoring
Alt + Shift + R  Rename
Ctrl + 2, R Rename locally (in file), faster than Alt + Shift + R
Alt + Shift + T Opens the context-sensitive re-factoring menu, e.g. displays

Must known shortcuts
Ctrl + S Saves current editor
Ctrl + 1 Quickfix; shows potential fixes for warnings, errors or shows possible actions
Ctrl + Space Content assist/ code completion
Ctrl + Q Goes to the last edited position
Ctrl+ D Deletes current line in the editor
Ctrl + Shift + O Adjusts the imports statements in the current Java source file
Ctrl + 2, L or F Assign statement to new local variable or field
Ctrl + Shift + T Open Type Dialog
Ctrl + O Shows quick outline of a class
Ctrl + F11 Run last launched application

@References-
Eclipse Official site

Thursday 7 November 2013

Java Interview Question Part-3


Q- Difference Between Serialization and Externalizable interface?
Serialization is Marker interface which doesnt contains any method.The implemented class just gives the instruction to JVM to behave differently for the implemented class.the main goal of serilaliztaion is persist the state of an object into a stream.
By implementing java.io.Serializable, you get "automatic" serialization capability for objects of your class. No need to implement any other logic, it'll just work. The Java runtime will use reflection to figure out how to marshal and unmarshal your objects.

In earlier version of Java, reflection was very slow, and so serializing large object graphs was a bit of a performance problem. To handle this situation, the java.io.Externalizable interface was provided, which is like java.io.Serializable but with custom-written mechanisms to perform the marshalling and unmarshalling functions (you need to implement readExternal and writeExternal methods on your class).It can be useful when there is a transient variable in your class and the value can be calculated from the object's state.

Q- Write a program in java to find the lenghth of string without using any length or size|().

int findStringLength(String str)
{
char[] elements = str.toCharArray();
int count=0;
for(char c : elements){
count++;
}
return count;
}


Q.what is generic Eraser in java?
When we implement the generic then compiler does these things
1. Type casting if necessary to preserve type safety.
2. Resolve all the cases at compile time. Make safe to run.
3. Generate a bridge to gain polymorphism.

And after this compiler removes the generic type and at runtime it is executed without specific type.
It means bytecode of List is same as bytecode of List.

As per the oracle docs,

Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to:

Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
Insert type casts if necessary to preserve type safety.
Generate bridge methods to preserve polymorphism in extended generic types.
Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.



Q.If new object is created by thread then where object's attributes are going to be created? stack or heap?

class Myclass{

String str;
MyObject object;

public void m1(){

str = new String("hello");
object = new MyObject();
int i = 10;
}
Suppose now thread A creates object of this class and calls method() then where data, object and i will be created? heap or stack of thread?

Object is allocated in Heap, but reference push to the stack. Also you should know that each thread has his own stack.
All four objects: MyClass, MyObject, String str and "hello" are created in Heap area. In fact there is no way an object can be "created" in stack area. Nevertheless, variable 'i' would be created in the stack of m1().
It does not matter whether "Thread" indirectly creates an object or JVM, objects would always be created in the Heap area only.





Wednesday 2 October 2013

Java Interview Question Part-2

How can Arraylist be synchronized without using Vector?

Arraylist can be synchronized using:

Collection.synchronizedList(List list)

Other collections can be synchronized:
Collection.synchronizedMap(Map map)
Collection.synchronizedCollection(Collection c)

What is difference between ArrayList and vector?

Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.
Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?

Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID
Now call Collections.sort() method and pass list as an argument.

How about when Employee class is a jar file and you do not have access to its source code?

Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .
Call Collections.sort() on the list and pass Comparator as an argument.

What is difference between HashMap and HashTable?

Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are
HashMap is not synchronized in nature but HashTable is.
Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. Fail-safe - if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException
HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null.


What are the prominent implementation of List interface?

The classes that implement List interface:
ArrayList: It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.
Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.
LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.


Which all classes implement Set interface?

SortedSet - It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.
TreeSet - It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.
HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets

What is difference between List and a Set?

List can contain duplicate values but Set doesnt allow. Set allows only to unique elements.
List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(Except HashSet)

What is difference between Arrays and ArrayList ?

Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as:
int [] intArray= new int[6];
intArray[7] // will give ArraysOutOfBoundException.
Also the size of array cannot be incremented or decremented. But with ArrayList the size is variable. Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.
List list = new ArrayList();
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.
ArrayList is one dimensional but array can be multidimensional.
int[][][] intArray= new int[3][2][1]; // 3 dimensional array
To create an array the size should be known or initialized to some value. If not initialized carefully there could me memory wastage. But arrayList is all about dynamic creation and there is no wastage of memory.


When to use ArrayList or LinkedList ?

Adding new elements is pretty fast for either type of list. For the ArrayList, doing random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list.


Consider a scenario. If an ArrayList has to be iterated to read data only, what are the possible ways and which is the fastest?

It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly as per the index.
Now another question with respect to above question is if accessing through iterator is slow then why do we need it and when to use it.
For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.

Which design pattern Iterator follows?

It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern. The Iterator pattern is one, which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation. Iterator should be implemented as an interface. This allows the user to implement it anyway its easier for him/her to return data. The benefits of Iterator are about their strength to provide a common interface for iterating through collections without bothering about underlying implementation.

Example of Iteration design pattern - Enumeration The class java.util.Enumeration is an example of the Iterator pattern. It represents and abstract means of iterating over a collection of elements in some sequential order without the client having to know the representation of the collection being iterated over. It can be used to provide a uniform interface for traversing collections of all kinds.

Is it better to have a HashMap with large number of records or n number of small hashMaps?

It depends on the different scenario one is working on:
If the objects in the hashMap are same then there is no point in having different hashmap as the traverse time in a hashmap is invariant to the size of the Map.
If the objects are of different type like one of Person class , other of Animal class etc then also one can have single hashmap but different hashmap would score over it as it would have better readability.

Why is it preferred to declare: List list = new ArrayList(); instead of ArrayList = new ArrayList();

It is preferred because
If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that.
The most important one – If a function is declared such that it takes list. E.g void showDetails(List list);
When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible.

What is difference between iterator access and index access?

Index based access allow access of the element directly on the basis of index. The cursor of the data structure can directly goto the 'n' location and get the element. It does not traverse through n-1 elements.
In Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the 'n'th element it need to traverse through n-1 elements.
Insertion,updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the datastructure.
Insertion,updation or deletion will be faster for index based access if the operations are performed on elements present at last of the datastructure.
Traversal or search in index based datastructure is faster.
ArrayList is index access and LinkedList is iterator access.

Can a null element added to a Treeset or HashSet?

A null element can be added only if the TreeSet contains one element because when a second element is added then as per set definition a check is made to check duplicate value and comparison with null element will throw NullPointerException. HashSet is based on hashMap and can contain null element.

How to sort list of strings - case insensitive?

using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

What is ConcurrentHashMap?

A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.

What is identityHashMap?

The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.

What is WeakHashMap?

A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations

Any Comment and suggestion must be appreciated :-)

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