Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Thursday, December 29, 2011

Packaging In Java


Create a shapes package with classes Point, Circle, Rectangle, and Square. Of those classes, ensure that Point is the only class not accessible outside its package. Use implementation inheritance to derive Circle from Point and Rectangle from Square. Provide an Area interface with a double getArea() method that returns the area of a Circle, a Square, or a Rectangle. Once you finish creating the package, create a TestShapes program that imports class and interface names from shapes, creates objects from shape classes, and computes the area of the shape each object represents. After compiling and running TestShapes (successfully), move shapes to another location on your hard drive and change classpath so that a second attempt to run TestShapes results in the same output as the previous run.
Complete the following steps:
1.      Ensure no classpath environment variable exists.
2.      Create a shapes directory.
3.      Copy the following source code into an Area.java file that appears in shapes:
// Area.java
package shapes;
public interface Area
{
   double getArea ();
}

4.      Copy the following source code into a Circle.java file that appears in shapes:
// Circle.java
package shapes;
public class Circle extends Point implements Area
{
   private int radius;
   public Circle (int x, int y, int radius)
   {
      super (x, y);
      this.radius = radius;
   }
   // Why do I need to redeclare getX () and getY ()? Hint: Comment
   // out both methods and try to call them from TestShapes.
   public int getX () { return super.getX (); }
   public int getY () { return super.getY (); }
   public int getRadius () { return radius; }
   public double getArea () { return 3.14159 * radius * radius; }
}

5.      Copy the following source code into a Point.java file that appears in shapes:
// Point.java
package shapes;
class Point
{
   private int x, y;
   Point (int x, int y)
   {
      this.x = x;
      this.y = y;
   }
   int getX () { return x; }
   int getY () { return y; }
}

6.      Copy the following source code into a Rectangle.java file that appears in shapes:
// Rectangle.java
package shapes;
public class Rectangle extends Square
{
   private int length;
   public Rectangle (int width, int length)
   {
      super (width);
      this.length = length;
   }
   public int getLength () { return length; }
   public double getArea () { return getWidth () * length; }
}

7.      Copy the following source code into a Square.java file that appears in shapes:
// Square.java
package shapes;
public class Square implements Area
{
   private int width;
   public Square (int width)
   {
      this.width = width;
   }
   public int getWidth () { return width; }
   public double getArea () { return width * width; }
}

8.      Copy the following source code into a TestShapes.java file that appears in shapes's parent directory:
// TestShapes.java
import shapes.*;
class TestShapes
{
   public static void main (String [] args)
   {
      Area [] a = { new Circle (10, 10, 20),
                    new Square (5),
                    new Rectangle (10, 15) };
      for (int i = 0; i < a.length; i++)
           System.out.println (a [i].getArea ());
   }
}

9.      Assuming the directory that contains TestShapes.java is the current directory, execute javac TestShapes.java to compile TestShapes.java and all files in the shapes directory. Then execute java TestShapes to run this application.
10.  Move shapes to another directory and set classpath to refer to that directory and the current directory. For example, under Windows, move shapes \temp moves shapes into the temp directory. set classpath=\temp;. points classpath to the temp directory (just below the root directory) and current directory so java TestShapes still runs.

Wednesday, July 20, 2011

Creating a Shared File Lock on a File

package org.best.example;

public static void main(String[] args)
    {
         try {
         // Obtain a file channel
         File file = new File("filename");
         FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
       
         // Create a shared lock on the file.
         // This method blocks until it can retrieve the lock.
         FileLock lock = channel.lock(0, Long.MAX_VALUE, true);
       
         // Try acquiring a shared lock without blocking. This method returns
         // null or throws an exception if the file is already exclusively locked.
             try {
             lock = channel.tryLock(0, Long.MAX_VALUE, true);
             } catch (OverlappingFileLockException e) {
             // File is already locked in this thread or virtual machine
         }
       
         // Determine the type of the lock
         boolean isShared = lock.isShared();
       
         // Release the lock
         lock.release();
       
         // Close the file
         channel.close();
         } catch (Exception e) {
     }
}

Tuesday, July 19, 2011

Creating a File Lock on a File

package org.best.examples;

public static void main(String[] args)
     {
         try {
         // Get a file channel for the file
         File file = new File("Test.java");
         FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
       
         // Use the file channel to create a lock on the file.
         // This method blocks until it can retrieve the lock.
         FileLock lock = channel.lock();
       
         // Try acquiring the lock without blocking. This method returns
         // null or throws an exception if the file is already locked.
             try {
             lock = channel.tryLock();
             } catch (OverlappingFileLockException e) {
             // File is already locked in this thread or virtual machine
         }
       
         // Release the lock
         lock.release();
       
         // Close the file
         channel.close();
         } catch (Exception e) {
     }
}

Sunday, July 10, 2011

How to Write Image with ImageWriter

package org.best.examples;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

public class Main {
  static public void main(String args[]) throws Exception {
    int width = 200, height = 200;
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    Graphics2D ig2 = bi.createGraphics();
    ig2.fillRect(0, 0, width - 1, height - 1);

    Iterator imageWriters = ImageIO.getImageWritersByFormatName("GIF");
    ImageWriter imageWriter = (ImageWriter) imageWriters.next();
    File file = new File("filename.gif");
    ImageOutputStream ios = ImageIO.createImageOutputStream(file);
    imageWriter.setOutput(ios);
    imageWriter.write(bi);
  }
}

Saturday, July 9, 2011

How to build up an image from individual pixels

package org.best.examples;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class RasterImageTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(new Runnable()
         {
            public void run()
            {
               JFrame frame = new RasterImageFrame();
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               frame.setVisible(true);
            }
         });
   }
}

/**
 * This frame shows an image with a Mandelbrot set.
 */
class RasterImageFrame extends JFrame
{
   public RasterImageFrame()
   {
      setTitle("RasterImageTest");
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
      BufferedImage image = makeMandelbrot(DEFAULT_WIDTH, DEFAULT_HEIGHT);
      add(new JLabel(new ImageIcon(image)));
   }


   public BufferedImage makeMandelbrot(int width, int height)
   {
      BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
      WritableRaster raster = image.getRaster();
      ColorModel model = image.getColorModel();

      Color fractalColor = Color.red;
      int argb = fractalColor.getRGB();
      Object colorData = model.getDataElements(argb, null);

      for (int i = 0; i < width; i++)
         for (int j = 0; j < height; j++)
         {
            double a = XMIN + i * (XMAX - XMIN) / width;
            double b = YMIN + j * (YMAX - YMIN) / height;
            if (!escapesToInfinity(a, b)) raster.setDataElements(i, j, colorData);
         }
      return image;
   }

   private boolean escapesToInfinity(double a, double b)
   {
      double x = 0.0;
      double y = 0.0;
      int iterations = 0;
      while (x <= 2 && y <= 2 && iterations < MAX_ITERATIONS)
      {
         double xnew = x * x - y * y + a;
         double ynew = 2 * x * y + b;
         x = xnew;
         y = ynew;
         iterations++;
      }     
      return x > 2 || y > 2;
   }

   private static final double XMIN = -2;
   private static final double XMAX = 2;
   private static final double YMIN = -2;
   private static final double YMAX = 2;
   private static final int MAX_ITERATIONS = 16;
   private static final int DEFAULT_WIDTH = 400;
   private static final int DEFAULT_HEIGHT = 400;
}

Friday, July 8, 2011

How to Implement Heap Sort

package org.best.examples;
 
class HeapSort
{
public static void main(String arg[]){
 int a[]={3,30,4,12,1,2,34,22,4,3,5,8};
 System.out.println("\n\nInput values:");
 for(int i=0;i<a.length;i++){
  System.out.print(" "+a[i]);
  }
 int N = a.length;
 for (int k = N/2; k > 0; k--) {
     downheap(a, k, N);     
        }
 do {
            int T = a[0];
            a[0] = a[N - 1];
            a[N - 1] = T;
     N = N - 1;
    downheap(a, 1, N);
 } while (N > 1);
    System.out.println("\n\n\nSorted values:");
 for(int i=0;i<a.length;i++)
  {
 System.out.print(" "+a[i]);
     }
}
 static void downheap(int a[], int k, int N) {
 int T = a[k - 1];
 while (k <= N/2) {
            int j = k + k;
            if ((j < N) && (a[j - 1] < a[j])) {
         j++;
     }
     if (T >= a[j - 1]) {
  break;
     } else {
                a[k - 1] = a[j - 1];
                k = j;
            }
 }
        a[k - 1] = T;
 
    }
}

Wednesday, July 6, 2011

How to implement Stop Watch

package org.best.examples;

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

public class Stopwatch extends JFrame implements ActionListener, Runnable
    {
     private long startTime;
     private final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("mm : ss.SSS");
     private final JButton startStopButton= new JButton("Start/stop");
     private Thread updater;
     private boolean isRunning= false;
     private final Runnable displayUpdater= new Runnable()
         {
         public void run()
             {
             displayElapsedTime(System.currentTimeMillis() - Stopwatch.this.startTime);
         }
     };
     public void actionPerformed(ActionEvent ae)
         {
         if(isRunning)
             {
             long elapsed= System.currentTimeMillis() - startTime;
             isRunning= false;
             try
                 {
                 updater.join();
                 // Wait for updater to finish
             }
             catch(InterruptedException ie) {}
             displayElapsedTime(elapsed);
             // Display the end-result
         }
         else
             {
             startTime= System.currentTimeMillis();
             isRunning= true;
             updater= new Thread(this);
             updater.start();
         }
     }
     private void displayElapsedTime(long elapsedTime)
         {
         startStopButton.setText(timerFormat.format(new java.util.Date(elapsedTime)));
     }
     public void run()
         {
         try
             {
             while(isRunning)
                 {
                 SwingUtilities.invokeAndWait(displayUpdater);
                 Thread.sleep(50);
             }
         }
         catch(java.lang.reflect.InvocationTargetException ite)
             {
             ite.printStackTrace(System.err);
             // Should never happen!
         }
         catch(InterruptedException ie) {}
         // Ignore and return!
     }
     public Stopwatch()
         {
         startStopButton.addActionListener(this);
         getContentPane().add(startStopButton);
         setSize(100,50);
         setVisible(true);
     }
     public static void main(String[] arg)
         {
         new Stopwatch().addWindowListener(new WindowAdapter()
             {
             public void windowClosing(WindowEvent e)
                 {
                 System.exit(0);
             }
         });
     }
}

Tuesday, July 5, 2011

How to Change Look and Feel of a GUI

package org.best.example;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;

public class ChangeLookAndFeel extends JFrame implements ActionListener {
  static String metalClassName = "javax.swing.plaf.metal.MetalLookAndFeel";
  static String motifClassName = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
  static String windowsClassName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";

  public static void main( String[] argv ) {
    ChangeLookAndFeel myExample = new ChangeLookAndFeel( "Change Look And Feel" );
  }

  public ChangeLookAndFeel( String title ) {
    super( title );
    setSize( 150, 150 );
    addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent we ) {
        dispose();
        System.exit( 0 );
      }
    } );
    JPanel my_panel = new JPanel();
    my_panel.setLayout( new GridLayout( 1, 3 ) );
    JButton jb = new JButton( "Metal" );
    my_panel.add( jb );
    jb.addActionListener( this );
    jb = new JButton( "Motif" );
    my_panel.add( jb );
    jb.addActionListener( this );
    jb = new JButton( "Windows" );
    my_panel.add( jb );
    jb.addActionListener( this );
    getContentPane().add( my_panel );
    my_panel.setBorder( BorderFactory.createEtchedBorder() );
    pack();
    setVisible( true );
  }

  public void changeLookTo( String cName ) {
    try {
      UIManager.setLookAndFeel( cName );
    }
    catch( Exception e ) {
      System.out.println( "Could not change l&f" );
    }
    SwingUtilities.updateComponentTreeUI( this );
    this.pack();
  }

  public void actionPerformed( ActionEvent ae ) {
    String title = ae.getActionCommand();
    if( title.equals( "Metal" ) )
      changeLookTo( metalClassName );
    else if( title.equals( "Motif" ) )
      changeLookTo( motifClassName );
    else if( title.equals( "Windows" ) ) changeLookTo( windowsClassName );

  }
}

Monday, July 4, 2011

How to Construct Hanoi Tower

package org.best.examples;

public class HanoiAlgorithmRecursion {
  public static void movetower( int height, int fromT, int toT, int usingT ) {
    if( height > 0 ) {
      movetower( height - 1, fromT, usingT, toT );
      moveDisk( fromT, toT );
      movetower( height - 1, usingT, toT, fromT );
    }
  }

  public static void moveDisk( int takeoff, int puton ) {
    System.out.println( takeoff + "->" + puton );
  }

  public static void main( String argv[] ) {
    int numberOfDisks = 3;
    movetower( numberOfDisks, 1, 3, 2 );
  }
}

Sunday, July 3, 2011

How to Make Java Doc from Programs

package org.best.examples;

public class JavaDocComments {

  /**
   * The execute method does blah blah
   *
   * @param min the min variable is this
   * @param max the max variable is that
   * @return String the process name
   * @throws java.lang.NullPointerException reports any problems trying to execute process
   */
  public String execute( int min, String max ) throws NullPointerException {
    return null;
  }

  /**
   * outputs something like this for the execute method

   execute

   public String execute(int min, String max)

   The execute method does blah blah

   Parameters:
   min - the min variable is this
   max - the max variable is that

   Returns:
   String the process name

   Throws:
   NullPointerException - reports any problems trying to execute process
   */
}

Friday, July 1, 2011

How to Log an Exception

package org.best.example;

public void myMethod() {
     Logger logger = Logger.getLogger("com.mycompany.MyClass");
   
     // This method should be used when an exception is encounted
         try {
         // Test with an exception
         throw new IOException();
         } catch (Throwable e){
         // Log the exception
         logger.log(Level.SEVERE, "Uncaught exception", e);
     }
   
     // When a method is throwing an exception, this method should be used
     Exception ex = new IllegalStateException();
     logger.throwing(this.getClass().getName(), "myMethod", ex);
}

Wednesday, June 29, 2011

How to List All Available Unicode to Character Set Converters

package org.best.example;


public static void main(String args[])
    {
     Map map = Charset.availableCharsets();
     Iterator it = map.keySet().iterator();
         while (it.hasNext()) {
         // Get charset name
         String charsetName = (String)it.next();
         System.out.println("Charset Name "+charsetName);
       
         // Get charset
         Charset charset = Charset.forName(charsetName);
         System.out.println("Charset "+charset);
     }
}




Tuesday, June 28, 2011

How to Locate Time Server

package org.best.example;

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;
import java.util.regex.*;


public class TimeServer {

    // We can't use the normal daytime port (unless we're running as root,
    // which is unlikely), so we use this one instead
    private static int PORT = 8013;

    // The port we'll actually use
    private static int port = PORT;

    // Charset and encoder for US-ASCII
    private static Charset charset = Charset.forName("US-ASCII");
    private static CharsetEncoder encoder = charset.newEncoder();

    // Direct byte buffer for writing
    private static ByteBuffer dbuf = ByteBuffer.allocateDirect(1024);


    // Open and bind the server-socket channel
    //
    private static ServerSocketChannel setup() throws IOException {
    ServerSocketChannel ssc = ServerSocketChannel.open();
    InetSocketAddress isa
        = new InetSocketAddress(InetAddress.getLocalHost(), port);
    ssc.socket().bind(isa);
    return ssc;
    }

    // Service the next request to come in on the given channel
    //
    private static void serve(ServerSocketChannel ssc) throws IOException {
    SocketChannel sc = ssc.accept();
    try {
        String now = new Date().toString();
        sc.write(encoder.encode(CharBuffer.wrap(now + "
")));
        System.out.println(sc.socket().getInetAddress() + " : " + now);
        sc.close();
    } finally {
        // Make sure we close the channel (and hence the socket)
        sc.close();
    }
    }

    public static void main(String[] args) throws IOException {
    if (args.length > 1) {
        System.err.println("Usage: java TimeServer [port]");
        return;
    }

    // If the first argument is a string of digits then we take that
    // to be the port number
    if ((args.length == 1) && Pattern.matches("[0-9]+", args[0]))
        port = Integer.parseInt(args[0]);

    ServerSocketChannel ssc = setup();
    for (;;)
        serve(ssc);

    }

}