Monday, March 3, 2014

Java Date examples

Convert Date to String.

 SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
 String date = sdf.format(new Date());
 System.out.println(date); //15/10/2013Example

Convert String to Date.

 SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
 String dateInString = "31-08-1982 10:20:56";
 Date date = sdf.parse(dateInString);
 System.out.println(date); //Tue Aug 31 10:20:56 SGT 1982

Get current date time

 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
 Date date = new Date();
 System.out.println(dateFormat.format(date)); //2013/10/15 16:16:39

Iterating Map in Java using KeySet Iterator && using EntrySet



HashMap
Set<String> keySet = loans.keySet();
Iterator<String> keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
   System.out.println("------------------------------------------------");
   System.out.println("Iterating Map using KeySet Iterator");
   String key = keySetIterator.next();
   System.out.println("key: " + key + " value: " + loans.get(key));
}

Output:
------------------------------------------------
Iterating Map using KeySet Iterator
key: home loan value: citibank
------------------------------------------------
Iterating Map using KeySet Iterator
key: personal loan value: Wells Fargo

Example for using EntrySet
Set<Map.Entry<String, String>> entrySet = loans.entrySet();
for (Entry entry : entrySet) {
   System.out.println("------------------------------------------------");
   System.out.println("looping HashMap in Java using EntrySet and java5 for loop");
   System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}

Output:
------------------------------------------------
looping HashMap in Java using EntrySet and java5 for loop
key: home loan value: citibank
------------------------------------------------
looping HashMap in Java using EntrySet and java5 for loop
key: personal loan value: Wells Fargo

What is the difference between Hashtable and HashMap?

import java.util.Iterator;
import java.util.Hashtable;
import java.util.Set;

public class HashtableEntriesIterator {

  public static void main(String[] args) {

    // Create a Hashtable and populate it with elements
    Hashtable hashtable = new Hashtable();
    hashtable.put("key_1","value_1");
    hashtable.put("key_2","value_2");
    hashtable.put("key_3","value_3");

    // Get a set of all the entries (key - value pairs) contained in the Hashtable
    Set entrySet = hashtable.entrySet();


    // Obtain an Iterator for the entries Set
    Iterator it = entrySet.iterator();
   
    // Iterate through Hashtable entries
    System.out.println("Hashtable entries : ");
    while(it.hasNext())

System.out.println(it.next());
   
  }
}

Difference between Comparator and Comparable in java


Comparable interface:

Class whose objects to be sorted must implement this interface.In this,we have to implement compareTo(Object) method.

For example:

public class Country implements Comparable<Country>{  
 @Override
 public int compareTo(Country country) {  
       return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ;  
 }}  

If any class implements comparable inteface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort().Object will be sort on the basis of compareTo method in that class.
Objects which implement Comparable in java can be used as keys in a SortedMap like TreeMap or SortedSet like TreeSet without implementing any other interface.

Comparator interface:

Class whose objects to be sorted do not need to implement this interface.Some third class can implement this interface to sort.E.g.CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id.

         Country indiaCountry=new Country(1, "India");  
         Country chinaCountry=new Country(4, "China");  
         Country nepalCountry=new Country(3, "Nepal");  
         Country bhutanCountry=new Country(2, "Bhutan");           

         List<Country> listOfCountries = new ArrayList<Country>(); 
         listOfCountries.add(indiaCountry);  
         listOfCountries.add(chinaCountry);  
         listOfCountries.add(nepalCountry);  
         listOfCountries.add(bhutanCountry);   
 
 //Sort by countryName  

           Collections.sort(listOfCountries,new Comparator<Country>() {  
                @Override 
                public int compare(Country o1, Country o2) {
                    return o1.getCountryName().compareTo(o2.getCountryName());  }  
            }); 

Sunday, March 2, 2014

Static Keyword

static keyword

The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
  1. variable (also known as class variable)
  2. method (also known as class method)
  3. block
  4. nested class

1) static variable

If you declare any variable as static, it is known static variable.
  • The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
  • The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable

class Student{   
     int rollno;   
     String name;   
     String college="ITS";   
}  

Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.If we make it static,this field will get memory only once.

static property is shared to all objects.

Example of static variable

  1. //Program of static variable   
  2.   
  3. class Student{   
  •    int rollno;   
  •    String name;   
  •    static String college ="ITS";   
  •       
  •    Student(int r,String n){   
  •    rollno = r;   
  •    name = n;   
  •    }   
  •  void display (){System.out.println(rollno+" "+name+" "+college);}   
  •   
  •  public static void main(String args[]){   
  •  Student s1 = new Student (111,"Karan");   
  •  Student s2 = new Student (222,"Aryan");   
  •     
  •  s1.display();   
  •  s2.display();   
  •  }   
  • }  
  • Output:111 Karan ITS
           222 Aryan ITS
    

    Program of counter without static variable

    In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count variable.
     
    1. class Counter{   
  • int count=0;//will get memory when instance is created   
  •   
  • Counter(){   
  • count++;   
  • System.out.println(count);   
  • }   
  •   
  • public static void main(String args[]){   
  •   
  • Counter c1=new Counter();   
  • Counter c2=new Counter();   
  • Counter c3=new Counter();   
  •   
  • }}  
  • Output:1
           1
           1
    

    Program of counter by static variable

    As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.
     
    1. class Counter{   
  • static int count=0;//will get memory only once and retain its value   
  •   
  • Counter(){   
  • count++;   
  • System.out.println(count);   
  • }   
  •   
  • public static void main(String args[]){   
  •   
  • Counter c1=new Counter();   
  • Counter c2=new Counter();   
  • Counter c3=new Counter();   
  •   
  • }}  
  • Output:1
           2
           3
    

    2) static method

    If you apply static keyword with any method, it is known as static method
    • A static method belongs to the class rather than object of a class.
    • A static method can be invoked without the need for creating an instance of a class.
    • static method can access static data member and can change the value of it.

    Example of static method

    //Program of changing the common property of all objects(static field).   
    1.   
    2. class Student{   
  •      int rollno;   
  •      String name;   
  •      static String college = "ITS";   
  •         
  •      static void change(){   
  •      college = "BBDIT";   
  •      }   
  •   
  •      Student(int r, String n){   
  •      rollno = r;   
  •      name = n;   
  •      }   
  •   
  •      void display (){System.out.println(rollno+" "+name+" "+college);}   
  •   
  •     public static void main(String args[]){   
  •     Student.change();   
  •   
  •     Student s1 = new Student (111,"Karan");   
  •     Student s2 = new Student (222,"Aryan");   
  •     Student s3 = new Student (333,"Sonoo");   
  •   
  •     s1.display();   
  •     s2.display();   
  •     s3.display();   
  •     }   
  • }  
  • Output:111 Karan BBDIT
           222 Aryan BBDIT
           333 Sonoo BBDIT
    

    Sunday, February 23, 2014

    Method Overriding in Java

    Advantage of Java Method Overriding:

        1) Method Overriding is used to provide specific implementation of a method that is         already provided by its super class.
        2) Method Overriding is used for Runtime Polymorphism

    Code Example:

        In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding. 

        class Engine{ 
        void run(){System.out.println("Engine is running");} 
        } 
        class Car extends Engine{ 
        void run(){System.out.println("Car is running Successfully ");} 
         
        public static void main(String args[]){ 
        Car obj = new Car(); 
        obj.run(); 
        } 

    Output:
     
       Car is running Successfully

    Wednesday, February 19, 2014

    Synchronized block


    Using synchronized block in java is also similar to using synchronized keyword in methods. Only important thing to note here is that if object used to lock synchronized block of code, Singleton.class in below example is null then Java synchronized block will throw a NullPointerException.

    public class Singleton {
       private static Singleton instance;
       public static Singleton getInstance()
       {
                if(instance == null) {
                      synchronized(Singleton.class){
                               if(instance == null) {
                                     instance = new Singleton();
                             }
                       }
                }
              return instance;
           }
       }