Showing posts from 2011

Jar command

Jar is a java archive file.Its like a zipped file.

All the java files can be archived into a jar file using the jar command.

jar - cf  MyJar.jar Myapp.--> archives Myapp into a jar file named MyJar.jar

To list the files in the Jar file.

jar-tf MyJar.jar

Relative Paths and Absolute Path in Java

Relative paths is the one the do not start with a  forward slash(/) or a backward slash(\).Example for Relative path:  -classpath dirB: dirB/dirC.  The relative path is meaningfull only when the user current directory is directory A where B is its sub directory.Absolute paths start with a slash. Indicates the root directory.

Java Class Path

Java class path can be thought as class search paths.Classes are searched from left to right.
Example of classpath:  -classpath  /com/foo
Classpaths can be declared in two places:

   as an environment variable in the operating system   as a command line option
The classpath declared as an environment variable is a default option.The classpath declared as an systems environment variable is used by default whenever java or javac is invoked.

The classpath declared as an command line option is temporary and exists only for the length of invocation.

Java Reflection Examples

Java Reflection is used the extensively in following areas:

JUNIT JAR-Junit 3.0 uses reflection to find methods that start with" test".The algorithm was changed in 4.0.Now reflections are used to find methods with @ test annotations.Java Editors and IDE: Most of the java editors like eclipse,Netbeans and others use reflection to populate the methods associated with the class.For example in most of the java editors when you type "classname." and press space or tab you get all the methods associated with it.The method suggestion is shown using java refelection.Java Ant Build Files: A user can use taskdef property to instantiate and compile a user defined task.Spring framework:Spring uses reflection to create an Object of each Bean.The spring xml file has the classname attribute which is read to create bean objects.All the Bean Objects will be created using a default constructor and the proprties of the objects are examined.Runtime code generation:This is used by IDES …

Singleton class-Violation

private static MyObject myObject;
private MyObject (){
public static synchronized MyObject getInstanceObject(){

myObject=new Object();

return myObject

It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration

Singleton Class-Private Constructor

A class is called a singleton class, if it allows only one instance of the object to be created throughout the application.

A singleton class has the following

 private constructor which-prevent other classes from instantiating it directly.a public method with static modifier which returns the instance.--a static method can be accessed at class level without     creating an object.private static instance of the class

package singleotons;

Public class Logger{
private static Logger logger;

private Logger(){

public static Logger getLoggerInstance(){
if (logger==null){

logger=new Logger();
return logger;

Complete date with date format Using Hibernate

Spring MVC- Redirect from one controller to another

In spring mvc its very easy to redirect from one controller to another controller

Example :

public class SpringController1{

public class SpringController2{

//thinking of redirecting on clicking on a method
@RequestMapping(value = "/", method = RequestMethod.POST, params = "action=cancel")
    public ModelAndView cancel(@ModelAttribute("MyForm") MyForm myForm, BindingResult errors,SessionStatus sessionStatus,HttpServletRequest request) throws MyException {
        ModelAndView modelAndView = new ModelAndView();

        //redirecting to controller1
        return new ModelAndView("redirect:/");



spring jdbc template rowmapper example

    public ArrayList getSearchResultByColumn_isAdmin(ABCResultForm  form, String roleId) {

        String query = StringConstants.ABC_RESULT_SEARCH_BY_COLUMN;
        System.out.println("Comes here getSearchResultByColumn");
        int count = 0;
                       query = query + " ORDER BY PROCESSING_DATE_START desc ";
                return (ArrayList) getJdbcTemplate().query(query,new Object[] {},new RowMapper() {
                            public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
                                String status;

                                if (rs.getString(4).equals("11"))
                                    status = "Error";
                                    status = "Ok/Warning";
                                ABCResultDataBean abcResultBean = new ABCResultDataBean(rs.getString(1), rs.getString(2), rs.getS…

convert string to BigDecimal

public BigDecimal convertStringtoBigDecimal(String a){
return new BigDecimal(a);


//can do a null check--before invoking this to avoid null pointer exception

power(base,n) recursively in java

Given base and n that are both 1 or more, compute recursively (no loops) the value of base to the n power, so powerN(3, 2) is 9 (3 squared).

powerN(3, 1) → 3
powerN(3, 2) → 9
powerN(3, 3) → 27

public int powerN(int base, int n) {

int result=base;

if(n==0) return 1;

if(n > 0){

return result * (powerN(base,n-1));

return result;


fibonocci number in java

The fibonacci sequence is a famous bit of mathematics, and it happens to have a recursive definition. The first two values in the sequence are 0 and 1 (essentially 2 base cases). Each subsequent value is the sum of the previous two values, so the whole sequence is: 0, 1, 1, 2, 3, 5, 8, 13, 21 and so on. Define a recursive fibonacci(n) method that returns the nth fibonacci number, with n=0 representing the start of the sequence.

fibonacci(0) → 0

fibonacci(1) → 1

fibonacci(2) → 1
public int fibonacci(int n) {


return 0;

else if (n == 1)

return 1;

else if (n == 2)

return 1;


return fibonacci(n-1) + fibonacci(n-2);


BunnyEars--Java Number sequencing problem

We have bunnies standing in a line, numbered 1, 2, ... The odd bunnies (1, 3, ..) have the normal 2 ears. The even bunnies (2, 4, ..) we'll say have 3 ears, because they each have a raised foot. Recursively return the number of "ears" in the bunny line 1, 2, ... n (without loops or multiplication).

bunnyEars2(0) → 0

bunnyEars2(1) → 2

bunnyEars2(2) → 5
public int bunnyEars2(int bunnies) {

if(bunnies==0) return 0;

else if(bunnies%2==0)

return 3 + bunnyEars2(bunnies-1);


return 2+bunnyEars2(bunnies-1);


Sum of Digits in an Integer

Given a non-negative int n, return the sum of its digits recursively (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).

sumDigits(126) → 9

sumDigits(49) → 13

sumDigits(12) → 3
public int sumDigits(int n) {

int Count=0;







return Count;


Occurance of a digit in an Integer recursively

Given a non-negative int n, return the count of the occurrences of 7 as a digit, so for example 717 yields 2. (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).

count7(717) → 2

count7(7) → 1

count7(123) → 0

public int count7(int n) {

int count=0;

int rtemp=0;

int ltemp=0;

if(n/10<10 ){















return count;