25 December 2009

encryption in java

The SHA hash functions are a set of cryptographic hash functions designed by the National Security Agency (NSA) and published by the NIST as a U.S. Federal Information Processing Standard.
SHA stands for Secure Hash Algorithm.
The three SHA algorithms are structured differently and are distinguished as SHA-0, SHA-1, and SHA-2. The SHA-2 family uses an identical algorithm with a variable digest size which is distinguished as SHA-224, SHA-256, SHA-384, and SHA-512. 

SHA-1: The Secure Hash Algorithm (SHA) was developed by NIST and is specified in the Secure Hash Standard (SHS, FIPS 180). SHA-1 is a revision to this version and was published in 1994. It is also described in the ANSI X9.30 (part 2) standard. SHA-1 produces a 160-bit (20 byte) message digest. Although slower than MD5, this larger digest size makes it stronger against brute force attacks.

MD5: MD5 was developed by Professor Ronald L. Rivest in 1994. Its 128 bit (16 byte) message digest makes it a faster implementation than SHA-1.

Data Encryption using SHA - 512

import java.security.MessageDigest;
import java.math.BigInteger.*;
public class Encryption

public static String Password(String data)
    StringBuffer sb = new StringBuffer();
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
        byte[] digestBytes = messageDigest.digest();

        String hex = null;
        for (int i = 0; i < digestBytes.length; i++)
            hex = Integer.toHexString(0xFF & digestBytes[i]);
            if (hex.length() < 2)
        String psw = sb.toString();
    catch (Exception ex)
    return new String(sb);
public static void main(String[] args)
    Encryption e = new Encryption();
    String s1 = e.Password("ankit");
    System.out.println("Encrypted String is "+s1);

Data Encryption using MD5

import java.math.*;
import java.security.*;
import java.security.MessageDigest;
class encrypt1
    public static void main(String[] arr)
        try {
      String toEnc = "ankit"; // Value to encrypt
      MessageDigest mdEnc = MessageDigest.getInstance("MD5"); // Encryption algorithm
      mdEnc.update(toEnc.getBytes(), 0, toEnc.length());
      String md5 = new BigInteger(1, mdEnc.digest()).toString(16); // Encrypted string
        catch (Exception ex)

21 December 2009

How to get google to index images quickly

Pictures are a valuable way to attract visitors to your site, because visitors search for them using Google, Yahoo and Bing image search.
When an image is placed on a page, there is a space for two tags called ALT and TITLE. These tags are displayed to the user when the mouse hovers over a picture. Both an ALT and a TITLE tag are needed.
Before going to indexing, you should confirm about your images that they are visible google crawler

So how will you check it
Go to:


Some Guideline are here:-
  • Give proper alt, title to the image
  • Define the size(width and height) of image
  • Each image must have unique alt tag
  • Don't use src="images/abc.jpg". Better one is to used src="htttp://www.domain.com/images/abc.jpg"
  • So you have to use full image path to display image in google search.

sum of matrix in java

In this program we are going to calculate the sum of two matrix. To make this program, we need to declare two dimensional array of type integer. Firstly it calculates the length of the both the arrays. Now we need to make a matrix out of it. To make the matrix we will use the for loop. By making use of the for loop the rows and column will get divide. This process will be performed again for creating the second matrix.
After getting both the matrix with us, we need to sum both the matrix. The both matrix will be added by using the for loop with array[i][j]+array1[i][j]. The output will be displayed by using the println() method.

class summatrix
    public static void main(String[] args) 
            int array[][]= {{4,5,6},{6,8,9}};
            int array1[][]= {{5,4,6},{5,6,7}};
            System.out.println("Number of Row= " + array.length);
            System.out.println("Number of Column= " + array[1].length);
            int l= array.length;
            System.out.println("Matrix 1 : ");
            for(int i = 0; i < l; i++)
                for(int j = 0; j <= l; j++)
                    System.out.print(" "+ array[i][j]);
            int m= array1.length;
            System.out.println("Matrix 2 : ");
            for(int i = 0; i < m; i++)
                  for(int j = 0; j <= m; j++)
                        System.out.print(" "+array1[i][j]);
            System.out.println("Addition of both matrix : ");
            for(int i = 0; i < m; i++)
                  for(int j = 0; j <= m; j++)
                        System.out.print(" "+(array[i][j]+array1[i][j]));

18 December 2009

file upload using servlet

Hi friends
Here is the example to upload a file using java servlet technology.

<form action="http://your_host/servlet/UploadServlet?your_config" enctype="multipart/form-data" method="post">

<td> <input name="fname" size="20" type="file" /> </td>
<td> <input type="Submit" value="Upload" /> </td> </form>



import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;

public class UploadFile extends HttpServlet {

public void doPost(HttpServletRequest req HttpServletResponse res)

FileUpload fup new FileUpload();
boolean isMultipart FileUpload.isMultipartContent(req);
// Create a new file upload handler
DiskFileUpload upload new DiskFileUpload();

// Parse the request
List /* FileItem */ items upload.parseRequest(req);

Iterator iter items.iterator();
while (iter.hasNext()) {

FileItem item (FileItem) iter.next();

if (item.isFormField()) {
System.out.println( its a field );
} else {
System.out.println( its a file );
File cfile new File(item.getName());
File tosave new File(getServletContext().getRealPath( / ) cfile.getName());

}catch(Exception e){System.out.println(e);}

describe servlet in your web.xml file: 



  • Servlet's configuration file can be saved anywhere on your server. i.e. if you are using UploadServlet?config line we assume this file is saved under the root directory of  your servletrunner. 
  • You can use query string for servlet in this form too: 
    This way you can provide a name for the uploaded file right in the query string. This option could be useful if you are generating upload forms (pages) dynamically.


14 December 2009

split string in java

Java equivalent of PHP explode function

In PHP we can easily break a long string into smaller parts by using the explode() function of PHP.
$longstring="I am a cool guy";
$brokenstring=explode(" ", $longstring);
After the execution of the second command the variable $brokenstring is an array such that,


In java we use String.split() function that achieves the same objective.
class splitString
        public static void main(String[] args)
            String s1 = "I am a cool guy";
            String[] array = s1.split(" ");
            for(int i=0; i

array[0] ="I"
array[1] ="am"
array[2] ="a" 
array[3] ="cool"
array[4] ="guy" 

The output will be like:

binary search in java

Binary Search is the fast way to search a sorted array. The idea is to look at the element in the middle. If the key is equal to that, the search is finished. If the key is less than the middle element, do a binary search on the first half. If it's greater, do a binary search of the second half.

public class BinarySearch {
  private long[] a;

  private int nElems;

  public BinarySearch(int max) {
    a = new long[max]; // create array
    nElems = 0;

  public int size() {
    return nElems;

  public int find(long searchKey) {
    return recFind(searchKey, 0, nElems - 1);

  private int recFind(long searchKey, int lowerBound, int upperBound) {
    int curIn;

    curIn = (lowerBound + upperBound) / 2;
    if (a[curIn] == searchKey)
      return curIn; // found it
    else if (lowerBound > upperBound)
      return nElems; // can't find it
    else // divide range
      if (a[curIn] < searchKey) // in upper half
        return recFind(searchKey, curIn + 1, upperBound);
        // in lower half
        return recFind(searchKey, lowerBound, curIn - 1);

  public void insert(long value) {
    int j;
    for (j = 0; j < nElems; j++)
      // find where it goes
      if (a[j] > value) // (linear search)
    for (int k = nElems; k > j; k--)
      // move bigger ones up
      a[k] = a[k - 1];
    a[j] = value; // insert it
    nElems++; // increment size

  public void display() {
    for (int j = 0; j < nElems; j++)
      System.out.print(a[j] + " ");
  public static void main(String[] args) {
    int maxSize = 100;
    BinarySearch arr = new BinarySearch(maxSize);


    arr.display(); // display array

    int searchKey = 12; // search for item
    if (arr.find(searchKey) != arr.size())
      System.out.println("Found " + searchKey);
      System.out.println("Can't find " + searchKey);
The advantage of a binary search over a linear search is astounding for large numbers. For an array of a million elements, binary search, O(log N), will find the target element with a worst case of only 20 comparisons. Linear search, O(N), on average will take 500,000 comparisons to find the element.
This performance comes at a price - the array must be sorted first. Because sorting isn't a fast operation, O(N log N), it may not be worth the effort to sort when there are only a few searches.
Output will be:

First I have used searchKey = 4
That was not in array. So it has given result Can't finf 4
Next Change value searchKey = 12
It will give you the result Found 12 

09 December 2009

sort an array of object in java

The java.util.Arrays class has static methods for sorting arrays, both arrays of primitive types and object types. The sort method can be applied to entire arrays, or only a particular range. For object types you can supply a comparator to define how the sort should be performed. All object types that implement Comparable (ie, defines compareTo() method), can be sorted with using a comparator.

import java.util.Arrays;

public class sortobjects {
  public static void main(String[] args) {
    String names[] = { "Ankit", "OM", "Deepti", "Anu" };
    for (int i = 0; i < names.length; i++) {
      String name = names[i];
      System.out.print("name = " + name + "; ");

    Person persons[] = new Person[4];
    persons[0] = new Person("Ankit");
    persons[1] = new Person("OM");
    persons[2] = new Person("Deepti");
    persons[3] = new Person("Anu");
    Arrays.sort(persons);    //Sorts the elements of the array of a primitive type into ascending order using their natural ordering.

    for (int i = 0; i < persons.length; i++) {
      Person person = persons[i];
      System.out.println("\n\nperson = " + person);
class Person implements Comparable {
  private String name;

  public Person(String name) {
    this.name = name;

  public int compareTo(Object o) {
    Person p = (Person) o;
    return this.name.compareTo(p.name);
  public String toString() {
    return name;
The output will be:-

07 December 2009

Quick sort in java

Quick sort algorithm is developed by C. A. R. Hoare. Quick sort is a comparison sort. The working of quick sort algorithm is depending on a divide-and-conquer strategy. A divide and conquer strategy is dividing an array into two sub-arrays. Quick sort is one of the fastest and simplest sorting algorithm. The complexity of quick sort in the average case is Θ(n log(n)) and in the worst case is Θ(n2).

Working of quick sort algorithm:
Input:12 9 4 99 120 1 3 10 13

Output:1 3 4 10 12 13 99 120
The code of the program :

public class QuickSort{
  public static void main(String a[]){
    int i;
    int array[] = {12,9,4,99,120,1,3,10,13};

    System.out.println("       Quick Sort\n\n");
    System.out.println("Values Before the sort:\n");
    for(i = 0; i < array.length; i++)
      System.out.print( array[i]+"  ");
    System.out.print("\nValues after the sort:\n\n");
    for(i = 0; i
      System.out.print(array[i]+"  ");


  public static void quick_srt(int array[],int low, int n){
    int lo = low;
    int hi = n;
    if (lo >= n) {
    int mid = array[(lo + hi) / 2];
    while (lo < hi) {
      while (lo< mid) {
      while (lo mid) {
      if (lo < hi) {
        int T = array[lo];
        array[lo] = array[hi];
        array[hi] = T;
    if (hi < lo) {
      int T = hi;
      hi = lo;
      lo = T;
    quick_srt(array, low, lo);
    quick_srt(array, lo == low ? lo+1 : lo, n);

05 December 2009

Sorting an array of integers in java

In computer science and mathematics, a sorting algorithm is an algorithm that puts elements of a list in a certain order.
Summaries of popular sorting algorithms
  1. Bubble sort
  2. Insertion sort
  3. Shell sort
  4. Merge sort
  5. Heap sort
  6. Quick sort
  7. Bucket sort
  8. Radix sort
  9. Distribution sort
  10. Shuffle sort
Make a class named whatever you want like as

public class SortNumbers {

  public static void sort(int[] nums) {
     for (int i = 0; i < nums.length; i++) {
      int min = i;
      for (int j = i; j < nums.length; j++) {
        if (nums[j] < nums[min])
          min = j;
      int tmp;
      tmp = nums[i];
      nums[i] = nums[min];
      nums[min] = tmp;

  public static void main(String[] args) {
    int[] nums = new int[args.length]; // Create an array to hold numbers
    for (int i = 0; i < nums.length; i++)    
      nums[i] = Integer.parseInt(args[i]);

    sort(nums); // Sort them
    for (int i = 0; i < nums.length; i++)
      // Print them out
Compile it as:

javac SortNumbers.java
java SortNumbers 45 89 21 74 15 -1 25 7
The output will be as:


03 December 2009

How to get values from command line in java

Hi friends
A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.
The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run.
When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings. 

This example is for all type data types, because from command line all the arguments are of string type.

class getcommandtext
    public static void main(String[] args)
        for (String s: args)

For Numeric Command line Argument:-
If an application needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as "12", to a numeric value.

class numericargument
    public static void main(String[] args)
        int[] firstArg =  new int[args.length];
        for (int i=0; i
             try {
                  firstArg[i] = Integer.parseInt(args[i]);
                          System.out.println("Argument at index "+ i + " is " + firstArg[i]);
            catch (NumberFormatException e)
                System.err.println("Argument must be an integer");

parseInt throws a NumberFormatException if the format of args[i] isn't valid. All of the Number classes — Integer, Float, Double, and so on — have parseXXX methods that convert a String representing a number to an object of their type.

If you run this program as
javac numericargument.java
java numericargument 1 2 3 4 5

The output will be as:
Argument at index 0 is 1
Argument at index 1 is 2
Argument at index 2 is 3
Argument at index 3 is 4
Argument at index 4 is 5

01 December 2009

How to Try the New Google Search

Hi Firends

  1. Go to Google.com
  2.  Once it loads, enter this code into your web browser's URL address field:

3. Hit the enter

 4. Reload or open a new Google.com page and you will have access to the new user interface

How to write a java program

Dear friends,        

Java technology allows you to work and play in a secure computing environment. 

Java allows you to play online games, chat with people around the world, calculate your mortgage interest, and view images in 3D, just to name a few. 

Now to write a program java first

Class test
        public static void main(String[] args)
             System.out.println("Hello! this is my first java program.");



  1. Save this as test.java
  2. open your command prompt
  3. type javac test.java
  4. A class test.class will be created in corresponding directory
  5. type java test
  6. It will print Hello! this is my first java program