Saturday 11 June 2011

sorting words in java

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.*;     // For ActionListener ...
import javax.swing.*;        // For components
import java.util.*;          // For StringTokenizer

///////////////////////////////////////////////////////////////// SortWords3
public class SortWords3 extends JFrame {
    //============================================================ variables
    JTextField inField;   // get the input from here
    JTextField outField;  // put the output here

    //========================================================== constructor
    public SortWords3() {
        inField = new JTextField(30);   // use this for input
        JButton sortWordsButton = new JButton("Sort Words");
        sortWordsButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                List words = stringToList(inField.getText());
                Collections.sort(words);
                outField.setText(listToString(words, ", "));
            }
          });

        outField = new JTextField(30);  // use this for output
        outField.setEditable(false);    // don't let the user change it

        // Layout the fields
        Container content = this.getContentPane();
        content.setLayout(new FlowLayout());
        content.add(new JLabel("Input"));
        content.add(inField);
        content.add(sortWordsButton);
        content.add(new JLabel("Sorted output"));
        content.add(outField);

        this.setTitle("SortWords3");
        this.pack();
    }//end constructor

   
    //========================================================= stringToList
    // Put all the "words" in a string into an array.
    List stringToList(String wordString) {
        ArrayList result = new ArrayList(20);
        StringTokenizer st = new StringTokenizer(wordString);
        while (st.hasMoreTokens()) { //--- Loop, getting each token
            result.add(st.nextToken());
        }
        return result;
    }//end stringToArray

   
    //========================================================= listToString
    // Convert list of strings to one string with 'separator' between each.
    String listToString(List a, String separator) {
        StringBuffer result = new StringBuffer(40);
        for (Iterator iter = a.iterator(); iter.hasNext(); ) {
            result.append(iter.next() + separator);
        }
        return result.toString();
    }//endmethod arrayToString
   
   
    //================================================================= main
    public static void main(String[] args) {
        JFrame window = new SortWords3();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setVisible(true);
    }//end main
}//endclass SortWords3



Digital Clock in java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

///////////////////////////////////////////////////////////// TextClock2
public class TextClock2 extends JApplet {

    //====================================================== constructor
    public TextClock2() {
        add(new Clock());
    }

    //============================================================= main
    public static void main(String[] args) {
        JFrame window = new JFrame("Time of Day");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        window.setContentPane(new Clock());

        window.pack();
        window.setVisible(true);
        System.out.println(window.getContentPane().size());
    }
}
 
---------------------------------------------------------------------- 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Calendar;

///////////////////////////////////////////////////////////// Clock
class Clock extends JTextField {
    javax.swing.Timer m_t;

    //================================================== constructor
    public Clock() {
        //... Set some attributes.
        setColumns(6);
        setFont(new Font("sansserif", Font.PLAIN, 48));

        //... Create a 1-second timer.
        m_t = new javax.swing.Timer(1000, new ClockTickAction());
        m_t.start();  // Start the timer
    }

    /////////////////////////////////////////// inner class listener
    private class ClockTickAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //... Get the current time.
            Calendar now = Calendar.getInstance();
            int h = now.get(Calendar.HOUR_OF_DAY);
            int m = now.get(Calendar.MINUTE);
            int s = now.get(Calendar.SECOND);
            setText("" + h + ":" + m + ":" + s);
        }
    }
}

analog clock in java



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;

///////////////////////////////////////////////////////////// ClockAnalogBuf
public class ClockAnalogBuf extends JApplet {
    
    //=============================================================== fields
    private Clock _clock;                        // Our clock component.
    
    //================================================================= main
    public static void main(String[] args) {
        JFrame window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setTitle("Analog Clock");
        window.setContentPane(new ClockAnalogBuf());
        window.pack();                          // Layout components
        window.setLocationRelativeTo(null);     // Center window.
        window.setVisible(true);
    }
    
    //========================================================== constructor
    public ClockAnalogBuf() {
        //... Create an instance of our new clock component.
        _clock = new Clock();
        
        //... Set the applet's layout and add the clock to it.
        setLayout(new BorderLayout());
        add(_clock, BorderLayout.CENTER);
        
        //... Start the clock running.
        start(); 
    }
    
    //=============================================================== start
    @Override public void start() {
        _clock.start();
    }
    
    //================================================================ stop
    @Override public void stop() {
        _clock.stop();
    }
}

 --------------------------------------------------------------------------------------------------



import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;

//////////////////////////////////////////////////////////////// Clock class
class Clock extends JComponent {
   
    //============================================================ constants
    private static final double TWO_PI   = 2.0 * Math.PI;
   
    private static final int    UPDATE_INTERVAL = 100;  // Millisecs
   
    //=============================================================== fields
    private Calendar _now = Calendar.getInstance();  // Current time.
   
    private int _diameter;                 // Height and width of clock face
    private int _centerX;                  // x coord of middle of clock
    private int _centerY;                  // y coord of middle of clock
    private BufferedImage _clockImage;     // Saved image of the clock face.
   
    private javax.swing.Timer _timer;      // Fires to update clock.
   
    //==================================================== Clock constructor
    public Clock() {
        setPreferredSize(new Dimension(300,300));
       
        _timer = new javax.swing.Timer(UPDATE_INTERVAL, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                updateTime();
                repaint();
            }
        });
    }
   
    //================================================================ start
    /** Start the timer. */
    public void start() {
        _timer.start();
    }
   
    //================================================================= stop
    /** Stop the timer. */
    public void stop() {
        _timer.stop();
    }
   
    //=========================================================== updateTime
    private void updateTime() {
        //... Avoid creating new objects.
        _now.setTimeInMillis(System.currentTimeMillis());
    }
   
    //======================================================= paintComponent
    @Override public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
       
        //... The panel may have been resized, get current dimensions
        int w = getWidth();
        int h = getHeight();
        _diameter = ((w < h) ? w : h);
        _centerX = _diameter / 2;
        _centerY = _diameter / 2;
       
        //... Create the clock face background image if this is the first time,
        //    or if the size of the panel has changed
        if (_clockImage == null
                || _clockImage.getWidth() != w
                || _clockImage.getHeight() != h) {
            _clockImage = (BufferedImage)(this.createImage(w, h));
           
            //... Get a graphics context from this image
            Graphics2D g2a = _clockImage.createGraphics();
            g2a.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                 RenderingHints.VALUE_ANTIALIAS_ON);
            drawClockFace(g2a);
        }
       
        //... Draw the clock face from the precomputed image
        g2.drawImage(_clockImage, null, 0, 0);
       
        //... Draw the clock hands dynamically each time.
        drawClockHands(g2);
    }
   
    //====================================== convenience method drawClockHands
    private void drawClockHands(Graphics2D g2) {
        //... Get the various time elements from the Calendar object.
        int hours   = _now.get(Calendar.HOUR);
        int minutes = _now.get(Calendar.MINUTE);
        int seconds = _now.get(Calendar.SECOND);
        int millis  = _now.get(Calendar.MILLISECOND);
       
        //... second hand
        int handMin = _diameter / 8;    // Second hand doesn't start in middle.
        int handMax = _diameter / 2;    // Second hand extends to outer rim.
        double fseconds = (seconds + (double)millis/1000) / 60.0;
        drawRadius(g2, fseconds, 0, handMax);
       
        //... minute hand
        handMin = 0;                    // Minute hand starts in middle.
        handMax = _diameter / 3;
        double fminutes = (minutes + fseconds) / 60.0;
        drawRadius(g2, fminutes, 0, handMax);
       
        //... hour hand
        handMin = 0;
        handMax = _diameter / 4;
        drawRadius(g2, (hours + fminutes) / 12.0, 0, handMax);
    }
   
    //======================================= convenience method drawClockFace
    private void drawClockFace(Graphics2D g2) {
        // ... Draw the clock face.  Probably into a buffer.       
        g2.setColor(Color.orange);
        g2.fillOval(0, 0, _diameter, _diameter);
        g2.setColor(Color.BLACK);
        g2.drawOval(0, 0, _diameter, _diameter);
       
        int radius = _diameter / 2;
       
        //... Draw the tick marks around the circumference.
        for (int sec = 0; sec < 60; sec++) {
            int tickStart;
            if (sec%5 == 0) {
                tickStart = radius - 10;  // Draw long tick mark every 5.
            } else {
                tickStart = radius - 5;   // Short tick mark.
            }
            drawRadius(g2, sec / 60.0, tickStart , radius);
        }
    }
   
    //==================================== convenience method drawRadius
    // This draw lines along a radius from the clock face center.
    // By changing the parameters, it can be used to draw tick marks,
    // as well as the hands.
    private void drawRadius(Graphics2D g2, double percent,
                            int minRadius, int maxRadius) {
        //... percent parameter is the fraction (0.0 - 1.0) of the way
        //    clockwise from 12.   Because the Graphics2D methods use radians
        //    counterclockwise from 3, a little conversion is necessary.
        //    It took a little experimentation to get this right.
        double radians = (0.5 - percent) * TWO_PI;
        double sine   = Math.sin(radians);
        double cosine = Math.cos(radians);
       
        int dxmin = _centerX + (int)(minRadius * sine);
        int dymin = _centerY + (int)(minRadius * cosine);
       
        int dxmax = _centerX + (int)(maxRadius * sine);
        int dymax = _centerY + (int)(maxRadius * cosine);
        g2.drawLine(dxmin, dymin, dxmax, dymax);
    }
}


Thursday 9 June 2011

Exception handling in java


Example:

// File Name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception
{
   private double amount;
   public InsufficientFundsException(double amount)
   {
      this.amount = amount;
   } 
   public double getAmount()
   {
      return amount;
   }
}
To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException.
// File Name CheckingAccount.java
import java.io.*;

public class CheckingAccount
{
   private double balance;
   private int number;
   public CheckingAccount(int number)
   {
      this.number = number;
   }
   public void deposit(double amount)
   {
      balance += amount;
   }
   public void withdraw(double amount) throws
                              InsufficientFundsException
   {
      if(amount <= balance)
      {
         balance -= amount;
      }
      else
      {
         double needs = amount - balance;
         throw new InsufficientFundsException(needs);
      }
   }
   public double getBalance()
   {
      return balance;
   }
   public int getNumber()
   {
      return number;
   }
}
The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount.
// File Name BankDemo.java
public class BankDemo
{
   public static void main(String [] args)
   {
      CheckingAccount c = new CheckingAccount(101);
      System.out.println("Depositing $500...");
      c.deposit(500.00);
      try
      {
         System.out.println("\nWithdrawing $100...");
         c.withdraw(100.00);
         System.out.println("\nWithdrawing $600...");
         c.withdraw(600.00);
      }catch(InsufficientFundsException e)
      {
         System.out.println("Sorry, but you are short $"
                                  + e.getAmount());
         e.printStackTrace();
      }
    }
}
Compile all the above three files and run BankDemo, this would produce following result:
Depositing $500...

Withdrawing $100...

Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
        at CheckingAccount.withdraw(CheckingAccount.java:25)
        at BankDemo.main(BankDemo.java:13)

Exception Example in java


public class ExcepTest{

   public static void main(String args[]){
      int a[] = new int[2];
      try{
         System.out.println("Access element three :" + a[3]);
      }catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Exception thrown  :" + e);
      }
      finally{
         a[0] = 6;
         System.out.println("First element value: " +a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}


Simple Thread in java

public class SimpleThread extends Thread {
  private int countDown = 5;
  private static int threadCount = 0;
  public SimpleThread() {
    super("" + ++threadCount)// Store the thread name
    start();
  }
  public String toString() {
    return "#" + getName() ": " + countDown;
  }
  public void run() {
    while(true) {
      System.out.println(this);
      if(--countDown == 0return;
    }
  }
  public static void main(String[] args) {
    for(int i = 0; i < 5; i++)
      new SimpleThread();
  }
}




Tuesday 7 June 2011

Array of Strings


public class Welcome
{
public static void main(String[]args){

String[] greeting = new String[3];

greeting[0] = "Welcome to core Java";

greeting[1] = "by Sateesh";

greeting[2] = "bagadhi";

for(int i=0; i<greeting.length; i++)

System.out.println(greeting[i]);

}

}


Monday 6 June 2011

Merge Sort in java


public class MergeSortArray {
  private long[] theArray;

  private int nElems;

  public MergeSortArray(int max) {
    theArray = new long[max];
    nElems = 0;
  }

  public void insert(long value) {
    theArray[nElems] = value; // insert it
    nElems++; // increment size
  }

  public void display() {
    for (int j = 0; j < nElems; j++)
      System.out.print(theArray[j] + " ");
    System.out.println("");
  }

  public void mergeSort() {
    long[] workSpace = new long[nElems];
    recMergeSort(workSpace, 0, nElems - 1);
  }

  private void recMergeSort(long[] workSpace, int lowerBound, int upperBound) {
    if (lowerBound == upperBound) // if range is 1,
      return; // no use sorting
    else { // find midpoint
      int mid = (lowerBound + upperBound) / 2;
      // sort low half
      recMergeSort(workSpace, lowerBound, mid);
      // sort high half
      recMergeSort(workSpace, mid + 1, upperBound);
      // merge them
      merge(workSpace, lowerBound, mid + 1, upperBound);
    }
  }

  private void merge(long[] workSpace, int lowPtr, int highPtr, int upperBound) {
    int j = 0; // workspace index
    int lowerBound = lowPtr;
    int mid = highPtr - 1;
    int n = upperBound - lowerBound + 1; // # of items

    while (lowPtr <= mid && highPtr <= upperBound)
      if (theArray[lowPtr] < theArray[highPtr])
        workSpace[j++] = theArray[lowPtr++];
      else
        workSpace[j++] = theArray[highPtr++];

    while (lowPtr <= mid)
      workSpace[j++] = theArray[lowPtr++];

    while (highPtr <= upperBound)
      workSpace[j++] = theArray[highPtr++];

    for (j = 0; j < n; j++)
      theArray[lowerBound + j] = workSpace[j];
  }

  public static void main(String[] args) {
    int maxSize = 100; // array size
    MergeSortArray arr = new MergeSortArray(maxSize); // create the array

    arr.insert(14);
    arr.insert(21);
    arr.insert(43);
    arr.insert(50);
    arr.insert(62);
    arr.insert(75);
    arr.insert(14);
    arr.insert(2);
    arr.insert(39);
    arr.insert(5);
    arr.insert(608);
    arr.insert(36);

    arr.display();

    arr.mergeSort();

    arr.display();
  }
}


Bubble Sort in java


public class BubbleSort {
  private long[] a;

  private int nElems;

  public BubbleSort(int max) {
    a = new long[max];
    nElems = 0;
  }

  //   put element into array
  public void insert(long value) {
    a[nElems] = value;
    nElems++;
  }

  //   displays array contents
  public void display() {
    for (int j = 0; j < nElems; j++)
      System.out.print(a[j] + " ");
    System.out.println("");
  }

  public void bubbleSort() {
    int out, in;

    for (out = nElems - 1; out > 1; out--)
      // outer loop (backward)
      for (in = 0; in < out; in++)
        // inner loop (forward)
        if (a[in] > a[in + 1]) // out of order?
          swap(in, in + 1); // swap them
  }

  private void swap(int one, int two) {
    long temp = a[one];
    a[one] = a[two];
    a[two] = temp;
  }

  public static void main(String[] args) {
    int maxSize = 100; // array size
    BubbleSort arr; // reference to array
    arr = new BubbleSort(maxSize);

    arr.insert(77); // insert 10 items
    arr.insert(66);
    arr.insert(44);
    arr.insert(34);
    arr.insert(22);
    arr.insert(88);
    arr.insert(12);
    arr.insert(00);
    arr.insert(55);
    arr.insert(33);

    arr.display();

    arr.bubbleSort();

    arr.display();
  }
}


selection sort in java


   
public class SelectionSort {
  private long[] a;

  private int nElems;

  public SelectionSort(int max) {
    a = new long[max];
    nElems = 0;
  }

  public void insert(long value) {
    a[nElems] = value;
    nElems++;
  }

  public void display() {
    for (int j = 0; j < nElems; j++)
      System.out.print(a[j] + " ");
    System.out.println("");
  }

  public void selectionSort() {
    int out, in, min;

    for (out = 0; out < nElems - 1; out++) // outer loop
    {
      min = out; // minimum
      for (in = out + 1; in < nElems; in++)
        // inner loop
        if (a[in] < a[min]) // if min greater,
          min = in; // a new min
      swap(out, min); // swap them
    }
  }

  private void swap(int one, int two) {
    long temp = a[one];
    a[one] = a[two];
    a[two] = temp;
  }

  public static void main(String[] args) {
    int maxSize = 100;
    SelectionSort arr; // reference to array
    arr = new SelectionSort(maxSize); // create the array

    arr.insert(17); // insert 10 items
    arr.insert(29);
    arr.insert(34);
    arr.insert(45);
    arr.insert(52);
    arr.insert(68);
    arr.insert(71);
    arr.insert(80);
    arr.insert(96);
    arr.insert(33);

    arr.display();

    arr.selectionSort();

    arr.display();
  }

}


string sorting in java


import java.util.Arrays;

public class StringSorting {
  public static void main(String[] args) {
    String[] sa = new String[] { "d", "e", "a", "c", "g" };

    System.out.println("Before sorting: " + Arrays.asList(sa));
    Arrays.sort(sa);
    System.out.println("After sorting: " + Arrays.asList(sa));
  }
}

Simple sort using java


public class SortDemo {
    public static void main(String[] args) {
        int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,
                              2000, 8, 622, 127 };

        for (int i = arrayOfInts.length; --i >= 0; ) {
            for (int j = 0; j < i; j++) {
                if (arrayOfInts[j] > arrayOfInts[j+1]) {
                    int temp = arrayOfInts[j];
                    arrayOfInts[j] = arrayOfInts[j+1];
                    arrayOfInts[j+1] = temp;
                }
            }
        }

        for (int i = 0; i < arrayOfInts.length; i++) {
            System.out.print(arrayOfInts[i] + " ");
        }
        System.out.println();
    }
}


queue implementation in java


import java.io.*;
import java.util.*;

public class QueueImplement{
LinkedList<Integer> list;
String str;
int num;
public static void main(String[] args){
QueueImplement q = new QueueImplement();
}
public QueueImplement(){
try{
list = new LinkedList<Integer>();
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader bf = new BufferedReader(ir);
System.out.println("Enter number of elements : ");
str = bf.readLine();
if((num = Integer.parseInt(str)) == 0){
System.out.println("You have entered either zero/null.");
System.exit(0);
}
else{
System.out.println("Enter elements : ");
for(int i = 0; i < num; i++){
str = bf.readLine();
int n = Integer.parseInt(str);
list.add(n);
}
}
System.out.println("First element :" + list.removeFirst());
System.out.println("Last element :" + list.removeLast());
System.out.println("Rest elements in the list :");
while(!list.isEmpty()){
System.out.print(list.remove() + "\t");
}
}
catch(IOException e){
System.out.println(e.getMessage() + " is not a legal entry.");
System.exit(0);
}
}
}



stack demo in java


import java.util.*;

public class StackDemo{
public static void main(String[] args) {
Stack stack=new Stack();
stack.push(new Integer(10));
stack.push("a");
System.out.println("The contents of Stack is" + stack);
System.out.println("The size of an Stack is" + stack.size());
System.out.println("The number poped out is" + stack.pop());
System.out.println("The number poped out is " + stack.pop());
//System.out.println("The number poped out is" + stack.pop());
System.out.println("The contents of stack is" + stack);
System.out.println("The size of an stack is" + stack.size());
}
}



display month calendar in java


import java.util.*;
import java.text.*;

public class MonthCalender {

public final static String[] monthcalender = {
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};

public final static int daysinmonths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

private void displayMonth(int month, int year) {

// The number of days to leave blank at
// the start of this month.

int blankdays = 0;
System.out.println("  " + monthcalender[month] + " " + year);

if (month < 0 || month > 11) {
throw new IllegalArgumentException(
"Month " + month + " is not valid and must lie in between 0 and 11");
}

GregorianCalendar cldr = new GregorianCalendar(year, month, 1);
System.out.println("Sunday Monday Tuesday Wednesday Thursday Friday Saturday");

// Compute how much to leave before before the first day of the month.
// getDay() returns 0 for Sunday.

blankdays = cldr.get(Calendar.DAY_OF_WEEK)-1;
int daysInMonth = daysinmonths[month];

if (cldr.isLeapYear(cldr.get(Calendar.YEAR)) && month == 1) {

++daysInMonth;
}

// Blank out the labels before 1st day of the month
for (int i = 0; i < blankdays; i++) {
System.out.print("   ");
}

for (int i = 1; i <= daysInMonth; i++) {

// This "if" statement is simpler than messing with NumberFormat
if (i<=9) {
System.out.print(" ");
}
System.out.print(i);

if ((blankdays + i) % 7 == 0) { // Wrap if EOL
System.out.println();
}
else {
System.out.print(" ");
}
}
}

/**
     * Sole entry point to the class and application.
     * @param args Array of String arguments.
     */
    public static void main(String[] args) {

int mon, yr;
MonthCalender moncldr = new MonthCalender();

if (args.length == 2) {
moncldr.displayMonth(Integer.parseInt(args[0])-1, Integer.parseInt(args[1]));
}
else {
Calendar todaycldr = Calendar.getInstance();
moncldr.displayMonth(todaycldr.get(Calendar.MONTH), todaycldr.get(Calendar.YEAR));
}
}
}


Friday 3 June 2011

Linked list Example in java


import java.util.*;

public class LinkedListDemo{
public static void main(String[] args){
LinkedList link=new LinkedList();
link.add("a");
link.add("b");
link.add(new Integer(10));
System.out.println("The contents of array is" + link);
System.out.println("The size of an linkedlist is" + link.size());

link.addFirst(new Integer(20));
System.out.println("The contents of array is" + link);
System.out.println("The size of an linkedlist is" + link.size());

link.addLast("c");
System.out.println("The contents of array is" + link);
System.out.println("The size of an linkedlist is" + link.size());

link.add(2,"j");
System.out.println("The contents of array is" + link);
System.out.println("The size of an linkedlist is" + link.size());

link.add(1,"t");
System.out.println("The contents of array is" + link);
System.out.println("The size of an linkedlist is" + link.size());

link.remove(3);
System.out.println("The contents of array is" + link);
System.out.println("The size of an linkedlist is" + link.size());
}
}

copying a file to destination and showing details using java



import java.io.*;
import java.util.*;

public class CopyFile {

    public static void copy(String source, String destination)
            throws IOException {
        File source_file = new File(source);
        File desti_file = new File(destination);
        FileInputStream fis = null;
        FileOutputStream fos = null;
        byte[] buffer;
        int byte_read;

        try {

            /* first check that file exists or not. */
            if (!source_file.exists() || !source_file.isFile()) {
                throw new ClassException("No source file found : "+source);
            }

/* check that the file is readable or not. */
            if (!source_file.canRead()) {
                throw new ClassException("Source file is unreadable: "+source);
            }
           
            /* If the destination exists, make sure it is a writeable file and ask before
             overwriting it. If the destination doesn't exist, make sure the directory
             exists and is writeable.*/
            if (desti_file.exists()) {
                if (desti_file.isFile()) {
                    DataInputStream in = new DataInputStream(System.in);

                    if (!desti_file.canWrite()) {
                        throw new ClassException("Destination is unwriteable : "+destination);
                    }
                    System.out.print("File " + destination + " already exists. Overwrite?(Y/N): ");
                    System.out.flush();
                    String response = in.readLine();
                    if (!response.equals("Y") && !response.equals("y")) {
                        throw new ClassException("Wrong Input.");
                    }
                }
   else {
                   throw new ClassException("Destination is not a normal file: " + destination);
                }
            }
else {
                File parentdir = parent(desti_file);
                if (!parentdir.exists()) {
                    throw new ClassException("No Destination directory exist: " + destination);
                }
                if (!parentdir.canWrite()) {
                    throw new ClassException("Destination directory is unwriteable: "
                            + destination);
                }
            }

            /* Now we have checked all the things so we can copy the file now.*/
            fis = new FileInputStream(source_file);
            fos = new FileOutputStream(desti_file);
            buffer = new byte[1024];
            while (true) {
                byte_read = fis.read(buffer);
                if (byte_read == -1) {
                    break;
                }
                fos.write(buffer, 0, byte_read);
            }
        } /* Finally close the stream. */
finally {
                           
                fis.close();
fos.close();            
        }
System.out.print("Last modification date of destination file : ");
        System.out.println(new Date(desti_file.lastModified()));
    }

    /* File.getParent() can return null when the file is specified without a directory or
is in the root directory. This method handles those cases.*/
    private static File parent(File f) {
        String dirname = f.getParent();
        if (dirname == null) {
            if (f.isAbsolute()) {
                return new File(File.separator);
            }
else {
                return new File(System.getProperty("user.dir"));
            }
        }
        return new File(dirname);
    }

    public static void main(String[] args) {
        if (args.length != 2) {
            System.err.println("Wrong argument entered. Try Again......");
        }
else {
            try {
                copy(args[0], args[1]);
            }
catch (IOException ex) {
                System.err.println(ex.getMessage());
            }
        }
    }
}

class ClassException extends IOException {

    public ClassException(String msg) {
        super(msg);
    }
}




Uncompressing GZip file using java


import java.util.zip.GZIPInputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class JavaUncompress{
public static void main(String args[]){
try{
//To Uncompress GZip File Contents we need to open the gzip file.....
if(args.length<=0){
System.out.println("Please enter the valid file name");
}
else{
String inFilename = args[0];
System.out.println("Opening the gzip file.......................... :  opened");
GZIPInputStream gzipInputStream = null;
FileInputStream fileInputStream = null;
gzipInputStream = new GZIPInputStream(new FileInputStream(inFilename));
System.out.println("Opening the output file............. : opened");
String outFilename = inFilename +".pdf";
OutputStream out = new FileOutputStream(outFilename);
System.out.println("Trsansferring bytes from the compressed file to the output file........:  Transfer successful");
byte[] buf = new byte[1024];  //size can be changed according to programmer's need.
int len;
while ((len = gzipInputStream.read(buf)) > 0) {
out.write(buf, 0, len);
}
System.out.println("The file and stream is ......closing.......... : closed");
gzipInputStream.close();
out.close();
}
}
catch(IOException e){
System.out.println("Exception has been thrown" + e);
}
}
}


compressing a file in to GZIP


import java.io.*;
import java.util.zip.*;

public class CompressingFile {
public static void doCompressFile(String inFileName){
try{
File file = new File(inFileName);
System.out.println(" you are going to gzip the  : " + file + "file");
FileOutputStream fos = new FileOutputStream(file + ".gz");
System.out.println(" Now the name of this gzip file is  : " + file + ".gz" );
GZIPOutputStream gzos = new GZIPOutputStream(fos);
System.out.println(" opening the input stream");
FileInputStream fin = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(fin);
System.out.println("Transferring file from" + inFileName + " to " + file + ".gz");
byte[] buffer = new byte[1024];
int i;
while ((i = in.read(buffer)) >= 0){
gzos.write(buffer,0,i);
}
System.out.println(" file is in now gzip format");
in.close();
gzos.close();
}
catch(IOException e){
System.out.println("Exception is" + e);
}
}
public static void main(String args[]){
if(args.length!=1){
System.err.println("Please enter the file name which needs to be compressed ");
}
else{
doCompressFile(args[0]);
}
}
}


Constructor Overloading in java


public class ConstructorOverloading{
public static void main(String args[]){
Rectangle rectangle1=new Rectangle(2,4);
int areaInFirstConstructor=rectangle1.first();
System.out.println(" The area of a rectangle in first constructor is :  " + areaInFirstConstructor);
Rectangle rectangle2=new Rectangle(5);
int areaInSecondConstructor=rectangle2.second();
System.out.println(" The area of a rectangle in first constructor is :  " + areaInSecondConstructor);
Rectangle rectangle3=new Rectangle(2.0f);
float areaInThirdConstructor=rectangle3.third();
System.out.println(" The area of a rectangle in first constructor is :  " + areaInThirdConstructor);
Rectangle rectangle4=new Rectangle(3.0f,2.0f);
float areaInFourthConstructor=rectangle4.fourth();
System.out.println(" The area of a rectangle in first constructor is :  " + areaInFourthConstructor);
}
}

class Rectangle{
int l, b;
float p, q;
public Rectangle(int x, int y){
l = x;
b = y;
}
public int first(){
return(l * b);
}
public Rectangle(int x){
l = x;
b = x;
}
public int second(){
return(l * b);
}
public Rectangle(float x){
p = x;
q = x;
}
public float third(){
return(p * q);
}
public Rectangle(float x, float y){
p = x;
q = y;
}
public float fourth(){
return(p * q);
}
}


constructor in java


class another{
int x,y;
another(int a, int b){
x = a;
y = b;
}
another(){
}
int area(){
int ar = x*y;
return(ar);
}
}
public class Construct{
   public static void main(String[] args)
   {
  another b = new another();
  b.x = 2;
  b.y = 3;
  System.out.println("Area of rectangle : " + b.area());
  System.out.println("Value of y in another class : " + b.y);
  another a = new another(1,1);
  System.out.println("Area of rectangle : " + a.area());
  System.out.println("Value of x in another class : " + a.x);
   }
}

Output:
--------------
Area of rectangle: 6
Value of y in another class: 3
Area of rectangle: 1
Value of x in another class: 1

Thursday 2 June 2011

Switch Case example in java


import java.io.*;

public class SwitchExample{
public static void main(String[] args) throws Exception{
int x, y;
BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter two numbers for operation:");
try{
x = Integer.parseInt(object.readLine());
y = Integer.parseInt(object.readLine());
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("enter your choice:");
int a= Integer.parseInt(object.readLine());
switch (a){
case 1:
System.out.println("Enter the number one=" + (x+y));
break;
case 2:
System.out.println("Enter the number two=" + (x-y));
break;
case 3:
System.out.println("Enetr the number three="+ (x*y));
break;
case 4:
System.out.println("Enter the number four="+ (x/y));
break;
default:
System.out.println("Invalid Entry!:");
}
}
catch(NumberFormatException ne){
System.out.println(ne.getMessage() + " is not a numeric value.");
System.exit(0);
}

}
}