Tuesday, 17 January 2012

Reading and writing data from Excel sheet using JExcel API

Using Java we can read the data from Excel sheets by creating type1 driver , but here we are taking help of JExcelapi we can able to read data directly from the Excel sheets.
Steps to be follow:
Step 1:
download JExcel api from here

Step2:
after downloading extract the zip file.
make jxl.jar available to your class path.

Step 3:
create a Excel sheet with some data

Step 4:
in this step we are reading data from the Excel sheet.
use the below java code:

package com.vaani.excel.jexcel;

import java.io.File;

import java.io.IOException;

import java.util.Date;

import jxl.*;

import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.Number;

public class ReadWriteInExcel {


 public static void readExcelFile() throws IOException, BiffException {

  Workbook workbook = Workbook.getWorkbook(
    new File("---/././file.xls"));

  // my excel sheet name is contacts, iam given the complete path.
// iam reading data from the sheet1

  Sheet sheet = workbook.getSheet(0); 

  // here iam reading the data of 1st column data up three cells

  Cell a1 = sheet.getCell(0,0);
  Cell b2 = sheet.getCell(0,1);
  Cell c2 = sheet.getCell(0,2);

  //getting  the data from cells
  String stringa1 = a1.getContents();
  String stringb2 = b2.getContents();
  String stringc2 = c2.getContents();

  //printing the data
  System.out.println("a1–>"+stringa1);
  System.out.println("b2–>"+stringb2);
  System.out.println("c3–>"+stringc2);


 }

 public static void writeInExcelFile(String args[]) 
throws IOException, WriteException
 {
  // STEP 1:
  // the first step is to create a writable workbook using the 
factory method on the Workbook class.
  WritableWorkbook workbook = Workbook.createWorkbook(
new File("/some file.xls"));
  //test.xls is my work book
  // STEP 2:
  //// sheet name 
WritableSheet sheet = workbook.createSheet("First Sheet",0); 
  //STEP 3:
  //adding(inserting) name to the sheet at location (0,2)
  Label label = new Label(0,2,"A label record");
  sheet.addCell(label);
  //adding number to the sheet at location (1,2)
  Number number = new Number(1,2,3.1459);
  sheet.addCell(number);
  //Step 4:
  //close the all opened connections
  workbook.write();
  workbook.close();
 }


}



Monday, 16 January 2012

Modulus operator in java

Unlike C, Java allows using the % for both integer and floating point and (unlike C89 and C++) it is well-defined for all inputs (including negatives):

x = n % d
 
n - dividend
d - divisor
 
The result of a floating-point remainder operation is determined by the rules of IEEE arithmetic:
  • If either operand is NaN, the result is NaN
    ...i.e. x=NaN, if n or d is NaN
  • If the result is not NaN, the sign of the result equals the sign of the dividend.
  • If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
  • If the dividend is finite and the divisor is an infinity, the result equals the dividend.
  • If the dividend is a zero and the divisor is finite, the result equals the dividend.
  • In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from the division of a dividend n by a divisor d is defined by the mathematical relation r=n-(d·q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d.

So for your example, 0.5/0.3 = 1.6... . q has the same sign (positive) as 0.5 (the dividend), and the magnitude is 1 (integer with largest magnitude not exceeding magnitude of 1.6...), and r = 0.5 - (0.3 * 1) = 0.2

Arrays in Java

Java Array Declaration

Java Array Instantiation
Shorthand method
Java has a shorthand to create an array object and supply initial values at the same time. Here's an example of the syntax at work:

int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };
Notice that you do not call new when you use this syntax. 

Memory Allocation and initialization
char[] s = new char[10];
for( int i=0; i<26; i++){
    s[i] = (char) ('A' + i);
  }

Array of references can be made similarly:
Point[] p = new Point[26];


No need to pass length of array to function unlike in cpp
To find the number of elements of an array, use array.length. For example,
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);


Iterating over array
Java provides 2 ways of iterating over arrays.
Traditional or old style iteration
for (int i = 0; i < a.length; i++)
    System.out.println(a[i]);


New style

JDK 5.0 introduces a powerful looping construct that allows you to loop through each element in an array (as well as other collections of elements) without having to fuss with index values.

for (variable : collection)
    statement

sets the given variable to each element of the collection and then executes the statement (which, of course, may be a block). The collection expression must be an array or an object of a class that implements the Iterable interface, such as ArrayList For example,



for (int element : a)
    System.out.println(element);

So here we are taking element from array a and dumping it on output.

Note: println prints each element of the array a on a separate line.

You should read this loop as "for each element in a". The designers of the Java language considered using keywords such as foreach and in. But this loop was a late addition to the Java language, and in the end nobody wanted to break old code that already contains methods or variables with the same names (such as System.in).

"for each" vs for
The loop variable of the "for each" loop traverses the elements of the array, not the index values.
The "for each" loop is a pleasant improvement over the traditional loop if you need to process all elements in a collection. However, there are still plenty of opportunities to use the traditional for loop. For example, you may not want to traverse the entire collection, or you may need the index value inside the loop.
Jakarta ArrayUtils class: http://jakarta.apache.org/commons/lang/api/index.html

Java IO Overview

We can diagrammatically cover how java io looks like from bird eye view.

So this is basic java IO :
Now looking at the class hierarchy :

Sunday, 15 January 2012

What are variables default values?

Variables declared in methods and in blocks are called local variables. Local variable are not initialized when they are created at method invocation. Therefore, a local variable must be initialized explicitly before being used. Otherwise the compiler will flag it as error when the containing method or block is executed.

Example:

public class SomeClassName{
public static void main(String args[]){ int total; System.out.println("The incremented total is " + total + 3); //(1)
}
}
The compiler complains that the local variable total used in println statement at (1) may not be initialized.
Initializing the local variable total before usage solves the problem:

public class SomeClassName{

public static void main(String args[]){int total = 45; //Local variable initialized with value 45 System.out.println("The incremented total is " + total+ 3); //(1)
}
}

Fields initialization

If no initialization is provided for an instance or static variable, either when declared or in an initializer block, then it is implicitly initialized with the default value of its type.
An instance variable is initialized with the default value of its type each time the class is instantiated, that is for every object created from the class.
A static variable is initialized with the default value of its type when the class is first loaded.


Data Type

Default Value
booleanfalse
char
'/u0000'
Integer(byte,short,int,long)0L for long, 0 for others
Floating-point(float,double)0.0F or 0.0D
reference typenull


Note: Reference fields are always initialized with the value null if no initialization is provided

Example of default values for fields

public class House{

// Static variable
static long similarHouses; //Default value 0L when class is loaded.

// Instance variables
String houseName; //Implicitly set to default value null
int numberOfRooms=5; // Explicitly set to 5
boolean hasPet; // Implicitly set to default value false

//..
}

How to declare and initialize a variable

A variable in Java has a type, name and a value. A variable may store of value of either:
- a primitive data type such as int, boolean, char.
or
- a reference to an object, also called reference variable.


for example:
int i; //variable i that can store an int value. boolean isDone; //Variable isDone that can store a boolean value.//Variables a, f and r that can store a char value each:
char a,f,r;

//Equivalent to the three separate declarations:
char a; char f; char r;

What we just deed above is called variable declaration. By declaring variable we are implicitly allocating memory for these variables and determining the value types that can be stored in them.
So, in the example above, we named a variable: isDone that can store a boolean value, but not initialized yet.

Giving a variable a value when declared is called initialization. Further, we can declare and initialize a variable in one go. For example, we could have declared and initialized our variables of the previous example:

int i = 101; //variable i initialized with the value 101://variable isDone initialized with the boolean value true.
boolean isDone = true;
// variables a,f and r initialized with the values 'a','f' and 'r' //respectively: char a = 'a', f='f', r='r';
//
equivalent to:
char a = 'a';char f = 'f';char r = 'r';


Analogous to declaring variables to denote primitive values, we can declare a variable denoting an object reference, that's; a variable having one of the following reference types: a class, an array, or an interface.

For instance (see also Class Instantiation ):
//declaring a redCar and a blueCar of class Car.
Car redCar, blueCar;

Please note that declarations above do not create any object of type Car. These are just variables that can store references to objects of class Car but no reference is created yet.
A reference variable has to be instantiated before being used. So:// declaring and initializing the redCar reference variable
Car redCar=new Car("red");
An object of class Car is created using the keyword new together with the Constructor call Car("red"), then stored in the variable redCar which is now ready to be manipulated.

Floats