Pages Navigation Menu

Coding is much easier than you think

How to exclude action methods from validation in struts2

Posted by in Struts-2



My Action class have the following methods,
1.execute
2.populate
3.fetchElement
4.addElement
5.deleteElement
 
** UPDATE: Struts 2 Complete tutorial now available here.
 
Suppose if we want to apply validation for addElement and deleteElement method alone and not for other method , then Simply list all the methods you don’t want to be run through the validation framework in the excludeMethods parameter. Since we only want addElement and deleteElement validated, list the other 3 as follows:
 

<interceptor-ref name="validation">
    <param name="excludeMethods">execute,populate,fetchElement</param>
</interceptor-ref>

 

Read More

Comparable vs Comparator

Posted by in Core Java, Java | 2 comments

 
One of the common asked interview question “What are differences between Comparator and Comparable”? Or “How will you sort collection of employee objects by its id or name”.
 
For this we can use two interfaces, Comparator and Comparable. Before we actually see differences, let me give you brief introduction of both.
 
Comparable interface:
 
Comparable is an interface from java.lang package. It includes only one abstract method compareTo() that is to be overridden by the programmer with his ordering code.

A comparable object (a class which implements Comparable interface) compares itself with another object. If the object obj1 would like to compare with obj2, call compareTo() method with obj1 and pass obj2 as parameter (like equals() method in case of strings).

The class which would like to sort the objects using Comparable must implement Comparable interface.
 
Comparator interface:
 
Comparator is an interface from java.util package. It includes two abstract methods – compare() and equals().

A comparator object (a class which implements Comparator interface) can compare any two objects and these two objects are passed as parameters to compare() method. That is, two objects of an Employee, like emp1 and emp2 can be passed.

The class which would like to sort the objects using Comparator must implement Comparator interface.

 
Signature of the methods existing in Comparable and Comparator interfaces
 
java.lang.Comparable interface

  • int compareTo(Object obj2): Compares two objects. With one object (current object, say obj1) the method is called and the other is passed as parameter (like obj2). The method returns an integer value depending on the objects under comparison as follows.

java.util.Comparator interface

  • int compare(Object obj1, Object obj2): Objects obj1 and obj2, under comparison, are passed as parameters. Returns an integer value depending on the objects under comparison as described below.

Both methods returns

a) A positive integer if obj1 is greater than obj2.
b) Zero if obj1 and obj2 are equal.
c) A negative integer if obj1 is less than obj2.
 
How to use the methods?
 
Since these methods are abstract, they must be overridden by the implementing classes.

The Comparable object is used along with Collections.sort(List) and Arrays.sort(Object[]) methods.

The Comparator object is used with Collections.sort(List, Comparator) and Arrays.sort(Object[], Comparator) methods.

 

1. A program using Comparable interface
 

import java.util.*;

class Employee implements Comparable<Employee> {
	private int salary;
	private String name;

	public Employee(int salary, String name) {
		this.salary = salary;
		this.name = name;
	}

	public int getSalary() {
		return salary;
	}

	public String getName() {
		return name;
	}

	public int compareTo(Employee emp) {
		return this.salary - emp.salary;
	}
}

public class EmployeeSortBySalary {
	public static void main(String args[]) {
		ArrayList<Employee> employeeList = new ArrayList<Employee>();
		employeeList.add(new Employee(50, "Haripriya"));
		employeeList.add(new Employee(40, "Venkat"));
		employeeList.add(new Employee(70, "Raman"));
		employeeList.add(new Employee(90, "Akathar"));
		employeeList.add(new Employee(30, "Farhan"));
		Collections.sort(employeeList);
		for (Employee emp : employeeList) {
			System.out.println(emp.getSalary() + " : " + emp.getName());
		}
	}
}

 
Output of the above program :
 

30 : Farhan
40 : Venkat
50 : Haripriya
70 : Raman
90 : Akathar

 
Explanation:
 

      class Employee implements Comparable<Employee>

 

The Employee class implements Comparable interface. Here, Comparable is designed to be generics; that is, Comparable object compares only Employee objects.

Two member variables salary and name are declared and values are assigned through a constructor. Two getter methods are declared with which Employee salary and name are retrieved later.

 

public int compareTo(Employee emp)
{
 return this.salary - emp.salary;
}

 

The Comparable interface’s abstract method compareTo() is overridden where salary are compared.

Another class EmployeeSortBySalary is created which creates some Employee objects and adds them to ArrayList employeeList.

 

Collections.sort(employeeList);

 

The ArrayList object employeeList is passed to sort() method of Collections class. The sort() method sorts as per the Comparable interface compareTo() method as Employee class implements Comparable interface.
 
Sorting with name(String) field

Now let us try sorting with name field. Just change the compareTo() method in Employee class as follows.
 

// compareTo() belongs to Comparable interface
public int compareTo(Employee emp1)
{
// compareTo() belongs to String class
return this.name.compareTo(emp1.name);
}

Here, you may get a little confusion between the two compareTo() methods used in the above code. The compareTo() method used inside (this.name.compareTo(emp1.name)) belongs to String class and not Comparable interface. compareTo() method of String class makes lexicographical comparison and returns three types of integers – positive, negative and 0.
 

2. A program using Comparator interface

Earlier you have seen one program “Comparator Example” where ArrayList elements are sorted. For a better understanding of the subject, let us do the same Employee class of Comparable but with Comparator.

 

import java.util.*;

class Employee
// Note that the Employee does not implement Comparator
{
	private int salary;
	private String name;

	public Employee(int salary, String name) {
		this.salary = salary;
		this.name = name;
	}

	public int getSalary() {
		return salary;
	}

	public String getName() {
		return name;
	}
} // Note that the EmployeeSortBySalary implements Comparator

public class EmployeeSortBySalary implements Comparator<Employee> {
	

	public static void main(String args[]) {
		ArrayList<Employee> employeeList = new ArrayList<Employee>();
		employeeList.add(new Employee(50, "Haripriya"));
		employeeList.add(new Employee(40, "Venkat"));
		employeeList.add(new Employee(70, "Raman"));
		employeeList.add(new Employee(90, "Akathar"));
		employeeList.add(new Employee(30, "Farhan"));
		
		Collections.sort(employeeList, new EmployeeSortBySalary());
		for (Employee st : employeeList) {
			System.out.println(st.getSalary() + " : " + st.getName());
		}
	}

	public int compare(Employee emp1, Employee emp2) {
		return emp1.getSalary() - emp2.getSalary();
	}
}

Output :
 

30 : Farhan
40 : Venkat
50 : Haripriya
70 : Raman
90 : Akathar

 
Explanation:
 
Here in the above program, one difference you can observe is, the Comparator interface is not implemented with Employee class but with another class. But in the case of Comparable, the Comparable interface is implemented with Employee class. That is, with Comparator, we can sort any class objects without changing the original class code.
 
The code explanation is the same of earlier Comparable, but with minor changes. The method overridden is compare() (in the case of Comparable, it is compareTo()). The compare() method parameters are two objects under comparison; but with Comparable, the compareTo() method parameter is one, the other object calls the method.
 

One more difference is the usage of overloaded sort() method.

In case of Comparator, it is Collections.sort(employeeList, new EmployeeSortBySalary()). The second parameter is an object of Comparator (a class that implements Comparator).

In case of Comparable, it is Collections.sort(employeeList).
 
When to use Comparator and Comparable in Java
 
At last let’s see some best practices and recommendation on when to use Comparator or Comparable in Java:

1) If the object is sorted by single way then it should implement Comparable interface, for example, let’s assume you have an employee bean class which have name, salary and id as member variable. In this case if you are about to perform sorting only by using id then you can go for Comparable interface.

On the other hand if an Object can be sorted on multiple ways and client is specifying on which parameter sorting should take place than use Comparator interface. For example if you want to sort all the fields in the Employee bean class (i.e. sort by name, salary or id) then you should go for Comparator interface.

2) Some time you write code to sort object of a class for which you are not the original author, or you don’t have access to code. In these cases you cannot implement Comparable and Comparator is only way to sort those objects.

3) Comparator has a distinct advantage of being self descriptive for example if you are writing Comparator to compare two Employees based upon their salary than name that comparator as SalaryComparator, on the other hand by using Comparable interface we can’t give unique name to it.

 

Read More

Is Java Pass by Reference or Pass by Value?

Posted by in Core Java, Java

 

This post will give you some insights of how Java really works to the point that in your next discussion about Java passing by reference or passing by value you’ll just smile :-)
 
Consider the following program:
 

public class Main
{
	public static void main(String[] args) {
		Foo f = new Foo("f");
		// It won't change the reference!
		changeReference(f);
		// It will modify the object that the reference variable "f" refers to!
		modifyReference(f);
	}

	public static void changeReference(Foo a) {
		Foo b = new Foo("b");
		a = b;
	}

	public static void modifyReference(Foo c) {
		c.setAttribute("c");
	}
}

 
I will explain this in steps:

  1. Declaring a reference named fof type Fooand assign it to a new object of type Foowith an attribute "f".
     
    Foo f = new Foo("f");

     

    Simple reference

  2. From the method side, a reference of type Foowith a name ais declared and it’s initially assigned to null.
     
    public static void changeReference(Foo a)

     
    new reference

  3. As you call the method changeReference, the reference awill be assigned to the object which is passed as an argument.
    changeReference(f);

     
    assign referrence

  4. Declaring a reference named bof type Fooand assign it to a new object of type Foowith an attribute "b".
    Foo b = new Foo("b");

     
    new reference 2

  5. a = b is re-assigning the reference aNOT fto the object whose its attribute is "b".
  6. As you call modifyReference(Foo c)method, a reference cis created and assigned to the object with attribute "f".
     
  7. c.setAttribute(“c”); will change the attribute of the object that reference cpoints to it, and it’s same object that reference fpoints to it.
     

I hope you understand now how passing objects as arguments works in Java :)

 

Read More

Compare two files by content in Java

Posted by in Java



In this tutorial, we will provide a simplified approach to compare two files in Java by content. We will use Apache Commons IO library to perform this comparison, and run this against some test files we prepare to see the results.

Before start download and add the following library in your classpath.
 

dwd2
Download It – commons-io-2.4.jar 

 
We will use the contentEquals() method of the FileUtils class of the above library to compare the file content.

 
The Java program to compare two files by content using Apache Commons IO, is provided below:
 

package com.simplecode.jdbc;

import java.io.File;
import org.apache.commons.io.FileUtils;

public class compareFileContent
{
	public static void main(String[] args) throws Exception
	{
		/* Get the files to be compared first */
		File file1 = new File(args[0]);
		File file2 = new File(args[1]);
	
		boolean compareResult = FileUtils.contentEquals(file1, file2);
		System.out.println("Are the files are same? " + compareResult);
		
	}
}



 

Using this code we can compare any two files (text , image , pdf etc)



The comparison works because, it is done as a byte by byte comparison between the two files as per the API docs. You can compare any two files using this code, be it of any format. One drawback of this approach, is that if one of the files has additional metadata but same content, the comparison still returns false. This is acceptable in one angle and otherwise. So, you may want to make use of this approach depending on your requirement.


Read More

Eclipse Shortcuts for fast coding

Posted by in Eclipse | 1 comment

 
eclipse shortcut


List of some Shortcuts for fast coding. Traverse below and improve your coding speed by utilizing Eclipse Shortcuts.

dwd2
Download It – eclipse.pdf

 

File navigation  Short cuts
 

Short cuts Description
Alt + Shift + nUse this shortcut key to open an new menu.
Ctrl + n  Use this  shortcut key to create a new file
Ctrl+HIf you want to search in your program and work space use this short cut .
CTRL + SHIFT + ROpen a resource. You need not know the path and just part of the file name is enough.
Ctrl +EOpen a file (editor) from within the list of all open files.
CTRL + PAGE UP or PAGE DOWNGo to previous or next edit positions from editor history list.
ALT + <- or ALT + ->If you want to close the all file in editor use this shortcut key.
Ctrl +WIf you want to close the all file in editor use this shortcut key.
Ctrl +Shift+WIf you want to close the all file in editor use this shortcut key.
F2,Alt +Shift+RIt is use for re-name  file .
Ctrl +Shift +GFind the reference variable in workspace.

 

Java Editing Short cuts
 

Short cutsDescription
Ctrl+Shift+FThis short cut use to formatting  the code .
Ctrl+SpaceType assist
Ctrl+ODisplays every one of the methods and variables in addition to methods available in the current class that’s selected.
Ctrl+Shift+O                                                            This Shortcut use for Organized  import .
Ctrl+Shift+UFind the reference of a file .
Ctrl+/,Ctrl+7Single Line comment .
Ctrl+Shift+/Add block Comment .
Ctrl+Shift+\Remove the block comment.
F3Go to the declaration of the variable
F4Show the type hierarchy of an class.
Ctrl+TShow the inheritance tree of current token .
Shift+f2Show the Java Doc for current  token.
Alt Shift ZAdd the try and catch block

 
Editing Short cuts
 

Short cutsDescription
F12Focus on current editor
Ctrl +LFind the Line number.
Ctrl+D                                     This short cut use for delete the single row.
Ctrl +MThis short cut use for maximize and minimize the editor.

 
 
Debug and  Run Eclipse short cuts
 

Short cuts                                                    Description
F11Start the Debug .
Ctrl+F11Run the last program or project.
Ctrl .Or ,To Navigate  the next and previous error .
F5Step Into.
F6Step Over.
F8Resume .
Ctrl+Q Add Inspect
Ctrl +1Quick fix code.

 
Some Extra Short cuts
 

Short cuts                                                    Description
Alt +Shift +BAdd the toggle breakpoint .
Alt +Shift+cChange the method signature .
Alt +Shift+S,RGenerate the setter and getter method .
Alt +Shift+X,JRun As java Application .
Alt +Shift+X,RRun As web application .
Alt +EnterShow The Property.
Alt +Shift+X,ARun As Applet .

 
String to StringBuffer /StringBuilder
 
In order to change the concatenation from String to StringBuffer /StringBuilder, move the cursor to the String variable, and press Ctrl +1, and select ‘Use StringBuffer//StringBuilder for string concatenation’
For eg, String s = “a”+”b”+”c”+”d”;
will change to StringBuffer sB = new StringBuffer();
sB.append(“a”);
sB.append(“b”);
sB.append(“c”);
sB.append(“d”);
String s = sB.toString();
 

Read More
Page 20 of 41«First...10...1819202122...3040...Last»