Thursday, 1 August 2013

Best Practices to write good Java code

Good java code should be readable and self explanatory to others.
In order to write a good java code,following things are need to be taken care of-

1) Variable Name- should be meaningful(related to context) and should be short.
   avoid hyphen,underscore while declaring variable.
    For ex: int sum,float temperature,double averageSum.

2) If variable name is long,use camel casing. for ex:numberOfRows

3) Class Name- should be noun not verb.It should be descriptive. For ex:ReadMailbox

4) Interface Name -Define Interface names which represents adjective.For ex:Versionable

5) Method Name– Should represent Verb. For ex: getHashItem() , addProject()

6) Comments-Should be written in few words and specific to the topic.

    a)Use implementation comments inside the method  or describing variable names, method line instead of documentation/block comment.
// This code check for valid value of tax if () { }

   b)Use documentation block comment to describe method name or class.

 /** This method retrieves project list  
 public List<String> retrieveProjectList() {  
7) The code should be properly indented and formatted so that it should be readable to programmers.

Thursday, 25 July 2013

Quick overview of collection concepts


collection - represents any data structures in which objects are stored and can be iterated.
Collection-which is actually the java.util.Collection interface from which Set, List, and Queue extend.
Collections-is the java.util.Collections class that holds a pile of static utility methods for use with collections.

LIST Interface-It provides ordered collection of elements.But it can contain duplicate elements.
ArrayList - A growable array. it is an ordered collection (by index), but not sorted.
Vector - Same as an ArrayList, but Vector methods are synchronized for thread safety.
LinkedList - LinkedList is ordered by index position, like ArrayList, except that the elements are doubly-linked to one another. Good for implementing stack and queue.

SET Interface- A Set cares about uniqueness—it doesn't allow duplicates.
HashSet - unsorted, unordered Set.
LinkedHashSet - A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements.
TreeSet - The TreeSet is one of two sorted collections (the other being TreeMap).

MAP Interface- A Map cares about unique identifiers. You map a unique key (the ID) to a specific value, where both the key and the value are, of course, objects.
HashMap - The HashMap gives you an unsorted, unordered Map. allows one null key and multiple null values in a collection.
Hashtable - Hashtable is the synchronized counterpart to HashMap. Hashtable doesn't let you have anything that's null.
LinkedHashMap - maintains insertion order (or, optionally, access order). Although it will be somewhat slower than HashMap for adding and removing elements, you can expect faster iteration with a LinkedHashMap.
TreeMap - It is a Sorted Map.

equals() method-
The equals() method in class Object uses only the == operator for comparisons, so unless you override equals(), two objects are considered equal only if the two references refer to the same object.
x.equals(y) == true => x.hashCode() == y.hashCode() [Required]
x.hashCode() != y.hashCode() => x.equals(y) == false [Required]

java.util.Comparator Interface -The Comparator interface gives you the capability to sort a given collection any number of different ways.
java.lang.Comparable Interface-The Comparable interface is used by the Collections.sort() method and the java.util.Arrays.sort() method to sort Lists and arrays of objects, respectively. To implement Comparable, a class must implement a single method, compareTo().

What is the differnce between String and StringBuffer class?

The basic differnece between String and StringBuffer class is String is immutable(means value stored in string object cannot be changed) where as StringBuffer is not.

Whenever you do any changes to your String object,it creates a new string object and does not change the existing object.

For ex:

So suppose you declare a String object:

 String test= “Hello”;  

Next, you want to append “Guest” to the same String. What do you do?


When you print the contents of test the output will be “Hello Guest”. Although we made use of the same object(test), internally a new object was created in the process. So, if you were to do some string operation involving an append or trim or some other method call to modify your string object, you would really be creating those many new objects of class String.This creates a performance issue.

In order to avoid this performance issue ,we use StringBuffer/StringBuilder class to efficiently use append and other string operations.

Oops Concepts

Q1) What is polymorphism?
Ans) The abiltiy to define more than one function with the same name is called Polymorphism. In java,there are two type of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).

When you override methods, JVM determines the proper methods to call at the program’s run time, not at the compile time. Overriding occurs when a class method has the same name and signature as a method in parent class.
Overloading occurs when several methods have same names with
  • Overloading is determined at the compile time.
  • Different method signature and different number or type of parameters.
  • Same method signature but different number of parameters.
  • Same method signature and same number of parameters but of different type

    Example of Overloading:-
      int add(int a,int b)  
        float add(float a,int b)  
        float add(int a ,float b)  
        void add(float a)  
        int add(int a)  
        void add(int a)         //error conflict with the method int add(int a)  
     Example: Overloading  
     Class BookDetails{  
           String title;  
           String publisher;  
           float price;  
     setBook(String title){  
     setBook(String title, String publisher){  
     setBook(String title, String publisher,float price){  
     Example: Overriding  
     class BookDetails{  
           String title;  
     setBook(String title){ }  
     class ScienceBook extends BookDetails{  
           setBook(String title){}                       //overriding  
     setBook(String title, String publisher,float price){ } //overloading  

Q2) What is inheritance?
Ans) Inheritance is the property which allows a Child class to inherit some properties from its parent class. In Java this is achieved by using extends keyword. Only properties with access modifier public and protected can be accessed in child class.

 public class Parent{  
 public String parentName;  
 public int parentage;  
 public String familyName;  
 public class Child extends Parent{  
 public String childName;  
 public int childAge;  
 public void printMyName(){  
 System.out.println(“ My name is “+ chidName+” “ +familyName)  
In above example the child has inherit its family name from the parent class just by inheriting the class.
Q3) What is multiple inheritance and does java support?
Ans) If a child class inherits the property from multiple classes is known as multiple inheritance.
Java does not allow to extend multiple classes but to overcome this problem it allows to implement multiple Interfaces.
Q4) What is abstraction?
Ans) Abstraction is way of converting real world objects in terms of class.It provides a way of representing essential features without explaining its internal working. For example creating a class Vehicle and injecting properties into it. E.g

 public class Vehicle {  
 public String colour;  
 public String model;  
Q5) What is encapsulation?
Ans) The encapsulation is achieved by combining the methods and attribute into a class. The class acts like a container encapsulating the properties. The users are exposed mainly public methods.The idea behind is to hide how thinigs work and just exposing the requests a user can do.
Q6) What is Association?
Ans) Association is a relationship between two classes. In this relationship the object of one instance perform an action on behalf of the other class. The typical behaviour can be invoking the method of other class and using the member of the other class.

 public class MyMainClass{  
 public void init(){  
 new OtherClass.init();  
} Q7) What is Aggregation?
Ans) Aggregation has a relationship between two classes. In this relationship the object of one class is a member of the other class. Aggregation always insists for a direction.

 public class MyMainClass{  
 OtherClass otherClassObj = new OtherClass();  
Q8) What is Composition?
Ans) Composition is a special type of aggregation relationship with a difference that its the compulsion for the OtherClass object (in previous example) to exist for the existence of MyMainClass.