RSS

Category Archives: Java

Some Questions on Collections

1. What is the difference between a List and a Set?
List allows duplicates and maintains the order in which the elements were inserted on the other hand a Set doesn’t allow duplicates and no order is maintained.

2. Tell me some ways to make a synchronized list.
You can use Vector or can use a method provided in Collections class. Collections.SynchronizedList(List list) which returns a synchronized list.

3. What method should the key class of Hashmap override?
The class used as a Key must override equals() and hashCode() methods.

4. What is the key difference between Enumeration and Iterator?
Iterator has a remove() method while Enumeration doesn’t. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, whereas using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used whenever we want to make Collection objects as Read-only.

5. What is the difference between Vector and ArrayList?
Vector is synchronized whereas ArrayList is not.

6. Can a List contain heterogeneous objects?
Yes a List can contain heterogeneous objects. It also depends upon the type declaration of the List. From Java 1.5 onwards use

 List<Object> list = new ArrayList<Object>(); 

to declare a hetrogenous list.

7. How do I sort the Elements in a Collection?
You can use Collections.sort method to sort the elements.

 
1 Comment

Posted by on September 11, 2010 in Java, Java Collections

 

Sorting List in Java

Sorting Lists in Java is a common task. For this Java provides Comparators and Comparables. These are Interfaces which are required to be implemented for sorting purpose. For the demonstration we will consider one at a time. sort method of Collections class in used to sort. This method is overloaded one takes List as its parameter and other takes List and Comparator as its arguments.

Sorting using Comparable Interface:

This Interface has a method compareTo. It compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. In the code provided below the Person class implements Comparable Interface.

package com.sample.beans;

import java.util.Date;

/**
 * @author hgupta
 *
 */
public class Person implements Comparable<Person> {

	/** used for name of the Person **/
	private String name;
	
	/** used for home address of the Person **/
	private String address;
	
	/** used for Date of Birth **/
	private Date dateOfBirth;
	
	/** used for phone number **/
	private Integer phoneNumber;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the address
	 */
	public String getAddress() {
		return address;
	}

	/**
	 * @param address the address to set
	 */
	public void setAddress(String address) {
		this.address = address;
	}

	/**
	 * @return the dateOfBirth
	 */
	public Date getDateOfBirth() {
		return dateOfBirth;
	}

	/**
	 * @param dateOfBirth the dateOfBirth to set
	 */
	public void setDateOfBirth(Date dateOfBirth) {
		this.dateOfBirth = dateOfBirth;
	}

	/**
	 * @return the phoneNumber
	 */
	public Integer getPhoneNumber() {
		return phoneNumber;
	}

	/**
	 * @param phoneNumber the phoneNumber to set
	 */
	public void setPhoneNumber(Integer phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	@Override
	public int compareTo(Person o) {
		return this.getName().compareTo(o.getName());
	}
	
}

Here the Person class implements the Comparable Interface and so it has the method compareTo. Here in this example it uses String’s compareTo method to compare the String at the base. Depending upon the comparison it returns an int which can be –ve, +ve or 0. Here one concept to be mentioned is it only depends upon the sign of the number but not its magnitude.
Now we will also write a Comparator which will be used to sort the List of Person on the property named dateOfBirth which is of Date type.

package com.comparators;

import java.util.Comparator;

import com.sample.beans.Person;

/**
 * @author Himanshu
 *
 */
public class PersonDOBComparator implements Comparator<Person> {

	@Override
	public int compare(Person o1, Person o2) {
		return o1.getDateOfBirth().compareTo(o2.getDateOfBirth());
	}


}

The PersonDOBComparator implements the Comparator Interface. The method compare takes two arguments and compares them. Using Comparator is easy. If you have any final class whose code cannot be modified, at that stage you can write a comparator. Also if you have a functionality in which you have to sort the List on a number of properties then writing a comparator for each property is easy. Also there are some libraries available which provides comparator on the fly.
Let us sort a List containing Person’s Objects. For this we will make a CollectionSorter.java class which will sort and display the sorted results to the user.

package com.collection.sorting.examples;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;

import com.comparators.PersonDOBComparator;
import com.sample.beans.Person;

/**
 * @author hgupta
 *
 */
public class CollectionSorter {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CollectionSorterUtil collectionSorterUtil = new CollectionSorterUtil();
		ArrayList<Person> persons = collectionSorterUtil.getPersonsAsArrayList();
		System.out.println("Orignal List");
		displayPersons(persons);
		Collections.sort(collectionSorterUtil.getPersonsAsArrayList());//Line 1
		System.out.println("List Sorted By Name");
		displayPersons(persons);
		Collections.sort(collectionSorterUtil.getPersonsAsArrayList(), new PersonDOBComparator());// Line 2
		System.out.println("List Sorted By Date of Birth");
		displayPersons(persons);
	}

	private static void displayPersons(ArrayList<Person> persons){
		DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
		System.out.println("----------------------------------------------------------");
		for(Person person:persons){
			System.out.print(person.getName());
			System.out.println(" " + dateFormat.format(person.getDateOfBirth()));
		}
		System.out.println("----------------------------------------------------------");
	}
}

This class uses another utility class named CollectionSorterUtil.java which populated the list used by CollectionSorter class. At Line 1 we have used Collections.sort(List list) method to sort the List. It uses the method compareTo which we provided in the Person class by implementing Comparable Interface. At Line 2 we have used a Comparator to sort it. This Comparator uses dateOfBirth to sort the List.

package com.collection.sorting.examples;

import java.util.ArrayList;
import java.util.Date;

import com.sample.beans.Person;

/**
 * @author hgupta
 *
 */
public class CollectionSorterUtil {

	/** ArrayList to store Persons Object**/
	ArrayList<Person> persons = new ArrayList<Person>();
	{
		populatePersons();
	}
	
	/**
	 * This method returns a collection of Person
	 * Objects.
	 * @return {@link ArrayList} Person
	 */
	public  ArrayList<Person> getPersonsAsArrayList(){
		return this.persons ;
	}
	
	private void populatePersons(){
		Person person = new Person();
		person.setName("Mark");
		person.setDateOfBirth(new Date("02/12/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Anthony");
		person.setDateOfBirth(new Date("02/30/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Zulia");
		person.setDateOfBirth(new Date("02/12/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Jenifer");
		person.setDateOfBirth(new Date("05/2/1988"));
		persons.add(person);
		
		person = new Person();
		person.setName("Jhon");
		person.setDateOfBirth(new Date("01/11/1987"));
		persons.add(person);
		
		person = new Person();
		person.setName("Russels");
		person.setDateOfBirth(new Date("02/12/1980"));
		persons.add(person);
		
		person = new Person();
		person.setName("Erik");
		person.setDateOfBirth(new Date("05/25/1984"));
		persons.add(person);
		
		person = new Person();
		person.setName("Peter");
		person.setDateOfBirth(new Date("12/02/1997"));
		persons.add(person);
		
	}
	
}

After you run the CollectionSorter class you will see the following output in the console.

Orignal List
----------------------------------------------------------
Mark 02/12/1987
Anthony 03/02/1987
Zulia 02/12/1987
Jenifer 05/02/1988
Jhon 01/11/1987
Russels 02/12/1980
Erik 05/25/1984
Peter 12/02/1997
----------------------------------------------------------
List Sorted By Name
----------------------------------------------------------
Anthony 03/02/1987
Erik 05/25/1984
Jenifer 05/02/1988
Jhon 01/11/1987
Mark 02/12/1987
Peter 12/02/1997
Russels 02/12/1980
Zulia 02/12/1987
----------------------------------------------------------
List Sorted By Date of Birth
----------------------------------------------------------
Russels 02/12/1980
Erik 05/25/1984
Jhon 01/11/1987
Mark 02/12/1987
Zulia 02/12/1987
Anthony 03/02/1987
Jenifer 05/02/1988
Peter 12/02/1997
----------------------------------------------------------

 
Leave a comment

Posted by on September 10, 2010 in Java, Java Collections

 

Tags: , , ,

Installing Tomcat on Windows

Tomcat is an open source servlet and JSP container. It is very easy to install and use. Many Java developers around the world use it. It has got very strong community support and has evolved a lot.  This article gives stress on the installation process of tomcat. To install Tomcat follow the step given as under:

  1. Download the Tomcat from the URL: http://tomcat.apache.org/download-60.cgi . There are two types of files available to download. One is to download the zip file and extract it. Second one is .exe windows installer file to install it in your PC. Second approach is much easier and it will install the service also to start and stop the tomcat server.
  2. If you have downloaded the .exe file just run it by double clicking it and it will install tomcat on your PC. In case you have downloaded the Core version of it then unzip the file to a folder. After unzipping it you will see the following directories inside parent tomcat directory.
  3. tomcat home directory

  4. Deploying a web-application: If you want to deploy any web application put it in the directory named webapp. The application should be a valid web application so that it can be deployed successfully.
  5. Starting /Stopping the Server: Go to the bin directory and double click the startup.bat file to start the server. You will see some logs in the console which opens up when you click the startup file. To shut it down click the shutdown.bat.

Tomcat bin Directory

Tomcat Startup screen

The Console window will show you the log messages when it starts and stops. If you don’t want to stop the server by clicking shutdown.exe you can press CTRL+C in the console window. It will stop the server by itself.

 
Leave a comment

Posted by on September 10, 2010 in Java, Servers

 

Tags: , ,

Writing your First Hello World Program in JAVA

Before attempting to start programming in Java make sure that you have Java installed in your computer.
This example is simple and easy to understand. The program will print “Hello World” in the console.
To start open notepad and type the following code:


/**
 * This is a public class named HelloWorld.
 */
public class HelloWorld {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("Hello World!!");
	}

}

1. Save this file by naming it HelloWorld.java. Make sure that the file name and the class name are same.
2. Open the command console and go to the parent directory where you have saved the HelloWorld.java file. Give the following command: javac HelloWorld.java and press Enter key. This will compile the HelloWorld file and make a class file of it. This file has the bytecode which will be executed by the JVM.

3. After that you can run your java program by running the following command:
C:\>java HelloWorld

This will give you output of “Hello World” in the console.
Source Code Explanation

You have complied and have seen your program run successfully. This all is good but it is also very important to understand how it works. The source code has three main components:

  • Comments
  • Class Declaration
  • Main method

Comments: The comments start from “/*” and end by “*/”. They are ignored by the compiler and are only useful for the programmers to improve readability of the code.  Java supports three types of comment types:

/* text */ Compiler completely ignores whatever comes between.

/** documentation */ These comments are called documentation comments and are also ignored by the compiler. The javadoc tool uses these comments to make automatically generated documentation.
// text: The compiler ignores everything from // to the end of the line.

Class Declaration: The following code declares a public class whose name is HelloWorld.

public class HelloWorld {
…………….
….
}

The class declaration uses the keyword class for its declaration and the code is written in between the opening and closing curly braces.

The main Method: The following code shows the main method. This method accepts a single argument: an array of elements of type String. Every Java Application must have this main method to run.  You can interchange the position of public and static keyword and doing this will not affect your code.

public static void main(String[] args) {
		System.out.println("Hello World!!");
	}

The code in this method is written between the curly braces.

The line System.out.println(“Hello World!!”); in this example uses System class to print the message “Hello World!!” to the console.

 
Leave a comment

Posted by on September 6, 2010 in Java

 

What are Servlets?

As seen from the top then Servlets are no different as compared to a Java class. They provide a component based way to design a web application. Using servlets web developers can create fast and efficient server side application which can run on any servlet enabled web server. Servlets run entirely inside the Java Virtual Machine and so have access to the whole set of Java API. Also an application written using Servlets can be deployed in any container and it will work. Servlets are popular choice for building interactive Web applications. Third-party servlet containers are available for example Apache Web Server, Microsoft IIS, and others. Servlet containers are usually a component of Web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server, and others.

Servlets are not bound to any specific protocol and can be extended to design one of its own choice but commonly servlets designed to work with HTTP(Hyper Text Transfer Protocol) are used heavily. These Servlets are controlled by the container from their creation to collection by Garbage Collector.

 
Leave a comment

Posted by on July 7, 2010 in J2EE, Java

 

Tags: ,

Spring Dependency Injection

Spring DI is the most fundamental feature that it provides. This feature has also been referred as Inversion of Control but after many discussions it was decided that DI is a better term.

Any application which is of practical use is composed of two or more Objects which communicate or use each other.  Traditionally each of those objects is responsible to get the reference of objects it uses but in DI objects are given references to the other objects when needed. All the bean creation and their injection are handled by Spring which acts as a container of beans. This provides loose coupling and also promotes programming to an Interface as the bean knows only about the type of bean but nothing about its implementation.

For Example: If the bean Store has declared Product property as an interface then the Product implementation becomes irrelevant.   The Product bean can be web-service implementation, an EJB or a mock test object.

Some other benefits of using DI:
• Reduction of boiler plate coding.
• As all metadata is in xml file and is easy to configure. This gives flexibility in testing and development.

 
Leave a comment

Posted by on July 5, 2010 in Java, Spring

 

Tags: ,

Java Example of Spring Dependency Injection

This tutorial uses the following:

    • Eclipse IDE
    • Spring Jars
    • commons-logging-api-1.1.jar
  1. Make a new Java Project in Eclipse.
  2. Add the following jars to its classpath:
    • commons-logging-api-1.1.jar
    • org.springframework.core-3.0.2.jar
    • org.springframework.beans-3.0.2.jar

The Spring jars can be taken from the dist folder of the expanded zip file. Here you have to include the two jars one for core and other for beans. Commons-logging is used for logging purpose.

  • Make a new class – Person.java. It is a 100% Java bean and has the proper getters and setters.
package com.spring.ioc.beans;

public class Person {

	private String name;

	private String address;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the address
	 */
	public String getAddress() {
		return address;
	}

	/**
	 * @param address the address to set
	 */
	public void setAddress(String address) {
		this.address = address;
	}

}

  • Make an XML file and name it context.xml and save it in the src folder.  This file contains all the meta information needed for bean creation. Here the bean id is person and class has the full qualified name of the class. The “name” property of the class Person is populated with the value Mac.

<?xml version="1.0" encoding="UTF-8"?>
xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
	<bean id="person" class="com.spring.ioc.beans.Person">
	<property name="name" value="Mac"></property>
	</bean>
</beans>

  • Make another class named Main.java.  Here an object of XmlBeanFactory loads the configurations from contect.xml file. Also its constructor takes an argument of ClassPathResource.
  • To get a bean from XmlBeanFactory object use its reference type to invoke the method getBean(<bean id>) and it will return the bean as defined in the spring context file.  The Object it returns is of type Object so you do have to cast it to the correct type.
package com.spring.ioc.main;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

import com.spring.ioc.beans.Person;

/**
 * @author hgupta
 *
 */
public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
				"context.xml"));
		Person person = (Person) beanFactory.getBean("person");
		System.out.println(person.getName());
	}

}

  • Run the Main class as Java Application and you will see the following output: The output is the name of the person which you configured in the xml file.

Output:

May 27, 2010 6:54:04 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [context.xml]

Mac

 
Leave a comment

Posted by on July 5, 2010 in Java, Spring

 

Tags: ,