- 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.)
- The constructor name must match the name of the class.
- Constructors must not have a return type.
- 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.
- If you don’t type a constructor into your class code, a default constructor will be automatically generated by the compiler.
- The default constructor is ALWAYS a no-arg constructor.
- 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 !
- 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.
- 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.
- A call to super() can be either a no-arg call or can include arguments passed to the super constructor.
- 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.
- You cannot make a call to an instance method, or access an instance variable, until after the super constructor runs.
- 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.)
- Abstract classes have constructors, and those constructors are always called when a concrete subclass is instantiated.
- Interfaces do not have constructors. Interfaces are not part of an object’s inheritance tree.
- The only way a constructor can be invoked is from within another constructor.
Thursday, 26 January 2012
Rules for constructors in java
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/
OOPS concepts – Introduction
There are three basic concepts of OOPS
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.
- Abstraction
- Encapsulation
- 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.
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.
http://way2java.com/collections/queue-programming/
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.
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
Following is the signature
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.
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.
Limitations of Stack Usage
There are two limitations for stack usage.
Following is the class signature
The java.util.Stack comes with five operations represented by five methods.
- 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.
- 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.
- 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.
- 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.
- 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()); }
There are two limitations for stack usage.
- 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.
- Another drawback is, the elements cannot be added or retrieved from the middle.
- 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()); }
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) + ", "); }
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);
Enumeration Interface
Enumeration interface is from java.util package introduced with JDK 1.0 version, the starting version of Java. It is used by many data structures (especially with legacy classes) to print their values. Following program illustrates.
In the above code, the elements() method of Vector returns an object of Enumeration. Following is the elements() method signature as defined in Vector class.
public Enumeration elements();
Observe, the elements() method returns an object of Enumeration. The above program gives a warning as program is designed for generics. But the program executes fine.
How Enumeration works?
The Enumeration interface comes with two methods.
public abstract boolean hasMoreElements();
public abstract Object nextElement();
The Enumeration object e contains all the elements of the Vector vect1. The Enumeration object e maintains a cursor over the elements. By default, the cursor is placed on the first element. The hasMoreElements() returns true if the cursor points to an element else false. If there exists an element (known by the true value), the control enters the while loop. In the while loop, the nextElement() returns the value (pointed by the cursor) and then pushes to the next element. Again the loop goes back and checks whether an element exists or not (known by the return value of hasMoreElements()) and then enters the loop. The nextElement() does its job. Like this, complete elements of the e object are returned. When cursor points to no element, the hasMoreElements() method returns false and the loop terminates.
The nextElement() method returns an object of Object class. If required, it can be casted to the respective element and used in the program. The following modified while loop, adds "great man" if the name is Rao.
We can make an analogy for nextElement() method. It is like read() method of FileInputStream. The read() method reads and returns the byte where the file pointer exists and then pushes the file pointer to the next byte.
import java.util.*; public class EnumerationDemo { public static void main(String args[]) { Vector vect1 = new Vector(); vect1.addElement("Raju"); vect1.addElement("Reddy"); vect1.addElement("Rao"); vect1.addElement("Ratnakar"); Enumeration e = vect1.elements(); while(e.hasMoreElements()) { Object obj1 = e.nextElement(); System.out.println(obj1); } } }
In the above code, the elements() method of Vector returns an object of Enumeration. Following is the elements() method signature as defined in Vector class.
public Enumeration elements();
Observe, the elements() method returns an object of Enumeration. The above program gives a warning as program is designed for generics. But the program executes fine.
How Enumeration works?
The Enumeration interface comes with two methods.
public abstract boolean hasMoreElements();
public abstract Object nextElement();
The Enumeration object e contains all the elements of the Vector vect1. The Enumeration object e maintains a cursor over the elements. By default, the cursor is placed on the first element. The hasMoreElements() returns true if the cursor points to an element else false. If there exists an element (known by the true value), the control enters the while loop. In the while loop, the nextElement() returns the value (pointed by the cursor) and then pushes to the next element. Again the loop goes back and checks whether an element exists or not (known by the return value of hasMoreElements()) and then enters the loop. The nextElement() does its job. Like this, complete elements of the e object are returned. When cursor points to no element, the hasMoreElements() method returns false and the loop terminates.
The nextElement() method returns an object of Object class. If required, it can be casted to the respective element and used in the program. The following modified while loop, adds "great man" if the name is Rao.
We can make an analogy for nextElement() method. It is like read() method of FileInputStream. The read() method reads and returns the byte where the file pointer exists and then pushes the file pointer to the next byte.
Sorting keys and values in Hashmap
Example shows how sorting operations on keys and values are done.
public static void sortingHashMapDemo(){ HashMap hm1 = new HashMap(); hm1.put("one", 1); hm1.put("thousand", 1000); hm1.put("ten", 10); hm1.put("hundred", 100); // SORTING KEYS Set mySet = hm1.keySet(); System.out.println("\nhm1 keys: " + mySet); TreeSet ts1 = new TreeSet(mySet); System.out.println("hm1 sorted keys: " + ts1); // SORTING VALUES Collection myCol = hm1.values(); System.out.println("\nhm1 values: " + myCol); TreeSet ts2 = new TreeSet(myCol); System.out.println("hm1 sorted values: " + ts2); // GET KEY FROM VALUE for(Object obj1 : mySet) { if(hm1.get(obj1).equals(10)) { System.out.println("10 value key is " + obj1); } } }
Wednesday, 18 January 2012
Collection methods
Map
obj = | m.put(key, val) | Creates mapping from key to val . It returns the previous value (or null) associated with the key. |
m.putAll(map2) | Adds all key-value entries from another map, map2. | |
Removing key-value pairs from a map | ||
m.clear() | Removes all elements from a Map | |
obj = | m.remove(key) | Deletes mapping from key to anything. Returns previous value (or null) associated with the key. |
Retrieving information from the map | ||
b = | m.containsKey(key) | Returns true if m contains a key key |
b = | m.containsValue(val) | Returns true if m contains val as one of the values |
obj = | m.get(key) | Returns value corresponding to key , or null if there is no mapping. If null has been stored as a value, use containsKey to see if there is a mapping. |
b = | m.isEmpty() | Returns true if m contains no mappings. |
i = | m.size() | Returns number of mappings in m . |
Retrieving all keys, values, or key-value pairs (necessary for iteration) | ||
set = | m.entrySet() | Returns set of Map.Entry values for all mappings. |
set = | m.keySet() | Returns Set of keys. |
col = | m.values() | Returns a Collection view of the values in m . |
TreeMap vs HashMap
After knowing Hashtable vs HashMap, now let us see the comparison of HashMap with TreeMap. Basically both are derived from Map interface and meant to store key/value pairs. But TreeMap inherits one more interface SortedMap and for this reason it attains the property of returning the elements in sorting order by default (irrespective of the addition of elements in any order).
By nature, all the classes derived from Map interface allow null values either as keys are values. Null keys are accepted only once because Map classes do not allow duplicate keys.
Similarities:
The concept of synchronization comes in multithreading. In multithreaded applications, there is every chance that multiple threads accessing the same source of data at the same time. This results in data corruption and data inconsistency. Synchronization avoids this by allowing only one thread to access the resource of data at a time.
That is, when one thread is modifying the data of Hashtable, the other thread cannot modify. The other thread should wait until the first one completes its job. This is done by acquiring the lock on Hashtable by the first thread. The lock will not be released until the first completes its job.
What is fail-fast?
The concept of fail-fast comes with iterators. When an Iterator object is created and iteration is going on, the HashMap elements cannot be modified (like addition or deletion of elements cannot be done). This is explained programmatically in ConcurrentModificationException.
Programs on HashMap and TreeMap are available at HashMap Tutorial and TreeMap Tutorial.
About Hashing and Hashcode
Comparing two strings letter by letter in a for loop is a time taking process. To make faster, the JVM converts each string into an integer number called hashcode. Different strings with different sequence of characters have different hashcodes. Comparison with integer numbers gives maximum performance. Usage of hashcode numbers for comparison, searching of duplicate elements and identification is faster.
Hashing is process of converting a string or object into a 32-bit integer number. Two objects are said to be equal if their hashcodes are same. hashCode() is used in combination of equals() method. When compared, hashing is done automatically by the JVM. Hashing, in data structures, is done implicitly in the basic operations with add(), contains(), remove() and size() etc. Hashing is more useful to compare the sets of large content.
By nature, all the classes derived from Map interface allow null values either as keys are values. Null keys are accepted only once because Map classes do not allow duplicate keys.
Similarities:
- The methods of both are not synchronized. Both are not thread-safe. But we can obtain a synchronized version as follows.
HashMap hm1 = new HashMap();
Now the methods of m1 are synchronized but still the methods of hm1 are not synchronized. So the programmer still has got a choice of using synchronized or unsynchronized map. This is the height of intelligence of Java designers in developing collection framework classes. It is a much matured framework.
Map m1 = Collections.synchronizedMap(hm1);
- Both do not support duplicate keys. If added it overrides the earlier (but not error or exception).
- Iterators of both are fail-fast.
- Allows null values for both keys and values (null key is allowed only once because no duplicate keys).
- HashMap is the direct implementation of Map whereas TreeMap comes with an intermittent SortedMap (see the above hierarchy).
- HashMap returns unordered values. TreeMap returns the elements in ascending order (known as natural order) of keys by default (the affect of deriving from SortedMap). TreeMap order can be customized using Comparator and Comparable interfaces.
- The performance of HapMap is higher than TreeMap because TreeMap requires minimum execution of two method calls to create a tree structure and to print the elements in natural order. The performance of HashMap can still be enhanced by the programmer by choosing optimum initial capacity and load factor, at the time of HashMap object creation itself, as per his requirements.
The concept of synchronization comes in multithreading. In multithreaded applications, there is every chance that multiple threads accessing the same source of data at the same time. This results in data corruption and data inconsistency. Synchronization avoids this by allowing only one thread to access the resource of data at a time.
That is, when one thread is modifying the data of Hashtable, the other thread cannot modify. The other thread should wait until the first one completes its job. This is done by acquiring the lock on Hashtable by the first thread. The lock will not be released until the first completes its job.
What is fail-fast?
The concept of fail-fast comes with iterators. When an Iterator object is created and iteration is going on, the HashMap elements cannot be modified (like addition or deletion of elements cannot be done). This is explained programmatically in ConcurrentModificationException.
Programs on HashMap and TreeMap are available at HashMap Tutorial and TreeMap Tutorial.
About Hashing and Hashcode
Comparing two strings letter by letter in a for loop is a time taking process. To make faster, the JVM converts each string into an integer number called hashcode. Different strings with different sequence of characters have different hashcodes. Comparison with integer numbers gives maximum performance. Usage of hashcode numbers for comparison, searching of duplicate elements and identification is faster.
Hashing is process of converting a string or object into a 32-bit integer number. Two objects are said to be equal if their hashcodes are same. hashCode() is used in combination of equals() method. When compared, hashing is done automatically by the JVM. Hashing, in data structures, is done implicitly in the basic operations with add(), contains(), remove() and size() etc. Hashing is more useful to compare the sets of large content.
Tuesday, 17 January 2012
Reading and writing data from Excel sheet using JExcel API
Using Java we can read the data from Excel sheets by creating type1 driver , but here we are taking help of JExcelapi we can able to read data directly from the Excel sheets.
Steps to be follow:
Step 1:
download JExcel api from here
Step2:
after downloading extract the zip file.
make jxl.jar available to your class path.
Step 3:
create a Excel sheet with some data
Step 4:
in this step we are reading data from the Excel sheet.
use the below java code:
Steps to be follow:
Step 1:
download JExcel api from here
Step2:
after downloading extract the zip file.
make jxl.jar available to your class path.
Step 3:
create a Excel sheet with some data
Step 4:
in this step we are reading data from the Excel sheet.
use the below java code:
package com.vaani.excel.jexcel; import java.io.File; import java.io.IOException; import java.util.Date; import jxl.*; import jxl.read.biff.BiffException; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.Number; public class ReadWriteInExcel { public static void readExcelFile() throws IOException, BiffException { Workbook workbook = Workbook.getWorkbook( new File("---/././file.xls")); // my excel sheet name is contacts, iam given the complete path.
// iam reading data from the sheet1 Sheet sheet = workbook.getSheet(0); // here iam reading the data of 1st column data up three cells Cell a1 = sheet.getCell(0,0); Cell b2 = sheet.getCell(0,1); Cell c2 = sheet.getCell(0,2); //getting the data from cells String stringa1 = a1.getContents(); String stringb2 = b2.getContents(); String stringc2 = c2.getContents(); //printing the data System.out.println("a1–>"+stringa1); System.out.println("b2–>"+stringb2); System.out.println("c3–>"+stringc2); } public static void writeInExcelFile(String args[])
throws IOException, WriteException { // STEP 1: // the first step is to create a writable workbook using the
factory method on the Workbook class. WritableWorkbook workbook = Workbook.createWorkbook(
new File("/some file.xls")); //test.xls is my work book // STEP 2: //// sheet name
WritableSheet sheet = workbook.createSheet("First Sheet",0); //STEP 3: //adding(inserting) name to the sheet at location (0,2) Label label = new Label(0,2,"A label record"); sheet.addCell(label); //adding number to the sheet at location (1,2) Number number = new Number(1,2,3.1459); sheet.addCell(number); //Step 4: //close the all opened connections workbook.write(); workbook.close(); } }
Monday, 16 January 2012
Modulus operator in java
Unlike C, Java allows using the % for both integer and floating point and (unlike C89 and C++) it is well-defined for all inputs (including negatives):
So for your example, 0.5/0.3 = 1.6... . q has the same sign (positive) as 0.5 (the dividend), and the magnitude is 1 (integer with largest magnitude not exceeding magnitude of 1.6...), and r = 0.5 - (0.3 * 1) = 0.2
x = n % d
n - dividend
d - divisor
The result of a floating-point remainder operation is determined by the rules of IEEE arithmetic:- If either operand is NaN, the result is NaN
...i.e. x=NaN, if n or d is NaN - If the result is not NaN, the sign of the result equals the sign of the dividend.
- If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
- If the dividend is finite and the divisor is an infinity, the result equals the dividend.
- If the dividend is a zero and the divisor is finite, the result equals the dividend.
- In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from the division of a dividend n by a divisor d is defined by the mathematical relation r=n-(d·q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d.
So for your example, 0.5/0.3 = 1.6... . q has the same sign (positive) as 0.5 (the dividend), and the magnitude is 1 (integer with largest magnitude not exceeding magnitude of 1.6...), and r = 0.5 - (0.3 * 1) = 0.2
Arrays in Java
Java Array Declaration
Java Array Instantiation
Shorthand method
Java has a shorthand to create an array object and supply initial values at the same time. Here's an example of the syntax at work:
Notice that you do not call new when you use this syntax.
Memory Allocation and initialization
No need to pass length of array to function unlike in cpp
To find the number of elements of an array, use array.length. For example,
Iterating over array
Java provides 2 ways of iterating over arrays.
Traditional or old style iteration
New style
JDK 5.0 introduces a powerful looping construct that allows you to loop through each element in an array (as well as other collections of elements) without having to fuss with index values.
So here we are taking element from array a and dumping it on output.
Note: println prints each element of the array a on a separate line.
You should read this loop as "for each element in a". The designers of the Java language considered using keywords such as foreach and in. But this loop was a late addition to the Java language, and in the end nobody wanted to break old code that already contains methods or variables with the same names (such as System.in).
"for each" vs for
The loop variable of the "for each" loop traverses the elements of the array, not the index values.
The "for each" loop is a pleasant improvement over the traditional loop if you need to process all elements in a collection. However, there are still plenty of opportunities to use the traditional for loop. For example, you may not want to traverse the entire collection, or you may need the index value inside the loop.
Jakarta ArrayUtils class: http://jakarta.apache.org/commons/lang/api/index.html
Java Array Instantiation
Shorthand method
Java has a shorthand to create an array object and supply initial values at the same time. Here's an example of the syntax at work:
int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };
Memory Allocation and initialization
char[] s = new char[10]; for( int i=0; i<26; i++){ s[i] = (char) ('A' + i); }Array of references can be made similarly:
Point[] p = new Point[26];
No need to pass length of array to function unlike in cpp
To find the number of elements of an array, use array.length. For example,
for (int i = 0; i < a.length; i++) System.out.println(a[i]);
Iterating over array
Java provides 2 ways of iterating over arrays.
Traditional or old style iteration
for (int i = 0; i < a.length; i++) System.out.println(a[i]);
New style
JDK 5.0 introduces a powerful looping construct that allows you to loop through each element in an array (as well as other collections of elements) without having to fuss with index values.
for (variable : collection)
statement
sets the given variable to each element of the collection and then executes the statement (which, of course, may be a block). The collection expression must be an array or an object of a class that implements the Iterable interface, such as ArrayList For example,
for (int element : a) System.out.println(element);
So here we are taking element from array a and dumping it on output.
Note: println prints each element of the array a on a separate line.
You should read this loop as "for each element in a". The designers of the Java language considered using keywords such as foreach and in. But this loop was a late addition to the Java language, and in the end nobody wanted to break old code that already contains methods or variables with the same names (such as System.in).
"for each" vs for
The loop variable of the "for each" loop traverses the elements of the array, not the index values.
The "for each" loop is a pleasant improvement over the traditional loop if you need to process all elements in a collection. However, there are still plenty of opportunities to use the traditional for loop. For example, you may not want to traverse the entire collection, or you may need the index value inside the loop.
Jakarta ArrayUtils class: http://jakarta.apache.org/commons/lang/api/index.html
Sunday, 15 January 2012
What are variables default values?
Variables declared in methods and in blocks are called local variables. Local variable are not initialized when they are created at method invocation. Therefore, a local variable must be initialized explicitly before being used. Otherwise the compiler will flag it as error when the containing method or block is executed.
Example:
public class SomeClassName{
public static void main(String args[]){ int total; System.out.println("The incremented total is " + total + 3); //(1)
}}
The compiler complains that the local variable total used in println statement at (1) may not be initialized.
Initializing the local variable total before usage solves the problem:
public class SomeClassName{
public static void main(String args[]){int total = 45; //Local variable initialized with value 45 System.out.println("The incremented total is " + total+ 3); //(1)
}}
An instance variable is initialized with the default value of its type each time the class is instantiated, that is for every object created from the class.
A static variable is initialized with the default value of its type when the class is first loaded.
Note: Reference fields are always initialized with the value null if no initialization is provided
Example of default values for fields
public class House{
// Static variable
static long similarHouses; //Default value 0L when class is loaded.
// Instance variables
String houseName; //Implicitly set to default value null
int numberOfRooms=5; // Explicitly set to 5
boolean hasPet; // Implicitly set to default value false
//..
}
Example:
public class SomeClassName{
public static void main(String args[]){ int total; System.out.println("The incremented total is " + total + 3); //(1)
}}
The compiler complains that the local variable total used in println statement at (1) may not be initialized.
Initializing the local variable total before usage solves the problem:
public class SomeClassName{
public static void main(String args[]){int total = 45; //Local variable initialized with value 45 System.out.println("The incremented total is " + total+ 3); //(1)
}}
Fields initialization
If no initialization is provided for an instance or static variable, either when declared or in an initializer block, then it is implicitly initialized with the default value of its type.An instance variable is initialized with the default value of its type each time the class is instantiated, that is for every object created from the class.
A static variable is initialized with the default value of its type when the class is first loaded.
Data Type | Default Value |
boolean | false |
char | '/u0000' |
Integer(byte,short,int,long) | 0L for long, 0 for others |
Floating-point(float,double) | 0.0F or 0.0D |
reference type | null |
Note: Reference fields are always initialized with the value null if no initialization is provided
Example of default values for fields
public class House{
// Static variable
static long similarHouses; //Default value 0L when class is loaded.
// Instance variables
String houseName; //Implicitly set to default value null
int numberOfRooms=5; // Explicitly set to 5
boolean hasPet; // Implicitly set to default value false
//..
}
How to declare and initialize a variable
A variable in Java has a type, name and a value. A variable may store of value of either:
- a primitive data type such as int, boolean, char.
or
- a reference to an object, also called reference variable.
for example:
int i; //variable i that can store an int value. boolean isDone; //Variable isDone that can store a boolean value.//Variables a, f and r that can store a char value each:
char a,f,r;
//Equivalent to the three separate declarations: char a; char f; char r;
What we just deed above is called variable declaration. By declaring variable we are implicitly allocating memory for these variables and determining the value types that can be stored in them.
So, in the example above, we named a variable: isDone that can store a boolean value, but not initialized yet.
Giving a variable a value when declared is called initialization. Further, we can declare and initialize a variable in one go. For example, we could have declared and initialized our variables of the previous example:
int i = 101; //variable i initialized with the value 101://variable isDone initialized with the boolean value true.
boolean isDone = true;
// variables a,f and r initialized with the values 'a','f' and 'r' //respectively: char a = 'a', f='f', r='r';
// equivalent to:
char a = 'a';char f = 'f';char r = 'r';
Analogous to declaring variables to denote primitive values, we can declare a variable denoting an object reference, that's; a variable having one of the following reference types: a class, an array, or an interface.
For instance (see also Class Instantiation ):
//declaring a redCar and a blueCar of class Car.
Car redCar, blueCar;
Please note that declarations above do not create any object of type Car. These are just variables that can store references to objects of class Car but no reference is created yet.
A reference variable has to be instantiated before being used. So:// declaring and initializing the redCar reference variable
Car redCar=new Car("red");
An object of class Car is created using the keyword new together with the Constructor call Car("red"), then stored in the variable redCar which is now ready to be manipulated.
- a primitive data type such as int, boolean, char.
or
- a reference to an object, also called reference variable.
for example:
int i; //variable i that can store an int value. boolean isDone; //Variable isDone that can store a boolean value.//Variables a, f and r that can store a char value each:
char a,f,r;
//Equivalent to the three separate declarations: char a; char f; char r;
What we just deed above is called variable declaration. By declaring variable we are implicitly allocating memory for these variables and determining the value types that can be stored in them.
So, in the example above, we named a variable: isDone that can store a boolean value, but not initialized yet.
Giving a variable a value when declared is called initialization. Further, we can declare and initialize a variable in one go. For example, we could have declared and initialized our variables of the previous example:
int i = 101; //variable i initialized with the value 101://variable isDone initialized with the boolean value true.
boolean isDone = true;
// variables a,f and r initialized with the values 'a','f' and 'r' //respectively: char a = 'a', f='f', r='r';
// equivalent to:
char a = 'a';char f = 'f';char r = 'r';
Analogous to declaring variables to denote primitive values, we can declare a variable denoting an object reference, that's; a variable having one of the following reference types: a class, an array, or an interface.
For instance (see also Class Instantiation ):
//declaring a redCar and a blueCar of class Car.
Car redCar, blueCar;
Please note that declarations above do not create any object of type Car. These are just variables that can store references to objects of class Car but no reference is created yet.
A reference variable has to be instantiated before being used. So:// declaring and initializing the redCar reference variable
Car redCar=new Car("red");
An object of class Car is created using the keyword new together with the Constructor call Car("red"), then stored in the variable redCar which is now ready to be manipulated.
Java Literals
A constant value in a program is denoted by a literal. Literals represent numerical (integer or floating-point), character, boolean or string values.
Example of literals:
Integer literals:
33 0 -9
Floating-point literals:
.3 0.3 3.14
Character literals:
'(' 'R' 'r' '{'
Boolean literals:(predefined values)
true false
String literals:
"language" "0.2" "r" ""
Note: Three reserved identifiers are used as predefined literals:
true and false representing boolean values.
null representing the null reference.
Let's have a closer look at our literals and type of data they can represent:
Integer data types consist of the following primitive data types: int,long, byte, and short.
int is the default data type of an integer literal.
An integer literal, let's say 3000, can be specified as long by appending the suffix L (or l) to the integer value: so 3000L (or 3000l) is interpreted as a long literal.
There is no suffix to specify short and byte literals directly; 3000S , 3000B, 3000s, 3000b
Integer literals can also be specified as octal (base 8), or hexadecimal (base 16). Octal and hexadecimal have 0 and 0x prefix respectively. So 03 and 0x3 are representation of integer three in octal and hexa-decimal respectively.
The default data type of floating-point literals is double, but you can designate it explicitly by appending the D (or d) suffix. However, the suffix F (or f) is appended to designate the data type of a floating-point literal as float.
We can also specify a floating-point literal in scientific notation using Exponent (short E or e), for instance: the double literal 0.0314E2 is interpreted as
0.0314 *10² (i.e 3.14).
Examples of double literals:
0.0 0.0D 0d0.7 7D .7d
9.0 9. 9D
6.3E-2 6.3E-2D 63e-1
Examples of float literals:
0.0f 0f 7F .7f9.0f 9.F 9f
6.3E-2f 6.3E-2F 63e-1f
Note: The decimal point and the exponent are both optional and at least one digit must be specified.
Note: Characters in Java are represented by the 16-bit Unicode character set.
Examples of string literals:
"false or true"
"result = 0.01"
"a"
"Java is an artificial language"
String literals are objects of the class String, so all string literals have the type String.
Escape (aka backslash) sequences are used inside literal strings to allow print formatting as well as preventing certain characters from causing interpretation errors. Each escape sequence starts with a backslash. The available sequences are:
Example of literals:
Integer literals:
33 0 -9
Floating-point literals:
.3 0.3 3.14
Character literals:
'(' 'R' 'r' '{'
Boolean literals:(predefined values)
true false
String literals:
"language" "0.2" "r" ""
Note: Three reserved identifiers are used as predefined literals:
true and false representing boolean values.
null representing the null reference.
Let's have a closer look at our literals and type of data they can represent:
Integer Literals
Integer data types consist of the following primitive data types: int,long, byte, and short.
int is the default data type of an integer literal.
An integer literal, let's say 3000, can be specified as long by appending the suffix L (or l) to the integer value: so 3000L (or 3000l) is interpreted as a long literal.
There is no suffix to specify short and byte literals directly; 3000S , 3000B, 3000s, 3000b
Integer literals can also be specified as octal (base 8), or hexadecimal (base 16). Octal and hexadecimal have 0 and 0x prefix respectively. So 03 and 0x3 are representation of integer three in octal and hexa-decimal respectively.
Floating-point Literals
Floating-point data consist of float and double types.The default data type of floating-point literals is double, but you can designate it explicitly by appending the D (or d) suffix. However, the suffix F (or f) is appended to designate the data type of a floating-point literal as float.
We can also specify a floating-point literal in scientific notation using Exponent (short E or e), for instance: the double literal 0.0314E2 is interpreted as
0.0314 *10² (i.e 3.14).
Examples of double literals:
0.0 0.0D 0d0.7 7D .7d
9.0 9. 9D
6.3E-2 6.3E-2D 63e-1
Examples of float literals:
0.0f 0f 7F .7f9.0f 9.F 9f
6.3E-2f 6.3E-2F 63e-1f
Note: The decimal point and the exponent are both optional and at least one digit must be specified.
Boolean Literals
As mentioned before, true and false are reserved literals representing the truth-values true and false respectively. Boolean literals fall under the primitive data type: boolean.Character Literals
Character literals have the primitive data type character. A character is quoted in single quote (').Note: Characters in Java are represented by the 16-bit Unicode character set.
String Literals
A string literal is a sequence of characters which has to be double-quoted (") and occur on a single line.Examples of string literals:
"false or true"
"result = 0.01"
"a"
"Java is an artificial language"
String literals are objects of the class String, so all string literals have the type String.
Escape (aka backslash) sequences are used inside literal strings to allow print formatting as well as preventing certain characters from causing interpretation errors. Each escape sequence starts with a backslash. The available sequences are:
Seq | Usage | Seq | Usage |
---|---|---|---|
\b | backspace | \\ | backslash |
\f | formfeed | \" | double quote |
\n | newline | \' | single quote |
\r | carriage return | \### | Octal encoded character |
\t | horizontal tab | \uHHHH | Unicode encoded character |
Java primitive data types
In Java, primitive data types can be categorized within three types:
A primitive data value can't act as an object in a Java program unless wrapped. Therefore, each primitive data type has a corresponding wrapper class that can be used to represent its value as an object.
- Integral types:
- signed integers : byte,short,int and long.
- unsigned character values, char,denoting all the 65536 characters in the 16-bit Unicode character set.
- Floating-point types: float and double, representing fractional signed numbers.
- Boolean type: boolean, representing logical values, the two literals, true or false.
A primitive data value can't act as an object in a Java program unless wrapped. Therefore, each primitive data type has a corresponding wrapper class that can be used to represent its value as an object.
Playing with double datatype using Java
Do you guess the output values of the following code snippets (in Java) ? .
Here is the output:
Have you noticed the values of d8, d9 and d10?. The output value is in E (exponential) format. Java is internally doing this conversion while convert the datatype double to String. If the value is greater than or equal to 10-3 but less than 107, then the output will be normal. Otherwise the value will be in Exponential.
To print the values all in normal format, use the "java.text.DecimalFormat" class. Check the following code snippet.
Refer the following URL to get the more details about the Double,.
double d5 =99999.99;
double d6 =999999.99;
double d7 =9999999.99;
double d8 =99999999.99;
double d9 =999999999.99;
double d10=9999999999.99;
System.out.println("d5 ="+d5);
System.out.println("d6 ="+d6);
System.out.println("d7 ="+d7);
System.out.println("d8 ="+d8);
System.out.println("d9 ="+d9);
System.out.println("d10="+d10);
Here is the output:
d5 =99999.99
d6 =999999.99
d7 =9999999.99
d8 =9.999999999E7
d9 =9.9999999999E8
d10=9.99999999999E9
Have you noticed the values of d8, d9 and d10?. The output value is in E (exponential) format. Java is internally doing this conversion while convert the datatype double to String. If the value is greater than or equal to 10-3 but less than 107, then the output will be normal. Otherwise the value will be in Exponential.
To print the values all in normal format, use the "java.text.DecimalFormat" class. Check the following code snippet.
The output is
DecimalFormat d = new DecimalFormat("##.##");
System.out.println("d5 ="+d.format(d5));
System.out.println("d6 ="+d.format(d6));
System.out.println("d7 ="+d.format(d7));
System.out.println("d8 ="+d.format(d8));
System.out.println("d9 ="+d.format(d9));
System.out.println("d10="+d.format(d10));
d5 =99999.99
d6 =999999.99
d7 =9999999.99
d8 =99999999.99
d9 =999999999.99
d10=9999999999.99
Refer the following URL to get the more details about the Double,.
Saturday, 14 January 2012
Generic class names to avoid
Overview
Java (Oracle Java update 2) has many classes with the same generic name. To avoid further confusion, I suggest avoiding these names if you can.Most repeated
The following class names are repeated, 19 Handler, 16 Messages, 13 Util, 10 Element, 8 Attribute, 7 SecuritySupport, 7 Node, 6 Provider, 6 Header, 6 FactoryFinder, 6 Document. 5 SOAPBinding, 5 Repository, 5 Ref, 5 ORB, 5 Name, 5 Constants, 5 Connection, 5 Comment, 5 Binding, 5 Attributes,This excludes the Apache XML library which repeats many names. If you include these libraries there are 26 classes called SecuritySupport.
Four times
Window, Version, Utility, Timer, Text, State, Signature, ServiceName, ServiceConfigurationError, Service, ResourceLoader, Queue, Policy, Parser, Operation, NativeLibLoader, Message, Label, JSObject, GetPropertyAction, FactoryFinder$ConfigurationError, Event, ConstantPool, AppletAudioClip, Action,Three times
XMLWriter, Wrapper, WildcardTypeImpl, Visitor, Validator, Types, TypeMismatch, TypeInfo, Type, Trace, Token, Timestamp, Target, Symbol, StyleSheet, SOAPFault, SOAPConstants, Scope, Schema, ResourceManager, Resource, Resolver, Request, Reference, Properties, ProgressMonitor, PrincipalImpl, Principal, Port, PooledConnection, Pool, Pipe, Patcher, ParseException, OutputStream, ObjectStreamField, Navigator, NamespaceSupport$Context, NamespaceSupport, MimeType, MemoryCache, MarshalException, Manifest, Main, Location, List, JarVerifier, IOR, Invoker, InvalidName, Introspector, InputStream, Import, ImageCache, HTMLDocument, HTMLCollection, Headers, FinalArrayList, Filter, FileSystem, FactoryImpl, Extension, EventListener, ErrorHandler, Entity, EncryptedPrivateKeyInfo, Delegate, DataSource, CurrentOperations, CurrentHelper, Current, Counter, Context, ContentType, Config, Code, CharacterData, Certificate, CacheTable, Cache, Bridge, Base64, Authenticator, AttributeList, ArrayType, Array, AppletAudioClip$1, Annotation,Appearing twice
Too many to mention.Friday, 13 January 2012
Exception Wrapping for persistence
Data can be stored in various ways, for example:
Removing the compilation point of view, lets look at the design point. Then consider a typical J2EE application that has a simple web layer, a business layer and a database layer. If some SQL query in the database layer goes completely wrong I will get an SQLException of some sort. In your point of view the web application (being the topmost layer) will catch this exception in the end.
This defeats the entire purpose of having a multitier (3+) architecture. I'm now dependent on the database layer in the web layer, because all exceptions are thrown all the way upwards.
The point of the PersistenceException is that it keeps the tiers independent from each other, except for the tier beneath it. The web layer doesn't care if it's an SQLException. It only needs to know something went wrong with the business logic, and more specifically with the persistence of business data objects.
In any case, the 'business code' knows more of what to do than the layers above it. If it can't do anything meaningful with it, you can either log it or perform some other action. The question is: what would a layer above it (eg. the web layer) know more of what to do than the business layer?
- a relational database
- text files
- on the web (for example, fetching the weather forecast from a web site)
Removing the compilation point of view, lets look at the design point. Then consider a typical J2EE application that has a simple web layer, a business layer and a database layer. If some SQL query in the database layer goes completely wrong I will get an SQLException of some sort. In your point of view the web application (being the topmost layer) will catch this exception in the end.
This defeats the entire purpose of having a multitier (3+) architecture. I'm now dependent on the database layer in the web layer, because all exceptions are thrown all the way upwards.
The point of the PersistenceException is that it keeps the tiers independent from each other, except for the tier beneath it. The web layer doesn't care if it's an SQLException. It only needs to know something went wrong with the business logic, and more specifically with the persistence of business data objects.
In any case, the 'business code' knows more of what to do than the layers above it. If it can't do anything meaningful with it, you can either log it or perform some other action. The question is: what would a layer above it (eg. the web layer) know more of what to do than the business layer?
Exceptions Methods
ollowing is the list of important medthods available in the Throwable class.
SN | Methods with Description |
---|---|
1 | public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. |
2 | public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. |
3 | public String toString() Returns the name of the class concatenated with the result of getMessage() |
4 | public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream. |
5 | public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. |
6 | public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace. |
Effective Java Exception handling
1. Use checked exceptions when you know that or you can recover from the exception without any side affects.
2. The best use of exceptions is to translate exception in the calling method to the exception which is more appropriate for it and you should let the cause of the exception flow from the called methods to the calling methods.
For this you should have one of the constructors of your Exception classes like
You can also use the Throwable.initCause method for this if you don’t have the constructor like the one above.
3. Don’t use the 2nd point too much if the lower level method can get away with the exception, then you should do that. Don’t overload the calling methods too much to handle the exceptions thrown by the lower methods.
4. If you are declaring your own exception class you can always include some methods or attributes which can be used to convey more about the exception when it occurs.
5. Try to reuse exceptions (comes generally when you are creating your own API). The most reusabel exceptions are
IllegalArgumentException, IllegalStateException, NullPointerException, IndexArrayOutOfBounds and some more.
6. Most importantly, use Exceptions only for Exceptional conditions. Don’t write your logic which is based on exceptions. For example, don’t do like this
7. If rather than Exception you can have state testing method before actually using a state-dependent method like checking iterator.hasNext() before executing the iterator.next() method is more appropriate.
8. All of the unchecked throwables you implement should subclass RuntimeException (directly or indirectly).
9. Use runtime exceptions to indicate programming errors. The great majority of runtime exceptions indicate precondition violations. A precondition violation is simply a failure by the client of an API to adhere to the contract established by the API specification. For example, the contract for array access specifies that the array index must be between zero and the array length minus one. ArrayIndexOutOfBoundsException indicates that this precondition was violated.
10. Always declare checked exceptions individually, and document precisely the conditions under which each one is thrown using the Javadoc @throws tag. Don’t take the shortcut of declaring that a method throws some superclass of multiple exception classes that it can throw. As an extreme example, never declare that a method “throws Exception” or, worse yet, “throws Throwable.”
11.Use the Javadoc @throws tag to document each unchecked exception that a method can throw, but do not use the throws keyword to include unchecked exceptions in the method declaration. It is important that the programmers using your API be aware of which exceptions are checked and which are unchecked, as their responsibilities differ in these two cases. The documentation generated by the Javadoc @throws tag in the absence of the method header generated by the throws declaration provides a strong visual clue to help the programmer distinguish checked exceptions from unchecked.
12. If an exception is thrown by many methods in a class for the same reason, it is acceptable to document the exception in the class’s documentation comment rather than documenting it individually for each method. A common example is NullPointerException. It is fine for a class’s documentation comment to say, “All methods in this class throw a NullPointerException if a null object reference is passed in any parameter,” or words to that effect.
13. To capture the failure, the detail message of an exception should contain the values of all parameters and fields that “contributed to the exception. You must write the toString() method of your exception carefully.
14. Failure Atomicity(Object remains in consistence state after a failure)-
ways to achieve failure atomicity:
a. A closely related approach to achieving failure atomicity is to order the computation so that any part that may fail takes place before any part that modifies the object.
b. This approach is a natural extension of the previous one when arguments cannot be checked without performing a part of the computation.
c. A third and far less common approach to achieving failure atomicity is to write recovery code that intercepts a failure that occurs in the midst of an operation and causes the object to roll back its state to the point before the operation began. This approach is used mainly for durable (disk-based) data structures.
d.A final approach to achieving failure atomicity is to perform the operation on a temporary copy of the object and to replace the contents of the object with the temporary copy once the operation is complete. This approach occurs naturally when the computation can be performed more quickly once the data has been stored in a temporary data structure. For example, Collections.sort dumps its
input list into an array prior to sorting to reduce the cost of accessing elements in the inner loop of the sort. This is done for performance, but as an added benefit, it ensures that the input list will be untouched if the sort fails.
As a rule, any generated exception that is part of a method’s specification should leave the object in the same state it was in prior to the method invocation. Where this rule is violated, the API documentation should clearly indicate what state the object will be left in.
15. An empty catch block defeats the purpose of exceptions, which is to force you to handle exceptional conditions. At the very
least, the catch block should contain a comment explaining why it is appropriate to ignore the exception.
2. The best use of exceptions is to translate exception in the calling method to the exception which is more appropriate for it and you should let the cause of the exception flow from the called methods to the calling methods.
For this you should have one of the constructors of your Exception classes like
1: // Exception with chaining-aware constructor
2: class HigherLevelException extends Exception {
3: HigherLevelException(Throwable cause) {
4: super(cause);
5: }
6: }
3. Don’t use the 2nd point too much if the lower level method can get away with the exception, then you should do that. Don’t overload the calling methods too much to handle the exceptions thrown by the lower methods.
4. If you are declaring your own exception class you can always include some methods or attributes which can be used to convey more about the exception when it occurs.
5. Try to reuse exceptions (comes generally when you are creating your own API). The most reusabel exceptions are
IllegalArgumentException, IllegalStateException, NullPointerException, IndexArrayOutOfBounds and some more.
6. Most importantly, use Exceptions only for Exceptional conditions. Don’t write your logic which is based on exceptions. For example, don’t do like this
1: // wrong usage of exception handling
2: try {
3: someObject.someMethod();
4: } catch (NullPointerException npe)
5: {
6: // other code
7: }
8. All of the unchecked throwables you implement should subclass RuntimeException (directly or indirectly).
9. Use runtime exceptions to indicate programming errors. The great majority of runtime exceptions indicate precondition violations. A precondition violation is simply a failure by the client of an API to adhere to the contract established by the API specification. For example, the contract for array access specifies that the array index must be between zero and the array length minus one. ArrayIndexOutOfBoundsException indicates that this precondition was violated.
10. Always declare checked exceptions individually, and document precisely the conditions under which each one is thrown using the Javadoc @throws tag. Don’t take the shortcut of declaring that a method throws some superclass of multiple exception classes that it can throw. As an extreme example, never declare that a method “throws Exception” or, worse yet, “throws Throwable.”
11.Use the Javadoc @throws tag to document each unchecked exception that a method can throw, but do not use the throws keyword to include unchecked exceptions in the method declaration. It is important that the programmers using your API be aware of which exceptions are checked and which are unchecked, as their responsibilities differ in these two cases. The documentation generated by the Javadoc @throws tag in the absence of the method header generated by the throws declaration provides a strong visual clue to help the programmer distinguish checked exceptions from unchecked.
12. If an exception is thrown by many methods in a class for the same reason, it is acceptable to document the exception in the class’s documentation comment rather than documenting it individually for each method. A common example is NullPointerException. It is fine for a class’s documentation comment to say, “All methods in this class throw a NullPointerException if a null object reference is passed in any parameter,” or words to that effect.
13. To capture the failure, the detail message of an exception should contain the values of all parameters and fields that “contributed to the exception. You must write the toString() method of your exception carefully.
14. Failure Atomicity(Object remains in consistence state after a failure)-
ways to achieve failure atomicity:
a. A closely related approach to achieving failure atomicity is to order the computation so that any part that may fail takes place before any part that modifies the object.
b. This approach is a natural extension of the previous one when arguments cannot be checked without performing a part of the computation.
c. A third and far less common approach to achieving failure atomicity is to write recovery code that intercepts a failure that occurs in the midst of an operation and causes the object to roll back its state to the point before the operation began. This approach is used mainly for durable (disk-based) data structures.
d.A final approach to achieving failure atomicity is to perform the operation on a temporary copy of the object and to replace the contents of the object with the temporary copy once the operation is complete. This approach occurs naturally when the computation can be performed more quickly once the data has been stored in a temporary data structure. For example, Collections.sort dumps its
input list into an array prior to sorting to reduce the cost of accessing elements in the inner loop of the sort. This is done for performance, but as an added benefit, it ensures that the input list will be untouched if the sort fails.
As a rule, any generated exception that is part of a method’s specification should leave the object in the same state it was in prior to the method invocation. Where this rule is violated, the API documentation should clearly indicate what state the object will be left in.
15. An empty catch block defeats the purpose of exceptions, which is to force you to handle exceptional conditions. At the very
least, the catch block should contain a comment explaining why it is appropriate to ignore the exception.
Subscribe to:
Posts (Atom)