128
10 PAINT 25.8.2010 AIM: To develop a simple paint like program that can draw basic graphical primitives in different dimensions and colors ALGORITHM: Step 1 : Import all packages Step 2 : Declare all necessary variables Step 3: Create drawing class that calls frame class Step4 : Create frame and include all icons of line ,oval,rectangle etc Step 5: Draw all ahapes using tools created Step 6: Close the application

Java

Embed Size (px)

Citation preview

Page 1: Java

10 PAINT 25.8.2010

AIM: To develop a simple paint like program that can draw basic graphical primitives in different dimensions and colors

ALGORITHM: Step 1 : Import all packages Step 2 : Declare all necessary variables Step 3: Create drawing class that calls frame class Step4 : Create frame and include all icons of line ,oval,rectangle etc Step 5: Draw all ahapes using tools created Step 6: Close the application

Page 2: Java

PROGRAM://Shape.javaimport java.awt.Graphics2D;import java.awt.Color;import java.awt.Paint;import java.awt.Stroke;

public abstract class Shape{ private int x1; private int y1; private Paint paint; private Stroke stroke; // Class constructor with no argument public Shape () { x1 = 0; y1 = 0; paint = Color.BLACK; } // Class constructor with three argument public Shape( int x1Value , int y1Value , Paint paintValue , Stroke strokeValue ) { x1 = x1Value; y1 = y1Value; paint = paintValue; stroke = strokeValue; } // Each class that inherites this class must implement this method // because this method is an abstract method public abstract void draw( Graphics2D g2d ); public int getx1() { return x1; } public void setx1( int x1Value) { x1 = ( x1Value > 0 ? x1Value : 0 ); } public int gety1()

Page 3: Java

{ return y1; } public void sety1( int y1Value ) { y1 = ( y1Value > 0 ? y1Value : 0 ); } public Paint getPaint() { return paint; } public void setPaint( Paint paintValue ) { paint = paintValue; } public void setStroke( Stroke strokeValue ) { stroke = strokeValue; } public Stroke getStroke() { return stroke; } } // end class Shape

//Drawing.javaimport javax.swing.JFrame;

public class Drawing{ public static void main (String[] args) { DrawFrame frame = new DrawFrame(); frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ); frame.setSize ( 600 , 600 ); frame.setVisible ( true ); }

Page 4: Java

} // end class Drawing

//DrawPanel.javaimport javax.swing.JPanel;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Color;import java.awt.Paint;import java.awt.GradientPaint;import java.awt.BasicStroke;import java.awt.Stroke;import java.awt.event.MouseAdapter;import java.awt.event.MouseMotionListener;import java.awt.event.MouseEvent;

public class DrawPanel extends JPanel{ private Shape shapes[]; // Holds the shapes that the user has drawn private Shape currentShape; // Holds the current shape the user is drawing private Color color1; // If user uses Gradient , it holds the first color private Color color2; // If user uses Gradient , it holds the second color private Paint currentPaint; // Holds the current paint Pattern private Stroke currentStroke; // Holds the current stroke pattern private int lineWidth; // Holds the line width as a parameter for currentStroke private int dashLength; // Holds the dash lenght as a parameter for currentStroke private int shapeCount; // Holds the number of shapes the user has drawn private int shapeType; // Holds the current shapeType ( Line , Retangle or oval ) private int x1 , y1 , x2 , y2; // Holds necessary points private boolean filledShape; // Holds whether to draw a fill or not private boolean useGradient; // Holds whether to use gradient or not private boolean dashed; // Holds whether to draw dashed lines or not private final int LINE = 0, // Constants for identifying how to draw different shapes RECT = 1, OVAL = 2; // Class constructor public DrawPanel() { shapes = new Shape[ 100 ]; currentShape = null; color1 = Color.BLACK; color2 = Color.BLACK;

Page 5: Java

currentPaint = Color.BLACK; currentStroke = null; lineWidth = 1; dashLength = 1; shapeCount = 0; shapeType = 0; x1 = 0; y1 = 0; x2 = 0; y2 = 0; filledShape = false; useGradient = false; dashed = false; // Set the DrawPanel's background color this.setBackground ( Color.WHITE ); // Register event listeners for DrawPanel this.addMouseMotionListener ( new mouseHandler() ); this.addMouseListener ( new mouseHandler() ); } // end constructor public void paintComponent( Graphics g ) {

super.paintComponent ( g ); // Cast Graphics object "g" to Graphics2D Graphics2D g2d = ( Graphics2D ) g; int i = 0; // Draw preceding shapes that the user has drawn while ( i < shapeCount ) { shapes[ i ].draw ( g2d ); i++; } // Draw the current shape that user has just drawn if ( currentShape != null ) currentShape.draw ( g2d ); } // end method paintComponent

Page 6: Java

public void setShapeType( int shapeTypeValue ) { shapeType = shapeTypeValue; } public void setCurrentPaint( Paint paintValue ) { currentPaint = paintValue; } public void setStroke( Stroke strokeValue ) { currentStroke = strokeValue; } public void setFilledShape( boolean fillValue) { filledShape = fillValue; } public void setUseGradient( boolean useGradientValue ) { useGradient = useGradientValue; } public void setColor1( Color color1Value ) { color1 = color1Value; } public void setColor2( Color color2Value ) { color2 = color2Value; } public void setDashed( boolean dashValue ) { dashed = dashValue; } public void setLineWidth( int lineWidthValue ) { lineWidth = lineWidthValue; } public void setDashLength( int dashLenghtValue )

Page 7: Java

{ dashLength = dashLenghtValue; } public void clearLastShape() { if ( shapeCount > 0 ){ shapeCount--; currentShape=null; // Invoke method repaint to refresh the DrawPanel this.repaint (); } } public void clearDrawing() { shapeCount = 0; currentShape = null; // Invoke method repaint to refresh the DrawPanel this.repaint (); } // Inner class for handling mouse events private class mouseHandler extends MouseAdapter implements MouseMotionListener { public void mousePressed( MouseEvent event ) { // set the shape's first point if ( event.isAltDown () == false && event.isMetaDown () == false){ x1 = event.getX (); y1 = event.getY (); } } public void mouseReleased( MouseEvent event ) { // Put the drew shape into the array "shapes" if ( event.isAltDown () == false && event.isMetaDown () == false) { shapes [ shapeCount ] = currentShape; shapeCount++; } }

Page 8: Java

public void mouseDragged( MouseEvent event ) { if ( event.isAltDown () == false && event.isMetaDown () == false) { // Set the shape's second point x2 = event.getX (); y2 = event.getY ();

// Check whether user wants to use gradient if ( useGradient == true ) currentPaint = new GradientPaint( 0 , 0 , color1 , 50 , 50 , color2 , true ); else currentPaint = color1; // Check whether user wants to draw dashed lines if ( dashed == true ) { float dashLenghtArray[]={ dashLength }; currentStroke = new BasicStroke( lineWidth , BasicStroke.CAP_ROUND , BasicStroke.JOIN_ROUND , 10 , dashLenghtArray , 0 ); } else currentStroke = new BasicStroke( lineWidth ); // Create the appropriate shape according to the user selection switch ( shapeType ) { case LINE: currentShape = new Line( x1 , y1 , x2 , y2 , currentPaint , currentStroke); break; case RECT: currentShape = new Rectangle( x1 , y1 , x2 , y2 , currentPaint , currentStroke , filledShape ); break; case OVAL: currentShape = new Oval( x1 , y1 , x2 , y2 , currentPaint , currentStroke , filledShape ); break; } DrawPanel.this.repaint (); } // end if } // end method mouseDragged

Page 9: Java

} // end class MouseHandler } // end class DrawPanel

//Line.javaimport java.awt.Graphics2D;import java.awt.Stroke;import java.awt.Paint;

public class Line extends Shape{

private int x2; private int y2; // Class constructor with no argument public Line () { super(); x2 = 0; y2 = 0; } // Class constructor with five argument public Line( int x1Value , int y1Value , int x2Value , int y2Value , Paint paintValue , Stroke strokeValue ) { super ( x1Value , y1Value , paintValue , strokeValue ); x2= x2Value; y2 = y2Value; } // Override abstract method "draw" inherited from class "Shape" to draw a line public void draw( Graphics2D g2d ) { g2d.setPaint ( super.getPaint () ); g2d.setStroke ( super.getStroke () ); g2d.drawLine ( super.getx1 () , super.gety1 () , x2 , y2 ); } } // end class Line

Page 10: Java

//Oval.javaimport java.awt.Graphics2D;import java.awt.Color;import java.awt.Stroke;import java.awt.Paint;

public class Oval extends Shape{

private int width; private int height; private boolean fill; // Class constructor with no argument public Oval () { super(); width = 1; height = 1; fill = false; } // Class constructor with six argument public Oval( int x1Value , int y1Value , int x2Value , int y2Value , Paint paintValue , Stroke strokeValue , boolean fillValue ) { super( x1Value < x2Value ? x1Value : x2Value , y1Value < y2Value ? y1Value : y2Value , paintValue , strokeValue ); width = Math.abs ( x1Value - x2Value ); height = Math.abs ( y1Value - y2Value ); fill = fillValue; } // Override abstract method "draw" inherited from class "Shape" to draw an oval public void draw ( Graphics2D g2d ) { g2d.setPaint ( super.getPaint () ); g2d.setStroke ( super.getStroke () ); if ( fill == true ) g2d.fillOval ( super.getx1 () , super.gety1 () , width , height ); else g2d.drawOval ( super.getx1 () , super.gety1 () , width , height ); } } // end class Oval

Page 11: Java

//DrawFrame.javaimport javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JButton;import javax.swing.JLabel;import javax.swing.JTextField;import javax.swing.JComboBox;import javax.swing.JCheckBox;import javax.swing.JColorChooser;import javax.swing.JOptionPane;import java.awt.Color;import java.awt.FlowLayout;import java.awt.BorderLayout;import java.awt.GridLayout;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import java.awt.event.ItemListener;import java.awt.event.ItemEvent;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;

public class DrawFrame extends JFrame{ private DrawPanel drawPanel; private JPanel panel1; private JPanel panel2; private JPanel panel3; private JButton undoButton; private JButton clearButton; private JButton firstColorButton; private JButton secondColorButton; private JComboBox shapeComboBox; private JCheckBox fillCheckBox; private JCheckBox gradientCheckBox; private JCheckBox dashCheckBox; private JLabel shapesLabel; private JLabel widthLabel; private JLabel lengthLabel; private JTextField widthTextField; private JTextField dashLengthTextField; private final String shapeNames[] = { "Line" , "Rectangle" ,"Oval" };

Page 12: Java

// Class constructor public DrawFrame () { // Set the title of JFrame setTitle ( "Drawing Application" ); // Create a JPanel as a container for GUI components in first row panel1 = new JPanel(); // Set the layout of panel1 panel1.setLayout ( new FlowLayout( FlowLayout.CENTER ) ); // Create a JPanel as a container for GUI components in second row panel2 = new JPanel();

// Set the layout of panel2 panel2.setLayout ( new FlowLayout( FlowLayout.CENTER ) ); // Create a JPanel to hold panel1 , panel2 and panel3 panel3 = new JPanel();

// Set the layout of panel4 panel3.setLayout ( new GridLayout( 2,1,0,0) ); // Create button "Undo" and add it to the panel undoButton = new JButton(); undoButton.setText( "Undo" ); undoButton.addActionListener ( // Create and register an ActionListener new ActionListener() { public void actionPerformed( ActionEvent event ) { drawPanel.clearLastShape (); } } ); panel1.add ( undoButton ); // Create button "Clear" and add it to panel1 clearButton = new JButton(); clearButton.setText( "Clear" ); clearButton.addActionListener ( // Create and register an ActionListener

Page 13: Java

new ActionListener() { public void actionPerformed( ActionEvent event ) { drawPanel.clearDrawing (); } } ); panel1.add ( clearButton );

// Create label "shapesLabel" and add it to panel1 shapesLabel = new JLabel(); shapesLabel.setText ( "Shapes:" ); panel1.add ( shapesLabel ); // Create a combobox that contains shape names and add it to panel1 shapeComboBox = new JComboBox( shapeNames); shapeComboBox.setMaximumRowCount ( 3 ); shapeComboBox.addItemListener ( // Create and register an ItemLsitener new ItemListener() { public void itemStateChanged( ItemEvent event ) { if ( event.getStateChange () == ItemEvent.SELECTED ) drawPanel.setShapeType ( shapeComboBox.getSelectedIndex () ); } } ); panel1.add ( shapeComboBox ); // Create checkbox "fillCheckBox" and add it to panel1 fillCheckBox = new JCheckBox(); fillCheckBox.setText ( "Filled" ); fillCheckBox.addItemListener ( // Create and register an ItemListener new ItemListener() { public void itemStateChanged( ItemEvent event ) { drawPanel.setFilledShape ( fillCheckBox.isSelected () ); } } );

Page 14: Java

panel1.add ( fillCheckBox );

// Create checkbox "gradientCheckBox" and add it to panel2 gradientCheckBox = new JCheckBox(); gradientCheckBox.setText ( "Use Gradient" ); gradientCheckBox.addItemListener ( // Create and register an ItemListener new ItemListener() { public void itemStateChanged( ItemEvent event ) { drawPanel.setUseGradient ( gradientCheckBox.isSelected () ); } } ); panel2.add ( gradientCheckBox );

// Create button "firstColor" and add it to panel2 firstColorButton = new JButton(); firstColorButton.setText ( "1st Color..." ); firstColorButton.addActionListener ( // Create and register an ActionListener new ActionListener() { public void actionPerformed( ActionEvent event ) { Color color = Color.BLACK; color = JColorChooser.showDialog ( null , "Color Chooser" , color ); if ( color == null) color = color.BLACK; drawPanel.setColor1 ( color ); } } ); panel2.add ( firstColorButton ); // Create button "secondColor" and add it to panel2 secondColorButton = new JButton(); secondColorButton.setText ( "2nd Color..." ); secondColorButton.addActionListener ( // Create and register an ActionListener new ActionListener() {

Page 15: Java

public void actionPerformed( ActionEvent event ) { Color color = Color.BLACK; color = JColorChooser.showDialog ( null , "Color Chooser" , color ); if ( color == null) color = color.BLACK; drawPanel.setColor2 ( color ); } } ); panel2.add ( secondColorButton ); // Create label "widthLabel" and set its properties widthLabel = new JLabel(); widthLabel.setText ( "Line width:" ); panel2.add ( widthLabel ); // Create text field "widthTextField" and set its properties widthTextField = new JTextField(); widthTextField.addKeyListener( // Create and register an KeyListener new KeyAdapter() { public void keyReleased( KeyEvent e) { int lineWidth;

try { lineWidth = Integer.parseInt ( widthTextField.getText () );

if ( lineWidth < 1 || lineWidth > 20 ) throw new NumberFormatException(); drawPanel.setLineWidth ( lineWidth ); } catch ( NumberFormatException exception ) { JOptionPane.showMessageDialog( null , "Please enter an integer between 1 to 20" , "Error" , JOptionPane.INFORMATION_MESSAGE ); widthTextField.setText( "" ); } }

Page 16: Java

} ); widthTextField.setColumns ( 2 ); panel2.add ( widthTextField ); // create label "lenghtLabel" and set its properties lengthLabel = new JLabel(); lengthLabel.setText ( "Dash length:" ); panel2.add ( lengthLabel ); // Create text field "dashLenghtTextField" and set its properties dashLengthTextField = new JTextField(); dashLengthTextField.setColumns ( 2 ); dashLengthTextField.addKeyListener( // Create and register an KeyListener new KeyAdapter() { public void keyReleased( KeyEvent e) { int dashLength;

try { dashLength = Integer.parseInt ( dashLengthTextField.getText () );

if ( dashLength < 1 || dashLength > 50 ) throw new NumberFormatException();

drawPanel.setDashLength ( dashLength ); } catch ( NumberFormatException exception ) { JOptionPane.showMessageDialog( null , "Please enter an integer between 1 to 50" , "Error" , JOptionPane.INFORMATION_MESSAGE ); dashLengthTextField.setText( "" ); } } } ); panel2.add ( dashLengthTextField ); // Create check box "dashCheckBox" and set its properties dashCheckBox = new JCheckBox(); dashCheckBox.setText ( "Dashed" ); dashCheckBox.addItemListener ( // Create and register an ItemLitener

Page 17: Java

new ItemListener() { public void itemStateChanged( ItemEvent event ) { drawPanel.setDashed ( dashCheckBox.isSelected () ); } } ); panel2.add ( dashCheckBox ); // Add panel1 to panel3 panel3.add ( panel1 ); // add panel2 to panel3 panel3.add ( panel2 ); // Add panel3 to the south region of JFrame this.add ( panel3 , BorderLayout.NORTH ); // Create an object of type DrawPanel drawPanel = new DrawPanel(); // Add "DrawPanel" object to JFrame this.add ( drawPanel ); } // end constructor } // end class DrawFrame

//Rectangle.javaimport java.awt.Graphics2D;import java.awt.Color;import java.awt.Stroke;import java.awt.Paint;

public class Rectangle extends Shape{

private int width; private int height; private boolean fill; // Class constructor with no argument

Page 18: Java

public Rectangle () { super(); width = 1; height = 1; fill = false; } // Class constructor with six argument public Rectangle( int x1Value , int y1Value , int x2Value , int y2Value , Paint paintValue , Stroke strokeValue , boolean fillValue ) { super( x1Value < x2Value ? x1Value : x2Value , y1Value < y2Value ? y1Value : y2Value , paintValue , strokeValue ); width = Math.abs ( x1Value - x2Value ); height = Math.abs ( y1Value - y2Value ); fill = fillValue; } // Override abstract method "draw" inherited from class "Shape" to draw a rectangle public void draw ( Graphics2D g2d ) { g2d.setPaint ( super.getPaint () ); g2d.setStroke ( super.getStroke () ); if ( fill == true ) g2d.fillRect ( super.getx1 () , super.gety1 () , width , height ); else g2d.drawRect ( super.getx1 () , super.gety1 () , width , height ); } } // end class Rectangle

Page 19: Java

OUTPUT:

RESULT: Thus the program is written to implement simple paint like program.

Page 20: Java

11 SCIENTIFIC CALCULATOR 2.9.2010

AIM: To write a program to implement scientific calculator using even-driven programming.

ALGORITHM:Step 1: Start the program.Step 2: Import the required packages.Step 3: Create class that extends frame.Step 4: Create text field and buttons.Step 5: Add buttons to panel.Step 6: Add mouse listener and perform necessary operation.Step 7: Exit the application.

Page 21: Java

PROGRAM://Scientific Calculatorimport java.awt.BorderLayout;import java.awt.Color;import java.awt.Container;import java.awt.Cursor;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.GridLayout;import java.awt.Insets;import java.awt.Toolkit;

import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;

import java.io.IOException;

import javax.swing.ButtonGroup;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JRadioButton;import javax.swing.JTextField;import javax.swing.UIManager;import javax.swing.WindowConstants;import javax.swing.border.EmptyBorder;

public class Calc extends JFrame implements ActionListener,MouseListener //,KeyListener{ private JButton jb_one,jb_two,jb_three,jb_four,jb_five,jb_six,jb_seven,jb_eight,jb_nine,jb_zero; private JButton jb_plus,jb_minus,jb_divide,jb_multiply; private JButton jb_sin,jb_cos,jb_tan,jb_asin,jb_acos,jb_atan,jb_pie,jb_E; private JButton jb_decimalpoint,jb_equalto,jb_fact,jb_power,jb_changesign,jb_reciporcal; private JButton jb_todeg,jb_torad,jb_round,jb_CA,jb_CE,jb_Backspace; private JRadioButton jrb_deg,jrb_rad; private ButtonGroup jrb_group; private JTextField jtf_display;

Page 22: Java

private double tempdisplayNum; boolean plusPressed,minusPressed,mulPressed,divPressed,equalPressed,powerPressed;

/** * This constructor forms GUI and add required Compontents * to listeners. */ public Calc() {

super("Scientic Calculator ( Currently running on JVM Version " + System.getProperty("java.version") + " )");

setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Calc.this.dispose(); System.runFinalization(); System.gc(); System.exit(0); } });

tempdisplayNum = 0; resetAllButton(); equalPressed = false;

/* * GUI Formation */ JPanel jp_main = new JPanel(); jp_main.setLayout(new BorderLayout()); jp_main.setBorder(new EmptyBorder(new Insets(3,5,5,5))); JPanel jp_top = new JPanel(); jp_top.setLayout(new BorderLayout()); JPanel jp_top_down = new JPanel(); jp_top_down.setLayout(new BorderLayout()); JPanel jp_top_west = new JPanel(); jb_Backspace = new JButton("BackSpace");

Page 23: Java

jp_top_west.setLayout(new FlowLayout(FlowLayout.LEFT,0,5)); jp_top_west.add(jb_Backspace); JPanel jp_top_east = new JPanel(); jp_top_east.setLayout(new FlowLayout(FlowLayout.RIGHT)); jtf_display = new JTextField(); jtf_display.setEditable(false); jtf_display.setHorizontalAlignment( JTextField.RIGHT ); jtf_display.setRequestFocusEnabled(false); jtf_display.setBackground(Color.white); jrb_deg = new JRadioButton("Degrees"); jrb_rad = new JRadioButton("Radian"); jrb_deg.setSelected(true); jrb_group = new ButtonGroup(); jrb_group.add(jrb_deg); jrb_group.add(jrb_rad); jp_top_east.add(jrb_deg); jp_top_east.add(jrb_rad); jp_top_down.add(jp_top_east,BorderLayout.EAST); jp_top_down.add(jp_top_west,BorderLayout.WEST); jp_top.setLayout(new BorderLayout());

jp_top.add(jtf_display,BorderLayout.CENTER); jp_top.add(jp_top_down,BorderLayout.SOUTH); JPanel jp_center = new JPanel(); jp_center.setLayout(new GridLayout(5,7,5,5)); jb_one = new JButton("1"); jb_two = new JButton("2"); jb_three = new JButton("3"); jb_four = new JButton("4"); jb_five = new JButton("5"); jb_six = new JButton("6"); jb_seven = new JButton("7"); jb_eight = new JButton("8"); jb_nine = new JButton("9"); jb_zero = new JButton("0"); jb_plus = new JButton("+"); jb_minus = new JButton("-"); jb_divide = new JButton("/"); jb_multiply = new JButton("*"); jb_sin = new JButton("Sin"); jb_cos = new JButton("Cos"); jb_tan = new JButton("Tan"); jb_asin = new JButton("aSin"); jb_acos = new JButton("aCos");

Page 24: Java

jb_atan = new JButton("aTan"); jb_pie = new JButton("PI"); jb_E = new JButton("E"); jb_decimalpoint = new JButton("."); jb_equalto = new JButton("="); jb_fact = new JButton("x!"); jb_power = new JButton("x^n"); jb_changesign = new JButton("+/-"); jb_reciporcal = new JButton("1/x"); jb_todeg = new JButton("toDeg"); jb_torad = new JButton("toRad"); jb_round = new JButton("Round"); jb_CA = new JButton("CA"); jb_CE = new JButton("CE");

/** * Adding Button to Listeners */ jb_one.addActionListener(Calc.this); jb_two.addActionListener(Calc.this); jb_three.addActionListener(Calc.this); jb_four.addActionListener(Calc.this); jb_five.addActionListener(Calc.this); jb_six.addActionListener(Calc.this); jb_seven.addActionListener(Calc.this); jb_eight.addActionListener(Calc.this); jb_nine.addActionListener(Calc.this); jb_zero.addActionListener(Calc.this); jb_plus.addActionListener(Calc.this); jb_minus.addActionListener(Calc.this); jb_divide.addActionListener(Calc.this); jb_multiply.addActionListener(Calc.this); jb_sin.addActionListener(Calc.this); jb_cos.addActionListener(Calc.this); jb_tan.addActionListener(Calc.this); jb_asin.addActionListener(Calc.this); jb_acos.addActionListener(Calc.this); jb_atan.addActionListener(Calc.this); jb_pie.addActionListener(Calc.this); jb_E.addActionListener(Calc.this); jb_decimalpoint.addActionListener(Calc.this); jb_equalto.addActionListener(Calc.this); jb_fact.addActionListener(Calc.this); jb_power.addActionListener(Calc.this); jb_changesign.addActionListener(Calc.this); jb_reciporcal.addActionListener(Calc.this);

Page 25: Java

jb_todeg.addActionListener(Calc.this); jb_torad.addActionListener(Calc.this); jb_round.addActionListener(Calc.this); jb_CA.addActionListener(Calc.this); jb_CE.addActionListener(Calc.this); jb_Backspace.addActionListener(Calc.this);

jp_center.add(jb_one); jp_center.add(jb_two); jp_center.add(jb_three); jp_center.add(jb_multiply); jp_center.add(jb_reciporcal); jp_center.add(jb_sin); jp_center.add(jb_asin); jp_center.add(jb_four); jp_center.add(jb_five); jp_center.add(jb_six); jp_center.add(jb_divide); jp_center.add(jb_power); jp_center.add(jb_cos); jp_center.add(jb_acos); jp_center.add(jb_seven); jp_center.add(jb_eight); jp_center.add(jb_nine); jp_center.add(jb_plus); jp_center.add(jb_changesign); jp_center.add(jb_tan); jp_center.add(jb_atan); jp_center.add(jb_zero); jp_center.add(jb_decimalpoint); jp_center.add(jb_equalto); jp_center.add(jb_minus); jp_center.add(jb_fact); jp_center.add(jb_pie); jp_center.add(jb_E); jp_center.add(jb_CA); jp_center.add(jb_CE); jp_center.add(jb_round); jp_center.add(jb_todeg); jp_center.add(jb_torad);

Container cp = this.getContentPane(); jp_main.add(jp_top,BorderLayout.NORTH); jp_main.add(jp_center,BorderLayout.CENTER);

Page 26: Java

cp.add(jp_main,BorderLayout.CENTER); setSize(520,250); /* Packing all Commponent, so spaces are left */ pack(); /* Making Window to appear in Center of Screen */ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = this.getPreferredSize(); setLocation(screenSize.width/2 - (frameSize.width/2),screenSize.height/2 - (frameSize.height/2)); setVisible(true);

this.requestFocus(); }

/** * This method is used to reset the condition that * No plus,minus,multiply,division or power action is going on * if there is cancel it. */ public void resetAllButton() { plusPressed = false; minusPressed = false; mulPressed = false; divPressed = false; powerPressed = false; }

/** * This method is use to calculate the factorial of * number of double data type * <p> * @param Double value * @return String value */ public String factorial(double num) { int theNum = (int)num;

if (theNum < 1) { JOptionPane.showMessageDialog(Calc.this,"Cannot find the factorial of numbers less than 1.","Facorial Error",JOptionPane.WARNING_MESSAGE); return ("0"); } else

Page 27: Java

{ for (int i=(theNum -1); i > 1; --i) theNum *= i; return Integer.toString(theNum); } }

/** * This is important method where All action takes places */ public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); String temptext = jtf_display.getText(); boolean decimalPointFound = false; double displayNumber = 0;

/** * Converts String value of jtf_display's to Double value for Calculation */ try { displayNumber = Double.valueOf(jtf_display.getText()).doubleValue(); } catch(NumberFormatException nfe) {}

/** * Checks if equal button is pressed */ if(equalPressed) { jtf_display.setText(""); equalPressed = false; }

if(s.equals("1")) jtf_display.setText(jtf_display.getText()+"1"); if(s.equals("2")) jtf_display.setText(jtf_display.getText()+"2"); if(s.equals("3")) jtf_display.setText(jtf_display.getText()+"3"); if(s.equals("4")) jtf_display.setText(jtf_display.getText()+"4"); if(s.equals("5"))

Page 28: Java

jtf_display.setText(jtf_display.getText()+"5"); if(s.equals("6")) jtf_display.setText(jtf_display.getText()+"6"); if(s.equals("7")) jtf_display.setText(jtf_display.getText()+"7"); if(s.equals("8")) jtf_display.setText(jtf_display.getText()+"8"); if(s.equals("9")) jtf_display.setText(jtf_display.getText()+"9");

if(s.equals("0") && !temptext.equals("")) jtf_display.setText(jtf_display.getText()+"0");

if(s.equals("E")) jtf_display.setText(Double.toString(Math.E)); if(s.equals("PI")) jtf_display.setText(Double.toString(Math.PI)); if(s.equals("toDeg")) jtf_display.setText(Double.toString(Math.toDegrees(displayNumber))); if(s.equals("toRad")) jtf_display.setText(Double.toString(Math.toRadians(displayNumber)));

if(s.equals("CE")) jtf_display.setText(""); if(s.equals("CA")) { resetAllButton(); jtf_display.setText(""); }

if(s.equals(".")) { for (int i =0; i < temptext.length(); ++i) { if(temptext.charAt(i) == '.') { decimalPointFound = true; continue; } } if(!decimalPointFound && temptext.length()==0) jtf_display.setText("0."); if(!decimalPointFound && temptext.length()!=0) jtf_display.setText(jtf_display.getText()+".");

Page 29: Java

}

/** * Calulation of sin,cos etc */ if(s.equals("Sin")) { if(jrb_deg.isSelected()) jtf_display.setText(Double.toString(Math.sin((displayNumber*Math.PI)/180))); else { jtf_display.setText(Double.toString(Math.sin(displayNumber))); // decimalPointpressed } }

if(s.equals("Cos")) { if(jrb_deg.isSelected()) jtf_display.setText(Double.toString(Math.cos((displayNumber*Math.PI)/180))); else { jtf_display.setText(Double.toString(Math.cos(displayNumber))); // decimalPointpressed } }

if(s.equals("Tan")) { if(jrb_deg.isSelected()) jtf_display.setText(Double.toString(Math.tan((displayNumber*Math.PI)/180))); else { jtf_display.setText(Double.toString(Math.tan(displayNumber))); // decimalPointpressed } }

if(s.equals("aSin")) { if(jrb_deg.isSelected()) jtf_display.setText(Double.toString(Math.asin((displayNumber*Math.PI)/180))); else { jtf_display.setText(Double.toString(Math.asin(displayNumber))); // decimalPointpressed

Page 30: Java

} }

if(s.equals("aCos")) { if(jrb_deg.isSelected()) jtf_display.setText(Double.toString(Math.acos((displayNumber*Math.PI)/180))); else { jtf_display.setText(Double.toString(Math.acos(displayNumber))); // decimalPointpressed } }

if(s.equals("aTan")) { if(jrb_deg.isSelected()) jtf_display.setText(Double.toString(Math.atan((displayNumber*Math.PI)/180))); else { jtf_display.setText(Double.toString(Math.atan(displayNumber))); // decimalPointpressed } }

/** * Calculation of "/""*""+""-" */ if(s.equals("*")) { resetAllButton(); mulPressed = true; try { tempdisplayNum = displayNumber; } catch(NumberFormatException mule) { tempdisplayNum = 0; } jtf_display.setText(""); }

if(s.equals("+")) { resetAllButton(); plusPressed = true; try

Page 31: Java

{ tempdisplayNum = displayNumber; } catch(NumberFormatException pluse) { tempdisplayNum = 0; } jtf_display.setText(""); }

if(s.equals("-")) { resetAllButton(); minusPressed = true; try { tempdisplayNum = displayNumber; } catch(NumberFormatException sube) { tempdisplayNum = 0; } jtf_display.setText(""); }

if(s.equals("/")) { resetAllButton(); divPressed = true; try { tempdisplayNum = displayNumber; } catch(NumberFormatException dive) { tempdisplayNum = 0; } jtf_display.setText(""); }

/** * It calculate power */ if(s.equals("x^n")) { powerPressed = true; try { tempdisplayNum = displayNumber; } catch(NumberFormatException dive) { tempdisplayNum = 0; }

Page 32: Java

jtf_display.setText(""); }

/** * Events after "=" is pressed */ if(s.equals("=")) { if(mulPressed) jtf_display.setText(Double.toString(tempdisplayNum*displayNumber)); if(plusPressed) jtf_display.setText(Double.toString(tempdisplayNum+displayNumber)); if(minusPressed) jtf_display.setText(Double.toString(tempdisplayNum-displayNumber)); if(divPressed) jtf_display.setText(Double.toString(tempdisplayNum/displayNumber)); if(powerPressed) jtf_display.setText(Double.toString(Math.pow(tempdisplayNum,displayNumber)));

resetAllButton(); equalPressed = true; }

/** * Events for more functions "1/x""+/-""x!""Round" */ if(s.equals("1/x")) jtf_display.setText(Double.toString(1/displayNumber)); if(s.equals("+/-") && displayNumber!=0) jtf_display.setText(Double.toString(-displayNumber)); if(s.equals("x!")) jtf_display.setText(factorial(displayNumber)); if(s.equals("Round")) jtf_display.setText(Double.toString(Math.round(displayNumber)));

/** * For BackSpace Event */ if(s.equals("BackSpace")) { String temptextt = jtf_display.getText(); if(!temptextt.equals("")) jtf_display.setText(temptextt.substring(0, temptextt.length() - 1)); }

}

Page 33: Java

public void mouseClicked(MouseEvent me) { }

public void mouseEntered(MouseEvent me) {

}

public void mouseExited(MouseEvent me) {

}

public void mouseReleased(MouseEvent me) {} public void mousePressed(MouseEvent me) {}

public static void main(String args[]) { try

{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch(Exception e) {} new Calc(); }}

Page 34: Java

OUTPUT:

RESULT: Thus the program is written to implement Scientific Calculator.

Page 35: Java

12 LINKED LIST 9.9.2010

AIM: To write a java program to implement linked list in java.

ALGORITHM:Step 1:Start the program.Step 2:Create a linked list.Step 3:Enter elements into the list.Step4:Then enter elements into the various positions in the list.Step 5:Delete elements in the list.Step 6:Stop

Page 36: Java

PROGRAM:import java.util.*;

public class LinkedListExample{  public static void main(String[] args) {    System.out.println("Linked List Example!");    LinkedList <Integer>list = new LinkedList<Integer>();    int num1 = 11, num2 = 22, num3 = 33, num4 = 44;    int size;    Iterator iterator;    //Adding data in the list    list.add(num1);    list.add(num2);    list.add(num3);    list.add(num4);    size = list.size();    System.out.print( "Linked list data: ");      //Create a iterator    iterator = list.iterator();         while (iterator.hasNext()){      System.out.print(iterator.next()+" ");      }    System.out.println();    //Check list empty or not    if (list.isEmpty()){      System.out.println("Linked list is empty");    }    else{      System.out.println( "Linked list size: " + size);    }    System.out.println("Adding data at 1st location: 55");    //Adding first    list.addFirst(55);    System.out.print("Now the list contain: ");    iterator = list.iterator();    while (iterator.hasNext()){      System.out.print(iterator.next()+" ");      }    System.out.println();    System.out.println("Now the size of list: " + list.size());    System.out.println("Adding data at last location: 66");    //Adding last or append    list.addLast(66);    System.out.print("Now the list contain: ");    iterator = list.iterator();    while (iterator.hasNext()){

Page 37: Java

      System.out.print(iterator.next()+" ");      }    System.out.println();    System.out.println("Now the size of list: " + list.size());    System.out.println("Adding data at 3rd location: 55");    //Adding data at 3rd position    list.add(2,99);    System.out.print("Now the list contain: ");    iterator = list.iterator();    while (iterator.hasNext()){      System.out.print(iterator.next()+" ");      }    System.out.println();    System.out.println("Now the size of list: " + list.size());    //Retrieve first data    System.out.println("First data: " + list.getFirst());    //Retrieve lst data    System.out.println("Last data: " + list.getLast());    //Retrieve specific data    System.out.println("Data at 4th position: " + list.get(3));    //Remove first    int first = list.removeFirst();    System.out.println("Data removed from 1st location: " + first);    System.out.print("Now the list contain: ");    iterator = list.iterator();    //After removing data    while (iterator.hasNext()){      System.out.print(iterator.next()+" ");      }    System.out.println();    System.out.println("Now the size of list: " + list.size());    //Remove last    int last = list.removeLast();    System.out.println("Data removed from last location: " + last);    System.out.print("Now the list contain: ");    iterator = list.iterator();    //After removing data    while (iterator.hasNext()){      System.out.print(iterator.next()+" ");      }    System.out.println();    System.out.println("Now the size of list: " + list.size());    //Remove 2nd data    int second = list.remove(1);    System.out.println("Data removed from 2nd location: " + second);    System.out.print("Now the list contain: ");

Page 38: Java

    iterator = list.iterator();    //After removing data    while (iterator.hasNext()){      System.out.print(iterator.next()+" ");      }    System.out.println();    System.out.println("Now the size of list: " + list.size());    //Remove all    list.clear();    if (list.isEmpty()){      System.out.println("Linked list is empty");    }    else{      System.out.println( "Linked list size: " + size);    }  }}

Page 39: Java

OUTPUT:E:\java>java LinkedListExampleLinked List Example!Linked list data: 11 22 33 44Linked list size: 4Adding data at 1st location: 55Now the list contain: 55 11 22 33 44Now the size of list: 5Adding data at last location: 66Now the list contain: 55 11 22 33 44 66Now the size of list: 6Adding data at 3rd location: 55Now the list contain: 55 11 99 22 33 44 66Now the size of list: 7First data: 55Last data: 66Data at 4th position: 22Data removed from 1st location: 55Now the list contain: 11 99 22 33 44 66Now the size of list: 6Data removed from last location: 66Now the list contain: 11 99 22 33 44Now the size of list: 5Data removed from 2nd location: 99Now the list contain: 11 22 33 44Now the size of list: 4Linked list is empty

RESULT: Thus the program is written to implement linked list.

Page 40: Java

13 PRODUCER CONSUMER USING MULTITHREAD 9.9.2010

AIM: To design a thread safe implementation of queue class.

ALGORITHM:1.The producer creates tasks and inserts them into work queue.2.The consumer thread pick up task queue and execute then.3.Simple instances of this paradigm in which the task queue can hold only one task,which may be sort or long but it is typically hava bounded size.4.In this simple model,the producer thread can estimate the time taken for consumer work and insert new work in shared buffer.5.Several possibilities exist in which the producer thread must not overwrite the shared buffer when the previous task has not been picked by consumer thread.6.Also,the consumer thread must not pick up tasks until there is something present in the shared data structure and individual consumer thread picks up tasks one at a time.7.Stop

Page 41: Java

PROGRAM:

class Q { int n; boolean valueSet = false; synchronized int get() { if(!valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } System.out.println("Got: " + n); valueSet = false; notify(); return n; } synchronized void put(int n) { if(valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } this.n = n; valueSet = true; System.out.println("Put: " + n); notify(); } }

class Producer implements Runnable { Q q; Producer(Q q) { this.q = q; new Thread(this, "Producer").start(); } public void run() { int i = 0; while(true) { q.put(i++); } } }

Page 42: Java

class Consumer implements Runnable { Q q; Consumer(Q q) { this.q = q; new Thread(this, "Consumer").start(); } public void run() { while(true) { q.get(); } } }

class PCFixed { public static void main(String args[]) { Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); } }

Page 43: Java

OUTPUT:

Got: 2441

Put: 2442

Got: 2442

Put: 2443

Got: 2443

Put: 2444

Got: 2444

Put: 2445

Got: 2445

Put: 2446

Got: 2446

Put: 2447

Got: 2447

Put: 2448

Got: 2448

Put: 2449

Got: 2449

Put: 2450

Got: 2450

Put: 2451

Got: 2451

Put: 2452

Page 44: Java

Got: 2452

Put: 2453

Got: 2453

Put: 2454

Got: 2454

Put: 2455

Got: 2455

Put: 2456

Got: 2456

Put: 2457

Got: 2457

Put: 2458

Got: 2458

Put: 2459

RESULT:

Thus the program is written to implement Producer Consumer problem.

Page 45: Java

14 FIBONICCI AND PRIME USING MULTITHREAD 17.9.2010

AIM: To Write Program to develop multithreaded concept using pipes

ALGORITHM: Step 1:Start the program Step 2:Import required packagesStep3:Declare necessary variables and functionStep 4:Create object parameters pr and pw to pass the valuesStep5: Using thread1()Function find the parameters find prime numbers and Fibonacci series And numbers common both the series.Step 6:Stop the program

Page 46: Java

PROGRAM:

import java.io.*;import java.util.*;class MyThread1 extends Thread {private PipedReader pr;

private PipedWriter pw;

MyThread1(PipedReader pr, PipedWriter pw) {this.pr = pr;this.pw = pw;}

public void run() {try {int i;for (i=1;i<10;i++){int j;for (j=2; j<i; j++){int n = i%j;if (n==0){break;}}if(i == j){pw.write(i+"\n");} }

pw.close();

} catch (IOException e) {}}}

class MyThread2 extends Thread {private PipedReader pr;private PipedWriter pw;

Page 47: Java

MyThread2(PipedReader pr, PipedWriter pw) {this.pr = pr;this.pw = pw;}public void run() {try {int f1, f2 = 1, f3 = 1;for (int i = 1; i <10; i++) {pw.write(f3+"\n");f1 = f2;f2 = f3;f3 = f1 + f2;}pw.close();} catch (IOException e) {}}}class MultithreadedProgram {public static void main(String[] args) throws Exception {ArrayList list1=new ArrayList();ArrayList list2=new ArrayList();PipedWriter pw1 = new PipedWriter();PipedReader pr1 = new PipedReader(pw1);MyThread1 mt1 = new MyThread1(pr1, pw1);System.out.println("Prime Numbers: ");mt1.start();int item1;while ((item1 = pr1.read()) != -1){char ch1=((char) item1); System.out.print(Character.toString(ch1));list1.add(Character.toString(ch1));}pr1.close();PipedWriter pw2 = new PipedWriter();PipedReader pr2 = new PipedReader(pw2);MyThread2 mt2 = new MyThread2(pr2, pw2);System.out.println("Fibonacci Numbers: ");mt2.start();int item2;while ((item2 = pr2.read()) != -1){char ch2=((char) item2); System.out.print(Character.toString(ch2));list2.add(Character.toString(ch2));}

Page 48: Java

pr2.close();System.out.println("Elements common to both lists are:");list1.retainAll(list2);for(int i=0;i<list1.size();i++){System.out.print(list1.get(i));}}}

Page 49: Java

OUTPUT:Prime Numbers: 2357Fibonacci Numbers: 1235813213455Elements common to both lists are:235

RESULT:

Thus the program is written to find prime and Fibonicci number and the elements that are common to both the lists.

Page 50: Java

8 DYNAMIC POLYMORPHISM 11.8.2010

Aim: To develop with suitable hierarchy,classes for point,shape,circle,Rectangule,RectangularSolid etc.Design a simple test application to demonstrate Dynamic polymorphism.

Algorithm:

STEP 1:Start the program.STEP 2:Create the abstract class shape.STEP 3:Declare the methods and abstract method.STEP 4:Define point class which extends shape.STEP 5:Define constructors and member function of that class.STEP 6:Create a circle which extends the sample class.STEP 7:Create a constructor for that class which calls the superclass constructors.STEP 8:Caluculatethe area of the circle.STEP 9:Create a class named cylinder which extends Circle.STEP 10:Create aconstructor which tells superclass constructor.STEP 11:Calculate the area and volume of the cylinder using suitable methods.STEP 12:Declare a class rectangle which inherit the parts.STEP 13:Calculate the area of the rectangle.STEP 14:Create a RectangularSolid class which extends the rectangle class.STEP 15:Define the member function of that class.STEP 16:Create a class named ShapeTest.STEP 17:Create object for all the class.STEP 18:Print the shapes as an array of ShapeSTEP 19:Sort array of shapes using insertion sortSTEP 20:Stop the program.

Page 51: Java

PROGRAM :

public abstract class Shape { private static int counter = 0; private int idNumber; public Shape ()

{ idNumber = ++counter; } public int getIdNumber() { return idNumber;} public double area() { return 0.0; } public double volume() { return 0.0; } public abstract String getName(); // abstract, so omit body

}

public class Point extends Shape { protected int x, y; public Point( int a, int b ) { x = a; y = b; } public int getX() { return x; }

public int getY() { return y; }public String toString()

{ return "[" + x + ", " + y + "]";

} public String getName() { return "Point"; }

}

public class Circle extends Point {

protected double radius; public Circle( double r, int a, int b )

{ super( a, b ); radius = ( r >= 0 ? r : 0 ); } public double area() { return Math.PI * radius * radius; } public String toString() {

return "Center = " + super.toString() +"; Radius = " + radius; } public String getName() { return "Circle"; }

}

Page 52: Java

public class Cylinder extends Circle {

protected double height; public Cylinder( double h, double r, int a, int b )

{ super( r, a, b ); height = ( h >= 0 ? h : 0 ); } public double area()

{ return 2 * super.area() + 2 * Math.PI * radius * height; }

public double volume() { return super.area() * height; } public String toString()

{ return super.toString() + "; Height = " + height; }

public String getName() { return "Cylinder"; }}

public class Rectangle extends Point {

protected double length; protected double width; public Rectangle( double len, double wid, int a, int b )

{ super( a, b );

length = ( len >= 0 ? len : 0 ); width = ( wid >= 0 ? wid : 0 ); } public double area() { return length * width; }

public String toString() {

return "Center = " + super.toString() + "; Length = " + length + ", Width = " + width;

} public String getName()

{ if (length == width) return "Square"; else return "Rectangle"; }

}

Page 53: Java

public class RectangularSolid extends Rectangle {

protected double height; public RectangularSolid(double h, double len, double wid, int a, int b)

{ super(len, wid, a, b); height = ( h >= 0 ? h : 0 ); }

public double area() {

return 2 * super.area() +2 * length * height +2 * width * height; } public double volume() { return super.area() * height; } public String toString()

{ return super.toString() + "; Height = " + height; } public String getName()

{ if (length == width && length == height) return("Cube"); else return "RectangularSolid"; }

}

public class ShapeTest {

private Shape shapes[]; public void createShapes()

{ shapes = new Shape[15]; shapes[0] = new Rectangle(3.0, 4.0, 6, 8); shapes[1] = new Point(7, 11); shapes[2] = new Circle(3.5, 22, 8); shapes[3] = new Cylinder(10, 3.3, 10, 10); shapes[4] = new RectangularSolid(2.0, 3.0, 4.0, 6, 8); shapes[5] = new Point(8, 12); shapes[6] = new Rectangle(2.0, 2.0, 7, 9); shapes[7] = new Circle(3.6, 23, 9); shapes[8] = new Cylinder(12, 3.4, 20, 20); shapes[9] = new Rectangle(6.0, 6.0, 5, 7); shapes[10] = new RectangularSolid(3.0, 3.0, 3.0, 10, 4); shapes[11] = new Point(9, 13); shapes[12] = new Circle(3.7, 24, 10); shapes[13] = new Cylinder(14, 3.5, 30, 30);

Page 54: Java

shapes[14] = new RectangularSolid(4.0, 4.0, 4.0, 8, 9); }

public void printShapes() {

System.out.println("PRINT THE SHAPES AS AN ARRAY OF SHAPE");

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

System.out.println(shapes[i].getName() + ": " + shapes[i].toString() + ", ID: " + shapes[i].getIdNumber()); System.out.println("Area = " + shapes[i].area()); System.out.println("Volume = " + shapes[i].volume()); System.out.println(); } } public void insertionSort ()

{ for (int index = 1; index < shapes.length; index++)

{ Shape key = shapes[index]; int position = index; while (position > 0 && compareShapes(shapes[position-1], key) > 0)

{ shapes[position] = shapes[position-1]; position--; } shapes[position] = key; } } private int compareShapes (Shape s1, Shape s2)

{ if ((s1.getName()).equals(s2.getName())) return s1.getIdNumber() - s2.getIdNumber(); else return (s1.getName()).compareTo(s2.getName()); } public static void main (String[] args)

{ ShapeTest shapeTest = new ShapeTest(); ShapeTest.createShapes(); ShapeTest.insertionSort(); ShapeTest.printShapes(); }}

Page 55: Java

OUTPUT:

C:\Documents and Settings\Administrator>cd des*

C:\Documents and Settings\Administrator\Desktop>cd C:\Program Files\Java\jdk1.5.0_03\bin

C:\Program Files\Java\jdk1.5.0_03\bin>javac Shape.java

C:\Program Files\Java\jdk1.5.0_03\bin>javac Point.java

C:\Program Files\Java\jdk1.5.0_03\bin>javac circle.java

C:\Program Files\Java\jdk1.5.0_03\bin>javac Cylinder.java

C:\Program Files\Java\jdk1.5.0_03\bin>javac Rectangle.java

C:\Program Files\Java\jdk1.5.0_03\bin>javac RectangularSolid.java

C:\Program Files\Java\jdk1.5.0_03\bin>javac ShapeTest.java

C:\Program Files\Java\jdk1.5.0_03\bin>java ShapeTestPRINT THE SHAPES AS AN ARRAY OF SHAPECircle: Center = [22, 8]; Radius = 3.5, ID: 3Area = 38.48451000647496Volume = 0.0

Circle: Center = [23, 9]; Radius = 3.6, ID: 8Area = 40.71504079052372Volume = 0.0

Circle: Center = [24, 10]; Radius = 3.7, ID: 13Area = 43.00840342764427Volume = 0.0

Cube: Center = [10, 4]; Length = 3.0, Width = 3.0; Height = 3.0, ID: 11Area = 54.0Volume = 27.0

Cube: Center = [8, 9]; Length = 4.0, Width = 4.0; Height = 4.0, ID: 15Area = 96.0Volume = 64.0

Cylinder: Center = [10, 10]; Radius = 3.3; Height = 10.0, ID: 4Area = 275.76900313211206Volume = 342.11943997592846

Page 56: Java

Cylinder: Center = [20, 20]; Radius = 3.4; Height = 12.0, ID: 9Area = 328.9875826839231Volume = 435.8017329059761

Cylinder: Center = [30, 30]; Radius = 3.5; Height = 14.0, ID: 14Area = 384.84510006474966Volume = 538.7831400906495

Point: [7, 11], ID: 2Area = 0.0Volume = 0.0

Point: [8, 12], ID: 6Area = 0.0Volume = 0.0

Point: [9, 13], ID: 12Area = 0.0Volume = 0.0

Rectangle: Center = [6, 8]; Length = 3.0, Width = 4.0, ID: 1Area = 12.0Volume = 0.0

RectangularSolid: Center = [6, 8]; Length = 3.0, Width = 4.0; Height = 2.0, ID:5Area = 52.0Volume = 24.0

Square: Center = [7, 9]; Length = 2.0, Width = 2.0, ID: 7Area = 4.0Volume = 0.0

Square: Center = [5, 7]; Length = 6.0, Width = 6.0, ID: 10Area = 36.0Volume = 0.0

RESULT:Thus the program to demonstrate dynamic polymorphism using java was written and output is achieved.

Page 57: Java

5 COMPLEX NUMBER 28.7.2010

AIM:To create a java code to get number as input and write itin complex form and find

addition ,subtarction,and multiplication forsuch two complexnumbers.

ALGORITHM:Step 1: Start the program.Step 2: Declare the necessary member variables and member functions.Step 3: Using getvalue() function get number to write it in complex form.Step 4: Using addition() function find the sum of two complex numbers by adding the real part of complex number and imaginary part of the complex numbers.Step 5: Similar to addition use subtarction() function,subtract the real part of one with real part of another complex number and imaginary part of one with imaginary part of another complex number.Step 6: Using multiplication() function find multiplie of two complex numbers.Step 7: Print all the function values.Step 8:Stop the program.

Page 58: Java

PROGRAM:

public class complexnumber{ private int a; private int b; public complexnumber(){}public complexnumber(int a,int b){ this.a=a; this.b=b;}public string getcomplexvalue(){ if(this.b<0) { return a+""+b+"i"; } else { return a+"+"+b+"i";}}public static string addition(complexnumber num1,complexnumber num2){ int a1=num1.a+num2.a; int b1=num1.b+num2.b; if(b1<0) { return a1+""+b1+"i"; }else{ return a1+"+"+b1+"i";} }public static string subtraction(complexnumber num1,complexnumber num2){int a1=num1.a-num2.a; int b1=num1.b-num2.b;if(b1<0){ return a1+""+b1+"i";}else

Page 59: Java

{ return a1+"+"+b1+"i";}}public static string multiplication(complexnumber num1,complexnumber num2){ int a1=num1.a*num2.a; int b1=num1.b*num2.b; int vi1=num1.a*num2.b; int vi2=num2.a*num1.b; int vi; vi=vi1+vi2; if(vi<0){ return a1-b1+""+vi+"i";}else{ return a1-b1+"+"+vi+"i";} }public static void main(String args[]){ complexnumber com1=new complexnumber(-2,-3); complexnumber com2=new complexnumber(-4,-5); System.out.println(com1.getcomplexvalue()); System.out.println(com2.getcomplexvalue()); System.out.println("addition of 2 nos:"+complexnumber.addition(com1,com2)); system.out.println("subtraction of 2 nos:"+complexnumber.subtraction(com1,com2));system.out.println("multiplication of 2 nos:"+complexnumber.multiplication(com1,com2));}}

Page 60: Java

OUTPUT: -2 -3i.-4 -5i.Addition of both complex number: -6 -8i.Subtraction of both complex number:2+2i.Multiplication of both complex number:-7 +22i.

RESULT: Thus the program for addition ,subtraction,multiplication of complex numbers using

JAVA has written and the expected output is achieved.

Page 61: Java

2 STACK ADT 21.7.2010

AIM: To design a java interface for stack ADT.

ALGORITHM:Step 1: Start the programStep 2: create :: Stack a—create an empty stackStep 3: push :: a->Stack a->Stack a—push an element on the stackStep 4: pop :: Stack a->(a.,Stack a)—pop an element off the stackStep 5: empty :: Stack a->Bool—tells whether stack is emptyStep 6: pop(push x s)=(x,s)Step 7: pop(create)errorStep 8: The interface to the stack ADT is defined as follows(file=”MyStack.java”);Step 9: A simple stack testing class(file=”StackTest.java”)Step 10:End the program

Page 62: Java

PROGRAM:import java.io.*;import java.util.*;class stack{static void pushop(Stack s,int a){s.push(new Integer(a));System.out.println("Push("+a+")");System.out.println("Stack:"+s);}static void popop(Stack s){System.out.println("Pop");Integer a=(Integer)s.pop();System.out.println("Stack:"+s);}public static void main(String[] args){Scanner in=new Scanner(System.in);Stack s=new Stack();System.out.println("Enter the value of n:");int n=in.nextInt();for(int i=0;i<n;i++){System.out.println("Enter the object to inserted:");int x=in.nextInt();pushop(s,x);}for(int i=0;i<n;i++){popop(s);}try{popop(s);}catch(EmptyStackException e){System.out.println("Empty stack");}}}

Page 63: Java

OUTPUT:Enter the value of n:3Enter the object to inserted:2 3Push(2)Stack:[2]Enter the object to inserted:Push(3)Stack:[2, 3]Enter the object to inserted:4Push(4)Stack:[2, 3, 4]PopStack:[2, 3]PopStack:[2]PopStack:[]PopEmpty stack

RESULT: Thus java program is written to find stack

Page 64: Java

1.3 FACTORIAL 6.7.2010

AIM: To write a java program to find factorial of a number.ALGORITHM:1.Start the program.2.Get the number from the user.3.Find the factorial of the number using for loop.4.Print the fatorial value.5.Stop.

Page 65: Java

PROGRAM:import java.util.*;class fact{public static void main(String[] args){Int I,sum=1;Scanner in=new Scanner(System.in);System.out.,println(“Enter the number:”);int a=in.nextInt();for(i=1;i<=a;i++){sum=sum*i;}System.out.println(“The factorial is:”+sum);}}

Page 66: Java

OUTPUT:Enter the number:5The Fatorial is:120

RESULT: Thus the program is written to find the factorial of the number.

Page 67: Java

1.1 FIBONICCI SERIES 6.7.2010

AIM: To write a java program to find the fibonicci series.ALGORITHM:1.Start the program.2.Get the number from the user.3.Find the fibonicci series using the formula f1=f2,f2=sum,sum=f1+f2.4.Print the result.5.Stop.

Page 68: Java

PROGRAM:import java.util.*;class fibo{public static void main(String args[]){System.out.println(“Program to find fibonicci series”);int i,sum=1;int f1,f2=0;Scanner in=new Scanner(System.in);System.out.printl;n(“Enter the number:”);int a=in.nextInt();System.out.println(“Output”);for(i=0;i<=a;i++){System.out.println(+sum);f1=f2;f2=sum;sum=f1+f2;}}}

Page 69: Java

OUTPUT:Program to find fibonicci seriesEnter the number:15Output1123581321345589144233377610987

RESULT: Thus the program is written to find fibonicci series.

Page 70: Java

1.4 ARITHMETIC OPERATION USING 6.7.2010 COMMAND LINE ARGUMENTS

AIM: To write a java program to do arithmetic operation using command line arguments.

ALGORITHM:1.Start the program.2.Assign values that are given during command line to variables.3.Perform basic arithmetic operations.5.Stop

Page 71: Java

PROGRAM:import java.util.*;class arith{public static void main(String[] args){int a=Integer.parseInt(args[0]);int b=Integer.parseInt(args[1]);System.out.println(“Addition:”+(a+b));System.out.println(“Subtraction:”+(a-b));System.out.println(“Multiplication:”+(a*b));System.out.println(“(“Division:”+(a/b));System.out.println(“Modulo:”+(a%b));}}

Page 72: Java

OUTPUT:D:\java>java arith 4 5Addition:9Subtraction:-1Multiplication:20Division:0Modulo:4

RESULT: Thus the program is written to do arithmetic operations using command line argument

Page 73: Java

1.2 PRIME 6.7.2010

AIM: To write java program to find whether given number is prime or not

ALGORITHM: Step 1:Start the program Step 2:import the necessary classes from util packageStep 3:Get number from the users Step 4:check whether given no is divisible by other number:Step 5: If it is divisible then print the no is not primeStep 6:else print no is primeStep 7:Stop the program

Page 74: Java

PROGRAM:import java .in.*;import java .util.*;public static void main(String a[]){int i,j=1,n;System.out.println(“enter the no”);Scanner in=new Scanner (Sytem.in);n=in.nextInt();for(i=2;i<n;i++){j=n%i;if(j==0){System.out.println(“Not a prime “);break;}}if(n==i){System.out.println(“prime no”);} } }

Page 75: Java

OUTPUT:Enter the no5Prime noEnter the no10Not a prime

RESULT: Thus Java program is written to find prime or not.

Page 76: Java

15 MULTI-THREADED GUI 23.9.2010

AIM: To develop a multithreaded GUI application.

ALGORITHM:1.Import the required packages.2.Create class that implements actionlistener and mouse listener.3.Create menus,menuitems,buttons.4.Add menuitems to menus and buttons to toolbars.5.Add mouse listener and perform necessary operation.6.Exit the application.

Page 77: Java

PROGRAM:ChatServer.java

import java.io.*;import java.util.*;import java.net.*;import static java.lang.System.out;

public class ChatServer { Vector<String> users = new Vector<String>(); Vector<HandleClient> clients = new Vector<HandleClient>();

public void process() throws Exception { ServerSocket server = new ServerSocket(9999,10); out.println("Server Started..."); while( true) { Socket client = server.accept(); HandleClient c = new HandleClient(client); clients.add(c); } // end of while } public static void main(String ... args) throws Exception { new ChatServer().process(); } // end of main

public void boradcast(String user, String message) { // send message to all connected users for ( HandleClient c : clients ) if ( ! c.getUserName().equals(user) ) c.sendMessage(user,message);

}

class HandleClient extends Thread { String name = "";

BufferedReader input;PrintWriter output;

public HandleClient(Socket client) throws Exception { // get input and output streams

input = new BufferedReader( new InputStreamReader( client.getInputStream())) ; output = new PrintWriter ( client.getOutputStream(),true); // read name name = input.readLine(); users.add(name); // add to vector start();

}

Page 78: Java

public void sendMessage(String uname,String msg) { output.println( uname + ":" + msg);}

public String getUserName() { return name; } public void run() { String line;

try { while(true) {

line = input.readLine(); if ( line.equals("end") ) { clients.remove(this); users.remove(name); break;

} boradcast(name,line); // method of outer class - send messages to all

} // end of while } // try catch(Exception ex) { System.out.println(ex.getMessage()); }

} // end of run() } // end of inner class

} // end of Server

ChatClient.java

import java.io.*;import java.util.*;import java.net.*;import javax.swing.*;import java.awt.*;import java.awt.event.*;import static java.lang.System.out;

public class ChatClient extends JFrame implements ActionListener { String uname; PrintWriter pw; BufferedReader br; JTextArea taMessages; JTextField tfInput;

Page 79: Java

JButton btnSend,btnExit; Socket client; public ChatClient(String uname,String servername) throws Exception { super(uname); // set title for frame this.uname = uname; client = new Socket(servername,9999); br = new BufferedReader( new InputStreamReader( client.getInputStream()) ) ; pw = new PrintWriter(client.getOutputStream(),true); pw.println(uname); // send name to server buildInterface(); new MessagesThread().start(); // create thread for listening for messages } public void buildInterface() { btnSend = new JButton("Send"); btnExit = new JButton("Exit"); taMessages = new JTextArea(); taMessages.setRows(10); taMessages.setColumns(50); taMessages.setEditable(false); tfInput = new JTextField(50); JScrollPane sp = new JScrollPane(taMessages, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); add(sp,"Center"); JPanel bp = new JPanel( new FlowLayout()); bp.add(tfInput); bp.add(btnSend); bp.add(btnExit); add(bp,"South"); btnSend.addActionListener(this); btnExit.addActionListener(this); setSize(500,300); setVisible(true); pack(); } public void actionPerformed(ActionEvent evt) { if ( evt.getSource() == btnExit ) { pw.println("end"); // send end to server so that server know about the termination System.exit(0); } else { // send message to server pw.println(tfInput.getText()); } }

Page 80: Java

public static void main(String args[]) { // take username from user String name = JOptionPane.showInputDialog(null,"Enter your name :", "Username", JOptionPane.PLAIN_MESSAGE); String servername = "localhost"; try { new ChatClient( name ,servername); } catch(Exception ex) { out.println( "Error --> " + ex.getMessage()); } } // end of main // inner class for Messages Thread class MessagesThread extends Thread { public void run() { String line; try { while(true) { line = br.readLine(); taMessages.append(line + "\n"); } // end of while } catch(Exception ex) {} } }} // end of client

OUTPUT:

Page 81: Java

RESULT: Thus the program is written to implement multi-threaded GUI.

9 INTERFACE FOR STACK ADT 18.8.2010

Page 82: Java

AIM: To design a java interface for stack ADT.

ALGORITHM:Step 1: Start the programStep 2: create :: Stack a—create an empty stackStep 3: push :: a->Stack a->Stack a—push an element on the stackStep 4: pop :: Stack a->(a.,Stack a)—pop an element off the stackStep 5: empty :: Stack a->Bool—tells whether stack is emptyStep 6: pop(push x s)=(x,s)Step 7: pop(create)errorStep 8: The interface to the stack ADT is defined as follows(file=”MyStack.java”);Step 9: A simple stack testing class(file=”StackTest.java”)Step 10:End the program

PROGRAM:

Page 83: Java

import java.util.*;

interface adt{public void push(int c);public int pop();public boolean isempty();public boolean isfull();public void display();}

class st implements adt{int top;int [] st=new int[20];st(){top=-1;}

public boolean isempty(){return(top==-1);}

public boolean isfull(){return(top>=20);}

public void push(int c){if(isfull()){System.out.println("STACK IS FULL");}else{top++;st[top]=c;}}

public int pop(){

Page 84: Java

if(isempty()){System.out.println("STACK IS EMPTY");return 0;}else{int c=st[top];top--;return c;}}

public void display(){if(isempty()){System.out.println("STACK IS EMPTY");}else{for(int i=top;i>=0;i--)System.out.println(st[i]);}}

}

public class stack{public static void main(String args[]){int choice;int element;st s=new st();do{System.out.println("1.PUSH 2.POP 3. DISPLAY 4. EXIT");System.out.println("ENTER UR CHOICE:");Scanner in=new Scanner(System.in);choice=in.nextInt();switch(choice){case 1:

Page 85: Java

try{System.out.println("ENTER AN INTEGER TO PUSH:");element=in.nextInt();s.push(element);}catch(Exception e){System.out.println("Integer values only allowed"+e);}break;case 2:element=s.pop();if(element!=0)System.out.println("THE POPPED CHARECTER IS:"+element);break;case 3:s.display();break;case 4:break;}}while(choice<4);} }

OUTPUT 1:

Page 86: Java

1.PUSH 2.POP 3. DISPLAY 4. EXITENTER UR CHOICE:1ENTER AN INTEGER TO PUSH:561.PUSH 2.POP 3. DISPLAY 4. EXITENTER UR CHOICE:1ENTER AN INTEGER TO PUSH:891.PUSH 2.POP 3. DISPLAY 4. EXITENTER UR CHOICE:389561.PUSH 2.POP 3. DISPLAY 4. EXITENTER UR CHOICE:2THE POPPED CHARECTER IS:891.PUSH 2.POP 3. DISPLAY 4. EXITENTER UR CHOICE:2THE POPPED CHARECTER IS:561.PUSH 2.POP 3. DISPLAY 4. EXITENTER UR CHOICE:2STACK IS EMPTY1.PUSH 2.POP 3. DISPLAY 4. EXITENTER UR CHOICE:3STACK IS EMPTY1.PUSH 2.POP 3. DISPLAY 4. EXITENTER UR CHOICE:4OUTPUT 2:1.PUSH 2.POP 3. DISPLAY 4. EXITENTER UR CHOICE:1ENTER AN INTEGER TO PUSH:WInteger values only allowed : java.util.InputMismatchException1.PUSH 2.POP 3. DISPLAY 4. EXITENTER UR CHOICE:4

Page 87: Java

RESULT: Thus the program for stack ADT using java interface was written and expected output is achieved.

Page 88: Java

7 PRINTING CURRENT DATE AND TIME 11.8.2010

AIM: To write a java program to print current date and time.

ALGORITHM:Step 1:Start the program.Step 2:Create an object for date foramt class.Step 3:From the string of months get the instance.Step 3:Print the current date,time.Step 4:Stop.

Page 89: Java

PROGRAM:import java.util.Calendar;import java.util.Date;import java.text.SimpleDateFormat;

class DateCalendar {public static void main(String args[]) {System.out.println("Display current date and time using Date class>>> ");Date d = new Date();SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");String formattedDate = formatter.format(d);System.out.println("Today's date and Time is:"+d);String months[] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug","Sep", "Oct", "Nov", "Dec"};Calendar calendar = Calendar.getInstance();System.out.println("Display current date and time using Calendar class>>>> ");System.out.print("Date: ");System.out.print(months[calendar.get(Calendar.MONTH)]);System.out.print(" " + calendar.get(Calendar.DATE) + " ");System.out.println(calendar.get(Calendar.YEAR));System.out.print("Time: ");System.out.print(calendar.get(Calendar.HOUR) + ":");System.out.print(calendar.get(Calendar.MINUTE) + ":");System.out.println(calendar.get(Calendar.SECOND));

}}

Page 90: Java

OUTPUT:

Display current date and time using Date class>>>Today's date and Time is:Sun Sep 26 09:19:30 IST 2010Display current date and time using Calendar class>>>>Date: Sep 26 2010Time: 9:19:30

RESULT: Thus the program is written to print current date and time.

Page 91: Java

3 STACK USING LINKED LIST 21.7.2010

AIM: To implement stack using linked list.

ALGORITHM: Step 1:Start the program.Step 2:Initialize head and tail as null.Step 3:Define a method to insert into the head of the stack.Step 4:Define a method to retrieve top element of the stack.Step 6:Based on user input do necessary operation.Step 7:Close the program.

Page 92: Java

PROGRAM:class Link{public Object data;public Link next;public Link(Object d, Link n){data = d; next = n;}}//LINKEDLIST CLASS AND MAINimport java.util.Scanner;

class LinkList{private Link head; // reference to first Link

private Link tail; // reference to last Link

private int size;

public LinkList(){

tail = null;head = null;

}

public Object peekHead() // return reference to first Object{return head.data;}

public Object peekTail() // return reference to last Object{return tail.data;}//THE ADD METHOD, NOT SURE IF DONE RIGHTpublic void addHead(Object newData){if (head == null){head = new Link(newData, tail);

Page 93: Java

}

else if (head != null && tail == null){tail = head;head = new Link (newData, tail);}else {

head.next = head;head = new Link (newData, head.next);

}}

public void addTail(Object newData){

}

//THE REMOVE METHODpublic Object removeHead(){Link removing = head;if (head != null){head = head.next; }

return removing.data;

}

//MAIN METHODpublic static void main (String[] args){Scanner scan = new Scanner(System.in);

int choice = 0;

LinkList first = new LinkList();

while (choice != 6){

Page 94: Java

System.out.println("What would you like to do? (enter the number)");System.out.println("1 - Push onto Head of Stack.");System.out.println("2 - Remove from Head of Stack.");System.out.println("3 - Peek at Head of Stack.");System.out.println("4 - Push at Tail of Stack.");System.out.println("5 - Peak at Tail of Stack.");System.out.println("6 - Close Program.");choice = scan.nextInt();

switch(choice){case 1:System.out.println("What do you want to push on Head?");Object pushingHead = scan.next();

first.addHead(pushingHead);break;

case 2:System.out.println("Removing: " + first.removeHead());break;

case 3:System.out.println("Peeking at Head of Stack: " + first.peekHead());break;

case 4:System.out.println("What do you want to push on Tail?");Object pushingTail = scan.next();

first.addHead(pushingTail);break;

case 5:System.out.println("Peeking at Tail of Stack: " + first.peekTail());break;

case 6:System.out.println("Good Bye!");break;}}

}}

Page 95: Java

OUTPUT:What would you like to do? (enter the number)1 - Push onto Head of Stack.2 - Remove from Head of Stack.3 - Peek at Head of Stack.4 - Push at Tail of Stack.5 - Peak at Tail of Stack.6 - Close Program.1What do you want to push on Head?12What would you like to do? (enter the number)1 - Push onto Head of Stack.2 - Remove from Head of Stack.3 - Peek at Head of Stack.4 - Push at Tail of Stack.5 - Peak at Tail of Stack.6 - Close Program.3Peeking at Head of Stack: 12What would you like to do? (enter the number)1 - Push onto Head of Stack.2 - Remove from Head of Stack.3 - Peek at Head of Stack.4 - Push at Tail of Stack.5 - Peak at Tail of Stack.6 - Close Program.4What do you want to push on Tail?23What would you like to do? (enter the number)1 - Push onto Head of Stack.2 - Remove from Head of Stack.3 - Peek at Head of Stack.4 - Push at Tail of Stack.5 - Peak at Tail of Stack.6 - Close Program.5Peeking at Tail of Stack: 12What would you like to do? (enter the number)1 - Push onto Head of Stack.2 - Remove from Head of Stack.3 - Peek at Head of Stack.4 - Push at Tail of Stack.5 - Peak at Tail of Stack.6 - Close Program.

Page 96: Java

2Removing: 23What would you like to do? (enter the number)1 - Push onto Head of Stack.2 - Remove from Head of Stack.3 - Peek at Head of Stack.4 - Push at Tail of Stack.5 - Peak at Tail of Stack.6 - Close Program.

RESULT: Thus the program is written to implement stack using linked list.

Page 97: Java

4 QUEUE 28.7.2010

AIM: To develop a Java program with simple Queue using Array

ALGORITHM:

Step 1: Declare a class queue in which implements the variable maxsize ,fronts,rear,nitemsStep 2: Declare a parameterized constructor Step 3: Get the function insert () to put item at rear end of queueStep 4:Get function remove to take item from front of queueStep 5: Get the function peek front() to peek item at front of queueStep 6: Declare Boolean to check queue sizeStep 7: Declare main imside class queue appStep 8: Declare an object thequeue Step 9: call insert and remove functionsStep 10:stop the program

Page 98: Java

PROGRAM:

class Queue{private int maxSize;private long[] queArray;private int front;private int rear;private int nItems;

public Queue(int s) // constructor{maxSize = s;queArray = new long[maxSize];front = 0;rear = -1;nItems = 0;}

public void insert(long j) // put item at rear of queue{if(rear == maxSize-1) // deal with wraparoundrear = -1;queArray[++rear] = j; // increment rear and insertnItems++; // one more item}

public long remove() // take item from front of queue{long temp = queArray[front++]; // get value and incr frontif(front == maxSize) // deal with wraparoundfront = 0;nItems--; // one less itemreturn temp;}

public long peekFront() // peek at front of queue{return queArray[front];}

public boolean isEmpty() // true if queue is empty{return (nItems==0);}

Page 99: Java

public boolean isFull() // true if queue is full{return (nItems==maxSize);}

public int size() // number of items in queue{return nItems;}

} class QueueApp{public static void main(String[] args){Queue theQueue = new Queue(5); // queue holds 5 itemstheQueue.insert(10); // insert 4 itemstheQueue.insert(20);theQueue.insert(30);theQueue.insert(40);theQueue.remove(); // remove 3 itemstheQueue.remove(); // (10, 20, 30)theQueue.remove();theQueue.insert(50); // insert 4 more itemstheQueue.insert(60); // (wraps around)theQueue.insert(70);theQueue.insert(80);while( !theQueue.isEmpty() ) // remove and display{ long n = theQueue.remove(); // (40, 50, 60, 70, 80)System.out.print(n);System.out.print(" ");}System.out.println(" ");} }

Page 100: Java

OUTPUT:

40 50 60 70 80

RESULT: Thus the program is written to implement queue.

Page 101: Java

6 READ FILE CONTENT 11.8.2010

AIM:

To develop a java program that reads file content and prints no of chars, lines, words, vowels.

ALGORITHM:Step 1: Declare the class DateCalenderStep 2:Inside class declare void mainStep 3: Declare integer variablesStep 4:using getchar get size ,length,buffer,starting locationStep 5:using for loop get check for vowelsStep 6:using object f1 write char to bufferStep 7:read the content writtenStep 8: stop the program

Page 102: Java

PROGRAM:import java.io.*;class DateCalendar{public static void main(String args[])throws Exception{int i,l=0,w=0,vow=0;String s="it is java program"+"\nplatform independent";char buffer[]=new char[s.length()];s.getChars(0,s.length(),buffer,0);System.out.println("no of characters="+s.length());for(i=0;i<s.length();i++){ char c=s.charAt(i);if(c=='\t'||c=='\b'||c==' '||c=='\n'){ w++;}if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {vow++; }}System.out.println("no of words:"+w);System.out.println("no of vowels:"+vow);FileWriter f1=new FileWriter("c:/a.txt");f1.write(buffer);f1.close();FileReader fr=new FileReader("c:/a.txt");BufferedReader br=new BufferedReader(fr);String t;while((t=br.readLine())!=null){l++;}System.out.println("no of lines"+l);fr.close();}}

Page 103: Java

OUTPUT:no of characters=39no of words:5no of vowels:12no of lines2

RESULT: Thus the program is written to print number of characters,vowels in a file.