Thursday, 26 January 2012

Rules for constructors in java

  1. Constructors can use any access modifier, including private. (A private constructor means only code within the class itself can instantiate an object of that type, so if the private constructor class wants to allow an instance of the class to be used, the class must provide a static method or variable that allows access to an instance created from within the class.)
  2. The constructor name must match the name of the class.
  3. Constructors must not have a return type.
  4. It’s legal (but stupid) to have a method with the same name as the class, but that doesn’t make it a constructor. If you see a return type, it’s a method rather than a constructor. In fact, you could have both a method and a constructor with the same namethe name of the classin the same class, and that’s not a problem for Java. Be careful not to mistake a method for a constructor, be sure to look for a return type.
  5. If you don’t type a constructor into your class code, a default constructor will be automatically generated by the compiler.
  6. The default constructor is ALWAYS a no-arg constructor.
  7. If you want a no-arg constructor and you’ve typed any other constructor(s) into your class code, the compiler won’t provide the no-arg constructor for you. In other words, if you’ve typed in a constructor with arguments, you won’t have a no-arg constructor unless you type it in yourself !
  8. Every constructor has, as its first statement, either a call to an overloaded constructor (this()) or a call to the superclass constructor (super()), although remember that this call can be inserted by the compiler.
  9. If you do type in a constructor (as opposed to relying on the compiler-generated default constructor), and you do not type in the call to super() or a call to this(), the compiler will insert a no-arg call to super() for you, as the very first statement in the constructor.
  10. A call to super() can be either a no-arg call or can include arguments passed to the super constructor.
  11. A no-arg constructor is not necessarily the default (i.e., compiler-supplied) constructor, although the default constructor is always a no-arg constructor. The default constructor is the one the compiler provides! While the default constructor is always a no-arg constructor, you’re free to put in your own noarg constructor.
  12. You cannot make a call to an instance method, or access an instance variable, until after the super constructor runs.
  13. Only static variables and methods can be accessed as part of the call to super() or this(). (Example: super(Animal.NAME) is OK, because NAME is declared as a static variable.)
  14. Abstract classes have constructors, and those constructors are always called when a concrete subclass is instantiated.
  15. Interfaces do not have constructors. Interfaces are not part of an object’s inheritance tree.
  16. The only way a constructor can be invoked is from within another constructor.

Wednesday, 25 January 2012

Access modifiers and non access modifiers meaning

http://way2java.com/oops-concepts/access-specifiers-access-modifiers/

Modifiers for variables, methods and classes

http://way2java.com/oops-concepts/access-modifiers-meanings/

Rules of Access Specifiers in Method Overriding

http://way2java.com/oops-concepts/rules-of-access-specifiers-in-method-overriding/

Modifiers and specifiers

http://way2java.com/oops-concepts/access-specifiers-access-modifiers/

OOPS concepts – Introduction

There are three basic concepts of OOPS

  1. Abstraction
  2. Encapsulation
  3. Polymorphism

1. Abstraction
Abstraction means using the equipment (or code) without knowing the details of working. For example, you are using your mobile phone without knowing how a mobile operates internally. Just a click on a button connects to your friend. This is abstraction. That is, the details of mobile mechanism are abstracted. Similarly we use the code of somebody to get the functionality without knowing how the code is written or working. For example, you are using printf() function to write to the DOS prompt without the awareness of what the code of printf(). One of the ways of achieving abstraction is inheritance. Through inheritance a subclass can use the super class methods as if they belong to it without caring their implementation details.
2. Encapsulation
Object-oriented concepts borrowed many terms from other technologies like encapsulation (from pharmaceuticals), inheritance (from biology), cloning (from genetics) and polymorphism (from biology) etc. Placing a powdered drug in a gelatin capsule and sealing it is known as encapsulation. With encapsulation, a Pharmacist hides the properties of a drug like its taste and color from the patient. Similar meaning is in OOPs also. Encapsulation hides the implementation details of coding; other way it is abstraction. With abstraction, implementation of information is hidden.
In a programming language, variables represent the properties and methods are used to change the properties. For example, the speed variable represent the property of a motor car and the method accelerator() is used to change the speed. Objects are used to call the methods. There may be multiple motor cars and every car has its own speed. Here, motor car represents an object. Every object encapsulates its own data. This encapsulation concept takes OOP languages a lead over traditional procedure-oriented languages. Binding data with objects (generally through method calls) is known as encapsulation.
In encapsulation, to have control over the manipulation of data (not to feed wrong data, for example, the speed cannot be negative) by other classes, a programmer declares variables as private and methods as public. Other classes can access the private variables through public methods. With encapsulation, every object maintains its own data and this data is entirely private to that object. Other objects cannot access or modify the data.
3. Polymorphism
Polymorphism is a Greek term and means many forms of the same ("poly" means many and "morphism" means forms). It is an OOP paradigm where one method can be made to give different outputs (functionalities) when called at different times. Polymorphism is two ways – static polymorphism where methods are binded at compile time and dynamic polymorphism where methods are binded dynamically at runtime. The same person is called as an officer (in office), husband (in house) and player (in cricket team). The person can be treated as base class. Extra subclasses can be added by hierarchical inheritance like son etc.

Types of inheritances in java

http://way2java.com/oops-concepts/types-of-inheritance/

Dynamic Polymorphism

http://way2java.com/oops-concepts/dynamic-polymorphism/

Method overloading

http://way2java.com/oops-concepts/using-methods-and-method-overloading/

Hashset Example in java

http://way2java.com/collections/hashset-operations/

Stack example with generics

http://way2java.com/collections/java-generics-stack/

Sunday, 22 January 2012

Queue example in java

Before going into the details of this program, it is advised to go through Queue Fundamentals where queue basics were discussed.
Following are some methods that do the similar operations.
  • boolean offer(Object obj): Adds the element obj to the queue. If the addition is successful, the method returns true else false.
  • Object poll(): Returns the head (first) element and also deletes it. That is, we cannot get it again. If no element exists (when queue is empty), the method returns null.
  • Object remove(): It also returns and deletes the head element like poll(), but with a small difference. This method throws NoSuchElementException if the queue is empty.
  • Object peek(): Returns the head element but it does not delete it. That is, we can get it again. Returns null when the queue is empty.
  • Object element(): It works similar to peek() but with a small difference (returns but does not delete the element). It throws NoSuchElementException when the queue is empty.
offer() method is equivalent to add() method of Collection interface.
http://way2java.com/collections/queue-programming/

Queues in java

interface Queue was introduced with JDK 1.5 and is part of collections framework as Queue extends Collection interface. Queue stores elements in such way it returns the first one added. Queue follows the style of FIFO (first in, first out, remember stack follows LIFO, last in, first out). The first element in the queue is known as head and the last one is known as tail. New elements are added to the tail.
Following is the signature
public interface Queue extends Collection
As queue is a subclass of Collection, it can make use of all the methods of Collection and also the extra defined in its own such as inserting, retrieving and checking the elements.
Queue vs List
The major variation is that list allows retrieving the elements from any position. But, queue follows FIFO. LinkedList implements both interfaces List and Queue.
Programming Tip: Queue allows null elements. But do not add null as the return type of poll() method is also null when the queue is empty. The return null value may confuse (or conflict) with the actual null value you have added.
Realtime examples of Queue
  • Job Seekers Queue: Imagine a number of participants, aspiring job, appearing for interview. They stand in a queue. The first one stood (head) in the queue comes out first and attends the interview. The participant who comes late joins at the last of the queue (tail). While queue moves on a number check points may be there to check their bonafides and marks lists etc. Care must be taken one participant cannot be checked by many at a time or one checking person cannot check a number of participants at a time. For this a synchronized queue (java.util.concurrent.BlockingQueue) exactly suits.
  • Cinema Tickets Queue: A person who stands first in the booking counter leaves first.

Saturday, 21 January 2012

Stack example in java

http://way2java.com/collections/java-stack/2/

Java Stack

Stack, in any language, stores elements in LIFO (Last-in First-out) order. As the name indicates, in LIFO, the last added element is retrieved first. It can be imagined like a stack of plates put on the top of the other. The plate added at the end is drawn first. In stack, elements cannot be added in the middle or removed. There can be only one point of entry and one point of exit.
Following is the class signature
public class Stack extends Vector
Stack is derived from Vector and again Vector is derived from List. List belongs to collections framework (JDK 1.2) and Stack and Vector belong to legacy classes (JDK 1.0). The Java designers extended List to Stack and Vector to give the features and advantages of collections to legacy classes. It is a good designing principle. Now stack and vector can use all the methods of Collection and List interfaces.
The java.util.Stack comes with five operations represented by five methods.
  1. Object push(Object obj): An element obj is added the to the stack with push() method. Elements are added implicitly on the top of another. The method returns the element added.
  2. Object pop(): With this method, the elements can be retrieved from the Stack. The last one added (which lies on the top) is returned first. With pop(), the element comes out of the stack permanently. That is, it cannot be retrieved again.
  3. int search(Object obj): With this method, an element, obj, index number can be obtained. The counting starts from the top. The topmost element index number is 1. If the stack is empty, the method returns EmptyStackException.
  4. peek(): This method returns the element existing on the top. But element is not popped (removed) out. With peek method, the element existence also can be known.
  5. boolean empty(): Returns true if no elements exist in the stack.
pop vs peek
For a beginner, these two methods are very confusing. Let us discuss again. The pop() method returns the element existing on the top of the stack. The element returned is deleted from the stack permanently. That is, the programmer cannot get it again.
The peek() method also returns the element but the element is not removed from the stack. That is, calling peek() method five times, returns the same element 5 times. peek() method can be used to know which element is lying on the top of the stack or which element is returned when pop() is called. It can be used in regular programming like this.
if(st.peek().equals("SNRao"))
       {
          System.out.println(st.pop());
       }
Limitations of Stack Usage
There are two limitations for stack usage.
  1. The programmer stores data in a DS with an intention to get the elements whenever he would like in the code. But with stack, the popped element is completely removed and cannot be obtained again. For this reason stack is not used much in general production software like health and banking etc, but used by system and tool developers.
  2. Another drawback is, the elements cannot be added or retrieved from the middle.
The Stack class comes with only one constructor.
  • Stack(): This default constructor creates an empty Stack object.

Thursday, 19 January 2012

TreeMap Program - Special functions


public static void specialFunctions(String args[])
{
 TreeMap<String, Integer> tm1 = new TreeMap<String, Integer>();  
 tm1.put("banana", 20);
 tm1.put("apple", 50);
 tm1.put("melon", 40);
 tm1.put("guava", 20);
 tm1.put("cherry", 30);

 System.out.println("\nElements of tm1: " + tm1);
 Set mySet = tm1.keySet();
 System.out.println("Keys of tm1: " + mySet);

 Collection myCol = tm1.values();
 System.out.println("Values of tm1: " + myCol);

 // USING ITERATOR
 System.out.print("\nPrinting keys with Iterator: ");
 Iterator it1 = mySet.iterator();
 while(it1.hasNext())
 {
  System.out.print(it1.next() + ", ");
 } 
 // TREEMAP SORT BY VALUE
 TreeSet yourSet = new TreeSet();
 yourSet.addAll(myCol);
 System.out.println("\nTreeMap sort by value: " + yourSet);

 // COMPARING TWO TREE MAPS
 TreeMap<String, Integer> tm2 = new TreeMap<String, Integer>();  
 tm2.putAll(tm1);
 System.out.println("\nElements of tm2: " + tm2);
 if(tm1.equals(tm2))
 {
  System.out.println("tm1 and tm2 contain same elements\n");
 } 

 System.out.println("\t\tEXTRACTING TREEMAP ELEMENTS\n");

 SortedMap m1 = tm1.subMap("banana", "guava");
 System.out.println("subMap(\"banana\", \"guava\"): " + m1);

 SortedMap m2 = tm1.headMap("guava");
 System.out.println("headMap(\"guava\"): " + m2);

 SortedMap m3 = tm1.tailMap("guava");
 System.out.println("tailMap(\"guava\"): " + m3);
}




TreeMap Progam - General Functions

public static void generalFunctionsDemo(String args[])
{
 TreeMap tm1 = new TreeMap();
 System.out.println("tm1 isEmpty() before adding elements: " + tm1.isEmpty());
 tm1.put("one", 1);
 tm1.put("apple", "red");
 tm1.put("two", 2);
 tm1.put("three", 3);
 tm1.put("four", 4);

 System.out.println("tm1 isEmpty() after adding elements: " + tm1.isEmpty());
 System.out.println("Key/value pairs of tm1:" +  tm1);

 System.out.println("\napple key exists: " + tm1.containsKey("apple"));
 System.out.println("two key exists: " + tm1.containsKey("two"));
 System.out.println("red value exists: " + tm1.containsValue("red"));
 System.out.println("2 value exists: " + tm1.containsValue(2));

 System.out.println("\nValue of three: " + tm1.get("three"));
 System.out.println("Value of four: " + tm1.get("four"));

 System.out.println("\nNo. of elements before removal: " + tm1.size());
 tm1.remove("one");
 System.out.println("No. of elements after removal: " + tm1.size());
 tm1.clear();
 System.out.println("No. of elements after clear(): " + tm1.size());
}




Null Pointer Exception

 http://way2java.com/exceptions/nullpointerexception/

Iterate over hashmap


public static void iterateOverHashmapGeneric(){


 HashMap<String, Integer> hm1 = new HashMap<String, Integer>();
 hm1.put("E", 69);
 hm1.put("A", 65);
 hm1.put("G", 71);
 hm1.put("C", 67);

 Set<String> mySet = hm1.keySet();
 System.out.print("foreach printing: ");
 for(String str : mySet)
 {
  System.out.print(str + ":" + hm1.get(str) + ", ");
 }

 HashMap<String, Integer> hm2 = new HashMap<String, Integer>();
 hm2.putAll(hm1);
 if(hm1.equals(hm2))
 {
  System.out.println("\n\nhm1 and hm2 contain the same elements");
 }

 HashMap<String, Integer> hm3 = (HashMap) hm1.clone();
 System.out.println("\nElements of hm3: " + hm3);   

}



A generics HashMap object hm1 is created that stores keys as strings and values as integers. With put() method elements are added.
Set<String> mySet = hm1.keySet();
     for(String str : mySet)
     {
       System.out.print(str + ":" + hm1.get(str) + ", ");
     }
With HashMap, Iterator cannot be used as Iterator stores elements of single entities but HashMap stores pairs. The new JDK 1.5 enhanced for loop (foreach) cannot be used straight away for the same reason. It is used indirectly. The keySet() returns all the keys of HashMap hm1. As keys are single entities, to iterate them, foreach loop is used. The str refers a key and using the key str, the value associated is retrieved with get() method.
HashMap<String, Integer> hm2 = new HashMap<String, Integer>();
     hm2.putAll(hm1);
     if(hm1.equals(hm2))
     {
       System.out.println("\n\nhm1 and hm2 contain the same elements");
     }
Another generics object hm2 is created and all the elements of hm1 are added at a time with putAll() method. equals() method is used to check both hm1 and hm2 contains the same elements are not. As they have same, the method returns true.
HashMap<String, Integer> hm3 = (HashMap) hm1.clone();
     System.out.println("\nElements of hm3: " + hm3);
Any Collection object including HashMap can be cloned. As the cloned object, hm3 and the hm1 occupy different locations and have their own set of values, they maintain perfect encapsulation.

Iterator vs ListIterator

http://way2java.com/collections/iterator-vs-listiterator/