Thursday, July 31, 2014

Java Tips and Tricks


This blog explains , most important tips & tricks that every one should remember always.

Java Collection Framework Architecture Diagram



Difference b/w HashTable and Hash Map

1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
2. Hashtable does not allow null keys or values.  HashMap allows one null key and any number of null values.
3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.
Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue


  Difference between ArrayList vs HashSet in Java 
Here are couple of differences between ArrayList and HashSet in Java:

1) First and most important difference between ArrayList and HashSet is that ArrayList implements List interface whileHashSet implements Set interface in Java.

2) Another difference between ArrayList and HashSet is that ArrayList allow duplicates while HashSet doesn't allow duplicates. This is the side effect of fist difference and property of implementing List and Set interface.

3) Third difference between ArrayList and HashSet is that ArrayList is an ordered collection and maintains insertion order of elements while HashSet is an unordered collection and doesn't maintain any order.

4) Fourth difference between ArrayList and HashSet is that ArrayList is backed by an Array while HashSet is backed by an HashMap instance.

5) Fifth difference between HashSet and ArrayList is that its index based you can retrieve object by calling get(index) or remove objects by calling remove(index) while HashSet is completely object based. HashSet also doesn't provide get() method.

     How to convert List to Array

List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
String [] array = list.toArray(new String[list.size()]);

Monday, May 12, 2014

How to Sort List of Custom Objects in Java ?


This blog explains about sorting list of custom objects in Java

- Define a Custom Java class, In this example, I want to sort all the EmployeeDTO objects based on salary
- Implement 'Comprable' Interface
- Override 'compareTo' method as shown below
- Perform Collections.sort(List) method as shown below, This will internally invoke compareTo() method and sort based on compareTo() implementation.

       

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

public class EmployeeDTO implements Comparable {
    public EmployeeDTO() {
        super();
    }
    private String firstName;
    private String lastName;
    private int sal;

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setSal(int sal) {
        this.sal = sal;
    }

    public int getSal() {
        return sal;
    }

    /**
     *Override compareTo() method
     * @param employee
     * @return
     */
    public int compareTo(EmployeeDTO employee) {
        // Ascending Order
        return this.sal - employee.getSal();
        // Descending Order
        //return employee.getSal()-this.sal;


    }
 }
       
 

- Test above code as shown below, Here I am randomly generating salary value using 'Random' Generator class.
       

      public static void main(String[] args) {
        EmployeeDTO dto = null;
        // Random Number Generator
        Random randomGenerator = new Random();
        List list = new ArrayList();
        for (int i = 0; i < 5; i++) {
            int sal = randomGenerator.nextInt(100);
            dto = new EmployeeDTO();
            dto.setFirstName("FirstName" + sal);
            dto.setLastName("LastName" + sal);
            dto.setSal(sal);
            list.add(dto);
        }
        System.out.println(" Before Sort : ");
        Iterator it = list.iterator();
        while (it.hasNext()) {
            dto = (EmployeeDTO)it.next();
            System.out.println(" First Name : " + dto.getFirstName());
            System.out.println(" Last Name : " + dto.getLastName());
            System.out.println(" Sal : " + dto.getSal());
        }
        // Perform Sorting
        Collections.sort(list);
        System.out.println(" After Sort : ");
        it = list.iterator();
        while (it.hasNext()) {
            dto = (EmployeeDTO)it.next();
            System.out.println(" First Name : " + dto.getFirstName());
            System.out.println(" Last Name : " + dto.getLastName());
            System.out.println(" Sal : " + dto.getSal());
        }
    }
       
 


- We can achieve same by using 'Comparator' Interface
- Write a custom comparator class as shown below
       

  package com.fm.recruitment.model.util;

import java.util.Comparator;


public class SalComparator implements Comparator {

    public SalComparator(){
        super();
    }
    public int compare(EmployeeDTO emp1, EmployeeDTO emp2) {
        int flag = emp1.getSal() - emp2.getSal();
        return flag;
    }
}

       
 

- Follow below code to sort using above comparator
Collections.sort(list,new SalComparator());

Sunday, April 6, 2014

Most commonly used Utility Methods in Java




How to truncate decimal value to two digits

     double d = 3.34568;
     DecimalFormat f = new DecimalFormat("##.00");
    Output is : 3.34


    public static void main(String args[]){
        // Initialize and assign String[] array
        String[] arr = new String[]{"A","B"};
        // Convert String[] array to List<String>
        List<String> arrList = new ArrayList<String>(Arrays.asList(arr));
        System.out.println(arrList);
        // Convert List<String> to String[] array
        arr = arrList.toArray(new String[arrList.size()]);
        System.out.println(arr);
    }

Thursday, March 27, 2014

How to Deploy & UnDeploy ADF applications using Jdeveloper and WEblogic console


This blog explains about deploying and undeploying an ADF application using Jdeveloper and Weblogic Console

Please refer to How to create Deployment Profiles to create deployment profiles.

- Establish Application server connection in Jdeveloper
- Choose View->ApplicationServerNavigator
- Right click on 'Application Servers' -> 'New Application Server Connection'
- Choose 'Standalone Server' -> Next
- Give Meaningful name to 'Connection' - Choose Connection type as 'weblogic 10.3' ->Next
- Enter login credentials
- Enter host name,  port numbers, Leave default option to 'Always use SSL', Weblogic Domain Name->Next
- Click on 'Test Connection' ensure all the tests successful.
- Click on 'Finish', After successful creation you will see newly created server connection as shown below.


- ------------------- Deploying from Jdeveloper -----------------------------
- Right click on Application, Choose the 'EAR' deployment profile
- Choose 'Deploy to Application Server' option, Next
- Choose the appropriate application server you want to deploy,Next
- If the Weblogic server has too many managed servers or connections, then select the appropriate one and click on 'Finish'
- Verify the deployment process in log window, ensure Deployment is successful.

------------------------ Undeploying from Jdeveloper ----------------------------
- Choose View->Application Server Navigator
- Expand the Application Servers, select the one which has application deployed and expand.
- Expand 'Deployment' folder, Select the application which you want to undeploy, Right click and choose 'Undeploy'







Friday, February 7, 2014

How to find a version of java class



This blog explains about how to find the version of the java class file, Java class version is based on JDK version where this is compiled. Each JDK will have different version. For example JDK1.5 has version as 49, JDK1.6 has version as 50


Use javap -verbose <class Name> as shown in below screenshot. major version indicates the version of java class.