Monday, November 19, 2012

Program to get contents of an excel sheet

import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ReadExcelSheet {
   private String inputFile;
   
  public void setInputFile(String inputFile) {
        this.inputFile = inputFile;
   }

  public void read() throws IOException  {
        File inputWorkbook = new File(inputFile);
        Workbook w;
        try {
            int rowCount = 0;
            int columnCount = 0;
            Cell rowData[] = null;
            // Get workbook instance
            w = Workbook.getWorkbook(inputWorkbook);
            // Get the first sheet
            Sheet s = w.getSheet(0);
            rowCount = s.getRows();          
            columnCount = s.getColumns();
         
            // Reading Individual Row Content
            for (int i = 0; i < rowCount; i++) {
                // Get Individual Row
                rowData = s.getRow(i);
                if (rowData.length > 1) {
                    System.out.println("\n");
                    for (int j = 0; j < columnCount; j++) {
                        if (rowData[j] != null)
                            System.out.print(rowData[j].getContents() +"----");
                    }
                }
            }
        } catch (BiffException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws IOException {
        ReadExcelSheet test = new ReadExcelSheet();
        test.setInputFile("D:\\testcodeline\\test\\Published_List 186.xls");
        test.read();
    }
}

Wednesday, May 11, 2011

Tricky way to convert an array list into a comma separated string

Today my husband suggested me a good way to convert an array list into string, i found it very efficient so sharing with you all.

Created a list l, added megha, dwivedi and jain into it. Need to store - megha, dwivedi, jain into a string so used toString() method.

List l = new ArrayList();
l.add("megha");
l.add("dwivedi");
l.add("jain");
String s = l.toString().substring(1, l.toString().length()-1);

If we perform toString on the list the output will be -

[megha, dwivedi, jain]

but i dont need square brackets so used substring method to cut 1st and last character, so variable 's' will contain - megha, dwivedi, jain

Other inefficient way which comes first in our mind is to iterate through list, get string one by one and append it comma separated, but using the above mentioned way we can avoid all those unnecessary loops and variables.

Thanks to my husband for explaining the same ;)

Monday, May 9, 2011

Run java code without main method

public class test{

 static{

System.out.println("M printing :p");

System.exit(0);

}

}

As soon as class loads it will run static initializer and before it tries to search for main method, we are exiting the program with System.exit, so prints the message and then will exit normally(without throwing any exception)

SQL related interview question

How to get the below outputs when executing a select on say employee table(suppose employee table is empty)-

1) No rows found

2) Zero rows found

Any idea??? :)


select * from employee  ---- it will give 1st output

and

select count(*) from employee -- it will give 2nd output

It looks so simple but doesn't click in mind when being interviewed :)

Thursday, January 6, 2011

Making Collections read only

Making a Collection Read-Only

Making a collection read-only involves wrapping the collection in another object whose mutation methods all throw UnsupportedOperationException.

List stuff = Arrays.asList(new String[]{"m", "d"});

// Make a list read-only

List list = new ArrayList(stuff);

list = Collections.unmodifiableList(list);

try {

// Try modifying the list

list.set(0, "value");

} catch (UnsupportedOperationException e) {

// Can't modify

}

// Make a set read-only

Set set = new HashSet(stuff);

set = Collections.unmodifiableSet(set);

// Make a map read-only

Map map = new HashMap();

// Add key/value pairs ...

map = Collections.unmodifiableMap(map);

Shuffling the Elements of a List or Array

Shuffling the Elements of a List or Array

Use Collections.shuffle() to randomly reorder the elements in a list.

// Create a list

List list = new ArrayList();

// Add elements to list

// Shuffle the elements in the list

Collections.shuffle(list);

// Create an array

String[] array = new String[]{"M", "e", "g", "h", "a"};

// Shuffle the elements in the array

Collections.shuffle(Arrays.asList(array));

Comparing three implementations of List interface

Comparing three implementations of List interface 

Classes implementing List

Underlying data structure

Pros

Cons

ArrayList

array

1.        Faster to access by index

 

2.        Faster than Vector as methods are not synchronized

1.        Insertion or deletion in the middle is slower.

2.        Not thread –safe.

3.        Searching is sequential and hence not very efficient.

Vector

array

1.        Faster to access by index.

 

2.        Thread-safe access

1.        Insertion or deletion in the middle is slower.

2.        Slower than ArrayList as methods are synchronized.

3.        Searching is sequential and hence not very efficient.

LinkedList

doubly linked list

1.        Allows faster inserts/delete at any location*

2.        Faster than Vector as methods are not synchronized.

1.        Accessing element by index is slower.

2.        Searching is sequential and hence not very efficient.