Monday, April 6, 2009

Sorting Objects in Java

Today we are talking about sorting.

What is sorting ?

Putting collection of data in some order is called sorting.


Luckily Java provides a Collections.sort method to sort a set of arraylist objects .Lets take a small example for sorting a collection of string objects.

package app;

import java.util.ArrayList;
import java.util.Collections;

public class SortingList
{

/**
* @param args
*/
public static void main(String[] args)
{
System.out.println("Sorting String Objects");
ArrayList Emp_list = new ArrayList();
Emp_list.add("Uday");
Emp_list.add("Mani");
Emp_list.add("Raja");
Emp_list.add("Yuva");
Emp_list.add("Abi");
Emp_list.add("Brindha");
System.out.println(Emp_list);
Collections.sort(Emp_list);
System.out.println(Emp_list);
}

}
Output :

Sorting String Objects
[Uday, Mani, Raja, Yuva, Abi, Brindha]
[Abi, Brindha, Mani, Raja, Uday, Yuva]

If you pass some objects other than string it will throw classcastException.

Why ?

String class implements comparable interface and overridden the compare method
thats why we can sort an array of String objects.if you want sort an object other than string
you should implement either comparator or comparable intefaces .

See the below program for sorting a Customer Objects

package app;
import java.util.*;

class Customer
{
int Cust_ID;
String Cust_Name;
String Ac_type;
int Balance_amt;

Customer()
{
}

Customer(int Id,
String Name,
String Type,
int amt)
{
this.Cust_ID = Id;
this.Cust_Name = Name;
this.Ac_type = Type;
this.Balance_amt = amt;
}

public Integer getId()
{
return Cust_ID;
}

public String getName()
{
return Cust_Name;
}

public Integer getBalance()
{
return Balance_amt;
}

@Override
public String toString()
{
// TODO Auto-generated method stub
return "EMPID :" + Cust_ID + "EMPNAME :" + Cust_Name + "A/C Type :"
+ Ac_type + "AMT :" + Balance_amt + "\n";
}
}
class Bank
{

final static Comparator EMP_ID =new Comparator(){
public int compare(Customer cust1, Customer cust2) {
return cust1.getId().compareTo(cust2.getId());
}
};
final static Comparator EMP_NAME =new Comparator(){
public int compare(Customer cust1, Customer cust2) {
return cust1.getName().compareTo(cust2.getName());
}
};
final static Comparator EMP_AMOUNT =new Comparator(){
public int compare(Customer cust1, Customer cust2) {
return cust1.getBalance().compareTo(cust2.getBalance());
}
};
public static void main(String st[])
{
ArrayList Emp_List = new ArrayList();
Emp_List.add(new Customer(118, "Raja", "Saving", 5000));
Emp_List.add(new Customer(136, "mani", "Saving", 8000));
Emp_List.add(new Customer(173, "Selva", "Saving", 15000));
Emp_List.add(new Customer(108, "kanna", "Saving", 56000));
Emp_List.add(new Customer(18, "Abi", "Saving", 12000));
System.out.println("Original List of Customer Objects");
System.out.println(Emp_List);
System.out.println("Original Customer Objects by Emp ID");
Collections.sort(Emp_List, EMP_ID);
System.out.println(Emp_List);
System.out.println("Original Customer Objects by Amount");
Collections.sort(Emp_List, EMP_AMOUNT);
System.out.println(Emp_List);


}
}

Output :

Original List of Customer Objects
[EMPID :118EMPNAME :RajaA/C Type :SavingAMT :5000
, EMPID :136EMPNAME :maniA/C Type :SavingAMT :8000
, EMPID :173EMPNAME :SelvaA/C Type :SavingAMT :15000
, EMPID :108EMPNAME :kannaA/C Type :SavingAMT :56000
, EMPID :18EMPNAME :AbiA/C Type :SavingAMT :12000
]
Original Customer Objects by Emp ID
[EMPID :18EMPNAME :AbiA/C Type :SavingAMT :12000
, EMPID :108EMPNAME :kannaA/C Type :SavingAMT :56000
, EMPID :118EMPNAME :RajaA/C Type :SavingAMT :5000
, EMPID :136EMPNAME :maniA/C Type :SavingAMT :8000
, EMPID :173EMPNAME :SelvaA/C Type :SavingAMT :15000
]
Original Customer Objects by Amount
[EMPID :118EMPNAME :RajaA/C Type :SavingAMT :5000
, EMPID :136EMPNAME :maniA/C Type :SavingAMT :8000
, EMPID :18EMPNAME :AbiA/C Type :SavingAMT :12000
, EMPID :173EMPNAME :SelvaA/C Type :SavingAMT :15000
, EMPID :108EMPNAME :kannaA/C Type :SavingAMT :56000
]

Friday, April 3, 2009

Sample Java Program - explaining each words

Sample Java Program - explaining each words
Lets take sample program in java and will research each and everthing
Class Test{

public static void main(String args[])
{

System.out.println("Welcome to Java program");

}

}
Now thing about following question :
1 Why the main method inside a Class rather than outside of class?
2 Why they decared main method as public ?
3 Will it compile if I declare private or other access specifier ?
4 why main class declared as static method? what is the purpose for static here ?
5 What happened if I decalre 'int' instead of void and return 0? Will it compile ?
6 Can I change the argument args[] to s[]?
7 Shall I call a main method from other class ?
8 what is System ?what is out ? what is println?

Understand the question and answer it .

Tuesday, March 24, 2009

How JVM works ?



From this week I will start write about Java language.If you are new to java language, these posts are very useful for learning java from the depth but its bit difficult to understand at your first step.For known user,its better to gain more information about java.I hope that my first topic will useful to all.

As we know,to run java program we need JVM(java virtual machine).This JVM converting your java byte code to machine understandable language .Fine ..! Let me explain first about parts of JVM and then how it works in OS.

JVM contains three parts

1. Class Loader
2. Byte code verifier
3. JIT Interpreter

Class Loader :
This class loader have two parts one is default class loader and another one is
custom class loader.

Default class loader:

Default class loader knows how to load class file from local system.It will works on regular situations, when you have java program fully compiled and waiting on your computer. Most of us running the program on this way only.

Custom class loader :

Custom class loader is, load a class file from website , other than local drive or network.
You can use custom class loader to

* Automatically verify a digital signature before excuting untrusted code
* Transparently decrypt code with a user supplied password
* Create dynamically built classes customized to the user's specific needs

The appletviewer contains the class loader that ,instead of looking in the localfilesytem for classes,access a remote server, loads
the raw byte code files via HTTP,and turns them into classes inside the JVM



Bytecode verifier :
Code may have come from the local system, or it may have travelled halfway around the planet. The bytecode verifier acts as a sort of gatekeeper: it ensures that code passed to the Java interpreter is in a fit state to be executed and can run without fear of breaking the Java interpreter. Imported code is not allowed to execute by any means until after it has passed the verifier's tests. Once the verifier is done, a number of important properties are known:

* There are no operand stack overflows or underflows
* The types of the parameters of all bytecode instructions are known to always be correct
* Object field accesses are known to be legal--private, public, or protected

While all this checking appears excruciatingly detailed, by the time the bytecode verifier has done its work, the Java interpreter can proceed, knowing that the code will run securely. Knowing these properties makes the Java interpreter much faster, because it doesn't have to check anything. There are no operand type checks and no stack overflow checks. The interpreter can thus function at full speed without compromising reliability.

JIT Interpreter:

It compiles the bytecode into platform-specific executable code that is immediately executed. Sun Microsystems suggests that it's usually faster to select the JIT compiler option, especially if the method executable is repeatedly reused.


After you've written a Java program, the source language statements are compiled by the Java compiler into bytecode and then JIT interpreter covert your byte code into machine understandable language .For ex ample, In windows JVM that convert byte code into windows understandable language the same way, linux JVM convert byte code into Linux understandable language.

Here you may ask a question that each JVM in each OS are different ?

Certainly ,Each JVM in each OS are different .

Quick View :

Soucre code compiled by java compiler and convert into bytecode.This byte code will available
as class file in Localfile system,network or remote server.Appropriate class loader will
load the class file and verify the code using with bytecode verifier.Once the
code verify by bytecode verifier,JIT interpreter will convert in to machine understandable language .Now the machine (OS) knows how do execute the program and
display the output .