Object Oriented Programming With Java - May/June 2012

Question 3

(a) Write a program using BufferedInputStream, FileInputStream, BufferedOutputStream, FileOutputStream to copy Content of one file File1.txt into another file File2.txt.

import java.io.*;
class CopyFileInJavaH2E
{
 public static void main(String args[]) throws IOException
 {
  int ch;
  FileInputStream fin = new FileInputStream("File1.txt");
  BufferedInputStream bfin = new BufferedInputStream(fin);
  FileOutputStream fout = new FileOutputStream("File2.txt");
  BufferedOutputStream bfout = new BufferedOutputStream(fout);
  while((ch=bfin.read()) != -1)
   bfout.write(ch);
  bfin.close();
  bfout.close();   
 }
}

(b) Describe abstract class called Shape which has three subclasses say Triangle,Rectangle,Circle. Define one method area() in the abstract class and override this area() in these three subclasses to calculate for specific object i.e. area() of Triangle subclass should calculate area of triangle etc. Same for Rectangle and Circle.

abstract class Shape
{
 double dimension1,dimension2,radius;
 abstract double area();
}
class Triangle extends Shape
{
 Triangle(double d1,double d2)
 {
  dimension1=d1;
  dimension2=d2;
 }
 double area()
 {
  System.out.print("Area Of Triangle : ");
  return ((dimension1*dimension2)/2);
 }
}
class Rectangle extends Shape
{
 Rectangle(double d1,double d2)
 {
  dimension1=d1;
  dimension2=d2;
 }
 double area()
 {
  System.out.print("Area Of Rectangle : ");
  return (dimension1*dimension2);
 }
}
class Circle extends Shape
{
 Circle(double d1)
 {
  radius = d1;
 }
 double area()
 {
  System.out.print("Area Of Circle : ");
  return ((22*radius*radius)/7);
 }
}
class AbstractClassWithSubclassExampleH2E
{
 public static void main(String args[])
 {
  Triangle t = new Triangle(25,20);
  Rectangle r = new Rectangle(15,20);
  Circle c = new Circle(49);
  Shape shapeRef;
  shapeRef = t;
  System.out.println(shapeRef.area());
  System.out.println();
  shapeRef = r;
  System.out.println(shapeRef.area());
  System.out.println();  
  shapeRef = c;
  System.out.println(shapeRef.area());
 }
}


(a) Write a program to display the bytes of a file in reverse sequence. Provide the name of the file as a command line argument. (Use RandomAccessFile).

import java.io.*;
public class RandomAccessFileExampleH2E{
 public static void main(String[] args) throws IOException{
  File file = new File(args[0]);
  if(!file.exists())
  {
   System.out.println("File does not exist.");
   System.exit(0);
  }
  try{
   //Open the file for both reading and writing
   RandomAccessFile rand = new RandomAccessFile(file,"r"); 
   int i=(int)rand.length();
   System.out.println("Length: " + i);
      
   for(int ct = (i-1); ct > 0; ct--){
    rand.seek(ct);
    byte b = rand.readByte();
    System.out.print(b); //read the character
   }
   rand.close();
  }
   catch(IOException e)
  {
  System.out.println(e.getMessage());
  }
 }
}


(b) Write a program that illustrates interface inheritance. Interface P is extended by P1 and P2. Interface P12 inherits from both P1 and P2.Each interface declares one constant and one method. class Q implements P12.Instantiate Q and invoke each of its methods. Each method displays one of the constants.

interface P
{
 public static final int p = 5;
 void methodP();
}
interface P1 extends P
{
 public static final int p1 = 10;
 void methodP1();
}
interface P2 extends P
{
 public static final int p2 = 15;
 void methodP2();
}
interface P12 extends P1,P2
{
 public static final int p12 = 20;
 void methodP12();
} 
class Q implements P12
{
 public void methodP12()
 {
  System.out.println("P12 class's method and Constant : "+p12);
 }
 public void methodP1()
 {
  System.out.println("P1 class's method and Constant : "+p1); 
 }
 public void methodP2()
 {
  System.out.println("P2 class's method and Constant : "+p2); 
 }
 public void methodP()
 {
  System.out.println("P class's method and Constant : "+p); 
 }
}
class InterfaceWithInheritanceExampleH2E
{
 public static void main(String args[])
 {
  Q obj = new Q();
  obj.methodP12();
  obj.methodP1();
  obj.methodP2();
  obj.methodP();  
 }
}

Question 4

(a) Write an applet that contains three buttons OK,CANCEL and HELP and one textfield. if OK is pressed shown on the status bar-“OK is pressed” and the text field should turn red. When CANCEL is pressed -shown on the status bar-“ CANCEL is pressed “and text field should turn green. When HELP is pressed- shown on the status bar-“HELP is pressed” and the text field should turn yellow.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AppletButtonActionEventH2E" width=300 height=300></applet>
*/
public class AppletButtonActionEventH2E extends Applet implements ActionListener
{
Button ok,cancel,help; TextField t;
String msg = "";
public void init()
{
ok = new Button("OK");
cancel = new Button("CANCEL");
help = new Button("HELP"); t = new TextField();
add(ok);
add(cancel);
add(help); add(t);
ok.addActionListener(this);
cancel.addActionListener(this);
help.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if(str.equals("OK"))
{
msg = "OK is pressed"; t.setBackground(Color.RED);
}
else if(str.equals("CANCEL"))
{
msg = "CANCEL is pressed"; t.setBackground(Color.GREEN);
}
else
{
msg = "HELP is pressed";
}
repaint();
}
public void paint(Graphics g)
{
showStatus(msg); t.setBackground(Color.YELLOW);
}
}
(b) Explain Applet life cycle with demo program.
import java.awt.*;
import java.applet.*;
/*
<applet code="AppletLifeCycle" width=300 height=300>
</applet>
*/
public class AppletLifeCycle extends Applet
{
String msg1,msg2,msg3,msg4;
// called first
public void init()
{
// Initialization
msg1="init section begins";
}
// called second
public void start()
{
// start or resume execution
msg2="start section";
}
// called when applet stopped
public void stop()
{
// suspends execution
msg3="stop section";
}
// called when applet
public void destroy()
{
// execute shutdown activities
msg4="destroy section";
}
public void paint(Graphics g)
{
// redisplay content of window
g.drawString("Demo for basic methods of applet",20,40);
g.drawString(msg1,20,80);
g.drawString(msg2,20,90);
g.drawString(msg3,20,100);
g.drawString(msg4,20,120);
}
}

Question 5

(b) Explain Generics in java with demo program.
class Gen<G>
{
 G Obj; 
 Gen(G ObjI)
 {
  Obj = ObjI; 
 }
 G getObj()
 {
  return Obj;
 }
}
class GenericClassExampleH2E
{
 public static void main(String args[])
 {
  Gen<Integer> ObjGI = new Gen<Integer>(125);
  System.out.println("Value of Object : "+ObjGI.getObj()); 
  Gen<String> ObjGS = new Gen<String>("Help2Engg");
  System.out.println("Value of Object : "+ObjGS.getObj());
 }
}


(b) Differentiate Method Overloading and Method Overriding with example.

class H2EA
{
 int a,b;
 H2EA(int i,int j)
 {
  a=i;
  b=j; 
 }
 void inside()
 {
  System.out.println("Inside H2EA");
 }
 int Multiplication()
 {
  return a*b;
 }
}
class H2EB extends H2EA
{
 int c;
 H2EB(int i,int j,int k)
 {
  super(i,j);
  c=k; 
 }
 void inside()
 {
  System.out.println("Inside H2EB");
 }
 int Multiplication(int x)
 {
  return x*c;
 }
}
class methodOverloadingAndOverridingDifferenceH2E
{
 public static void main(String args[])
 {
  H2EB Obj = new H2EB(5,6,7);
  Obj.inside();  // Method Overriding
  System.out.println("Multiplication = "+Obj.Multiplication());  // Method Overloading
  System.out.println("Multiplication = "+Obj.Multiplication(8)); // Method Overloading 
 }
}


 

Object Oriented Programming With Java(OOPJ) - Nov/Dec 2011

Question 1

(b) Explain the followings:
(i) Dynamic Method Dispatch with example

class First
{
 void display()
 {
  System.out.println("First Class's metohd Display");
 }
}
class Second extends First
{
 void display()
 {
  System.out.println("Second Class's metohd Display");
 }
}
class Third extends First
{
 void display()
 {
  System.out.println("Third Class's metohd Display");
 }
}
public class dynamicMethodDispatchExampleH2E 
{
 public static void main(String args[]) 
 {
  First f = new First();
  Second s = new Second();
  Third t = new Third();
  First fRef;
  fRef = f;
  fRef.display();
  fRef = s;
  fRef.display();
  fRef = t;
  fRef.display();
  
 }
}
  

Question 2

(b) Design a class named Fan to represent a fan. The class contains:
- Three constants named SLOW, MEDIUM and FAST with values 1,2 and 3 to denote the fan speed.
- An int data field named speed that specifies the speed of the fan (default SLOW).
- A boolean data field named f_on that specifies whether the fan is on(default false).
- A double data field named radius that specifies the radius of the fan (default 4).
- A data field named color that specifies the color of the fan (default blue).
- A no-arg constructor that creates a default fan.
- A parameterized constructor initializes the fan objects to given values.
- A method named display() will display description for the fan. If the fan is on, the display() method displays speed, color and radius. If the fan is not on, the method returns fan color and radius along with the message “fan is off”.
Write a test program that creates two Fan objects. One with default values and the other with medium speed, radius 6, color brown, and turned on status true. Display the descriptions for two created Fan objects.



class Fan
{ 
 public static final int SLOW = 1;
 public static final int MEDIUM = 2;
 public static final int FAST = 3;
 int speed;
 boolean f_on;
 double radius;
 String color;
 Fan()
 {
  speed = SLOW;
  f_on = false;
  radius = 4;
  color = "blue";
 }
 Fan(int s,boolean f, double r, String c)
 {
  speed = s;
  f_on = f;
  radius = r;
  color = c;
 }
   public void display()
 {
  if(f_on)
  { 
   System.out.println("Speed of Fan : "+speed);
   System.out.println("Radius of Fan : "+radius);
   System.out.println("Color of Fan : "+color); 
  }
  else
  {
   System.out.println("Fan is Off.");
   System.out.println("Radius of Fan : "+radius);
   System.out.println("Color of Fan : "+color);
  }
 }
}
class Q2bFanClassH2E
{
 public static void main(String args[])
 {
  Fan f1 = new Fan(); 
  f1.display();
  Fan f2 = new Fan(2,true,6,"brown");
  f2.display();
 }
}

(b) Define the Rectangle class that contains:
Two double fields x and y that specify the center of the rectangle, the data field width and height ,
A no-arg constructor that creates the default rectangle with (0,0) for (x,y) and 1 for both width and height.
A parameterized constructor creates a rectangle with the specified x,y,height and width.
A method getArea() that returns the area of the rectangle.
A method getPerimeter() that returns the perimeter of the rectangle.
A method contains(double x, double y) that returns true if the specified point (x,y) is inside this rectangle.
Write a test program that creates two rectangle objects. One with default values and other with user specified values. Test all the methods of the class for both the objects.


class Rectangle
{
 double centerX,centerY,width,height;
 double x1,x2,x3,x4,y1,y2,y3,y4;
 Rectangle()
 {
  centerX=centerY=0;
  width=height=1;
 }
 Rectangle(double x,double y,double w,double h)
 {
  centerX=x;
  centerY=y;
  width=w;
  height=h;
 }
 double getArea()
 {
  return (width*height);
 }
 double getPerimeter()
 {
  
  return ( 2*(width+height) );
 }
 boolean contains(double x,double y)
 {
  x1=x3= ( centerX - (width/2) ); 
  x2=x4= ( centerX + (width/2) ); 
  y1=y2= (centerY + (height/2)); 
  y3=y4= (centerY - (height/2)); 
  if( (x > x1 && x < x4) && (y < y1 && y > y3))
   return true;
  else
   return false;
 }
}
class RectangleH2E
{
 public static void main(String args[])
 {
  Rectangle r1Obj = new Rectangle();
  Rectangle r2Obj = new Rectangle(200,200,100,50);
  System.out.println("Rectangle 1 : Area "+r1Obj.getArea());
  System.out.println("Rectangle 1 : Perimeter "+r1Obj.getPerimeter());
  System.out.println("Rectangle 1 : Contains (3,2) "+r1Obj.contains(3,2));
  System.out.println();
  System.out.println("Rectangle 2 : Area "+r2Obj.getArea());
  System.out.println("Rectangle 2 : Perimeter "+r2Obj.getPerimeter());
  System.out.println("Rectangle 2 : Contains (160,190) "+r2Obj.contains(160,190));
 }
}
 

Question 3


(c) State whether any error exists in the following code. If so, correct the error and
give output.
class Test {
public static void main(String args[]) {
A a = new A();
a.print();
}
}
class A {
String s;
A(String s) {
this.s=s;
}
public void print() {
System.out.println(s);
}
}

class Test
{
public static void main(String args[])
{
A a = new A("Jaydip");
a.print();
}
}
class A
{
String s;
A(String s)
{
this.s=s;
}
public void print()
{
System.out.println(s);
}
}

(c) Give output of the following program:
public class Test {
public static void main(String args[]) {
Count myCount = new Count();
int times=0;
for(int i=0;i<100;i++)
increment(myCount,times);
System.out.println("count is "+myCount.count);
System.out.println("times is "+times);
}
public static void increment(Count c,int times) {
c.count++;
times++;
}
}
class Count {
public int count;
Count(int c){ count=c; }
Count(){ count=1; }
}

//count is 101
//time is 0
public class Test
{
public static void main(String args[])
{
Count myCount = new Count();
int times=0;
for(int i=0;i<100;i++)
increment(myCount,times);
System.out.println("count is "+myCount.count);
System.out.println("times is "+times);
}
public static void increment(Count c,int times)
{
c.count++;
times++;
}
}
class Count
{
public int count;
Count(int c)
{
count=c;
}
Count()
{
count=1;
}
}
 

Question 4

(b) The abstract Vegetable class has three subclasses named Potato, Brinjal and Tomato. Write an application that demonstrates how to establish this class hierarchy. Declare one instance variable of type String that indicates the color of a vegetable. Create and display instances of these objects. Override the toString() method of Object to return a string with the name of the vegetable and its color.
import java.lang.*;
abstract class Vegetable
{
 String colorVeg;
 abstract public String toString();
}
class Potato extends Vegetable
{
 public String toString()
 {
  colorVeg = "Yellow";
  return colorVeg;
 }
}
class Brinjal extends Vegetable
{
 public String toString()
 {
  colorVeg = "Purpul";
  return colorVeg;
 }
}
class Tomato extends Vegetable
{
 public String toString()
 {
  colorVeg = "Red";
  return colorVeg;
 }
}
class abstractClassH2E
{
 public static void main(String args[])
 {
  Potato p = new Potato(); 
  Brinjal b = new Brinjal();
  Tomato t = new Tomato(); 
  Vegetable vegref;
  vegref = p;
  System.out.println("Color of Potato : "+vegref.toString());
  vegref = b;
  System.out.println("Color of Brinjal : "+vegref.toString());
  vegref = t;
  System.out.println("Color of Tomato : "+vegref.toString());
 }
}


(a) (ii) Give output of the following program for value of y=0 and y=2:
public class Test {
public static void main(String args[]) {
try {
System.out.println("calling method a");
a();
System.out.println("return from method a");
} catch(ArithmeticException e) {
System.out.println("main: catch");
} finally {
System.out.println("main: finally");
}
}
public static void a() {
try {
int x=8,y=0;
int z=x/y;
System.out.println("value of z="+z);
} catch(NumberFormatException e) {
System.out.println("method a:catch");
} finally {
System.out.println("method a:finally");
} }}



// y = 0
// calling metod a
// method a : finally 
// main : catch
// main : finally
// y = 2

// calling metod a
// value of z=4
// method a : finally 
// return from method a
// main : finally
public class Test 
{
 public static void main(String args[]) 
 {
  try 
  {
   System.out.println("calling method a");
   a();
   System.out.println("return from method a");
  }
   catch(ArithmeticException e) 
  {
   System.out.println("main: catch");
  }
   finally 
  {
   System.out.println("main: finally");
  }
 }
 public static void a() 
 {
  try 
  {
   int x=8,y=0;
   int z=x/y;
   System.out.println("value of z="+z);
  } 
  catch(NumberFormatException e) 
  {
   System.out.println("method a:catch");
  } 
  finally 
  {
   System.out.println("method a:finally");
  }
  }
}


(b) Write a program that takes input for filename and search word from commandline arguments and checks whether that file exists or not. If exists, the program will display those lines from a file that contains given search word.

import java.io.*;
class FileExistsWordSearchH2E
{
 public static void main(String args[]) throws IOException
 {
  int fileExistFlag;
  boolean wordExists=false;
                                File f1h2e = new File(args[0]);
  fileExistFlag = f1h2e.exists()?1:0;
  if(fileExistFlag == 1)
  {
   BufferedReader fileReader = new BufferedReader(new FileReader(f1h2e));
   String wholeLine;
   String word = args[1];
   while ((wholeLine = fileReader.readLine()) != null) 
   {
    String[] wordArr = wholeLine.split(" "); 
    for(String wordElem:wordArr)
    {
     if(wordElem.equalsIgnoreCase(word))
     {
      System.out.println("'"+word+"'" + " exists in line '" + wholeLine+"'"); 
      wordExists = true;    
     }
    } 
   }
   if(!wordExists)
    System.out.println("Word Not Exists in File");
  }
  else
  {
   System.out.println("File Not Exists");
  }
  
 }
}
 

Question 5

(a) Write an applet that draws four horizontal bars of equal size & of different colors such that they cover up the whole applet area. The applet should operate correctly even if it is resized.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="appletComponentResizedH2E" width=400 height=400>
</applet>
*/
public class appletComponentResizedH2E extends Applet implements ComponentListener
{
int fullAppletHeight = 400, fullAppletWidth = 400;
int oneRectHeight = (fullAppletHeight/4);
public void init()
{
addComponentListener(this);
}
public void componentHidden(ComponentEvent e)
{
repaint();
}
public void componentMoved(ComponentEvent e)
{
repaint();
}
public void componentResized(ComponentEvent e)
{
fullAppletWidth = e.getComponent().getWidth();
fullAppletHeight = e.getComponent().getHeight();
oneRectHeight = (fullAppletHeight/4);
repaint();
}
public void componentShown(ComponentEvent e)
{
repaint();
}
public void paint(Graphics g)
{
g.setColor(Color.orange);
g.fillRect(0,0,fullAppletWidth,oneRectHeight);
g.setColor(Color.blue);
g.fillRect(0,oneRectHeight,fullAppletWidth,oneRectHeight);
g.setColor(Color.yellow);
g.fillRect(0,(oneRectHeight*2),fullAppletWidth,oneRectHeight);
g.setColor(Color.black);
g.fillRect(0,(oneRectHeight*3),fullAppletWidth,oneRectHeight);
}
}
(a) Write an applet that tracks the position of the mouse when it is dragged or moved. At the current mouse position, it displays message (x, y) showing current position of the mouse. The message should disappear as soon as the user releases the mouse.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="mouseMoveDraggedH2E" width=300 height=300>
</applet>
*/
public class mouseMoveDraggedH2E extends Applet implements MouseListener, MouseMotionListener {
String msg="";
int mouseX=0,mouseY=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
repaint();
}
public void mouseEntered(MouseEvent me)
{
repaint();
}
public void mouseExited(MouseEvent me)
{
repaint();
}
public void mousePressed(MouseEvent me)
{
repaint();
}
public void mouseReleased(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "";
repaint();
}
public void mouseDragged(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "Help2Engg at ("+mouseX+","+mouseY+")";
repaint();
}
public void mouseMoved(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "Help2Engg at ("+mouseX+","+mouseY+")";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,mouseX,mouseY);
}
}

(b) Write a program that counts the no. of words in a text file. The file name is passed as a command line argument. The program should check whether the file exists or not. The words in the file are separated by white space characters.
import java.io.*;
class FileWordCountH2E
{
public static void main(String args[]) throws IOException
{
int ch;
boolean prev=false;
boolean last=false;
int word_count = 0;
int line_count = 0;
FileInputStream h2ein = new FileInputStream(args[0]);
while((ch=h2ein.read())!=-1)
{
last = false;
if(!prev && ch == ' ')
{
++word_count;
last=true;
}
if(ch==' ')
{
prev=true;
last=true;
}
else
prev=false;
if(ch=='\n')
{
++line_count;
last=true;
}
}
word_count += line_count;
if(!last)
++word_count;
System.out.println("No. of Words = "+word_count);
h2ein.close();
}
}

Object Oriented Programming With Java(OOPJ) - June 2011

Question 1

(a) Explain final and super by giving examples.

class H
{
final void show()
{
System.out.println("Final Method. Cant Override");
}
}
final class E extends H
{
//void show()
//{
// Can Not Override Final Method from H
//}
}
//class J extends E
//{
// Can Not Subclass Of E
//}
public class FinalKeywordSimpleExampleH2E
{
public static void main(String args[])
{
H h = new H();
h.show();
}
}
class employee
{
int employee_id;
String employee_name;
employee(int employee_id, String employee_name)
{
this.employee_id = employee_id;
this.employee_name = employee_name;
}
}
class salary extends employee
{
String designation;
double monthly_salary;
salary(int employee_id, String employee_name,String designation,double monthly_salary)
{
super(employee_id,employee_name);
this.designation = designation;
this.monthly_salary = monthly_salary;
}
void show()
{
System.out.println("Employee Details : ");
System.out.println("Id = "+this.employee_id);
System.out.println("Name = "+this.employee_name);
System.out.println("Designation = "+this.designation);
System.out.println("Salary = "+this.monthly_salary);
}
}
class SuperKeywordSimpleEampleH2E
{
public static void main(String args[])
{
salary s = new salary(1,"Shruti Patel","HR Manager",30000);
s.show();
}
}

(b) Declare a class called employee having employee_id and employee_name as members. Extend class employee to have a subclass called salary having designation and monthly_salary as members. Define following:
- Required constructors
- A method to find and display all details of employees drawing salary more than Rs. 20000/-.
- Method main for creating an array for storing these details given as command line arguments and showing usage of above methods.
class employee
{
int employee_id;
String employee_name;
}
class salary extends employee
{
String designation;
double monthly_salary;
salary()
{}
salary(int employee_id,String employee_name,String designation,double monthly_salary)
{
this.employee_id = employee_id;
this.employee_name = employee_name;
this.designation = designation;
this.monthly_salary = monthly_salary;
}
void findDataAbove20000(String arr[][])
{
for(int i=0;i<arr.length;i++)
{
if( (Double.parseDouble(arr[i][3]) ) > 20000 )
{
System.out.println("Employee Details : ");
System.out.println("Id = "+arr[i][0]);
System.out.println("Name = "+arr[i][1]);
System.out.println("Designation = "+arr[i][2]);
System.out.println("Salary = "+arr[i][3]);
}
}
}
}
public class employeeClassExampleInJavaH2E
{
public static void main(String args[])
{
salary s1[] = new salary[4];
String dataArr[][];
s1[0] = new salary(1,"Jaydip-Panchal","Finance-Manager",18000);
s1[1] = new salary(2,"Pratik-Patel","HR-Manager",29000);
s1[2] = new salary(3,"Arpan-Patel","Project-Manager",25000);
s1[3] = new salary();
try
{
s1[3].employee_id = Integer.parseInt(args[0]);
s1[3].employee_name = args[1];
s1[3].designation = args[2];
s1[3].monthly_salary = Double.parseDouble(args[3]);
//System.out.println(args[0]+args[1]+args[2]+args[3]);
}
catch(NumberFormatException e)
{
System.out.println("Exception : "+ e);
}
dataArr = new String[s1.length][4];
for(int i=0;i<s1.length;i++)
{
dataArr[i][0] = String.valueOf(s1[i].employee_id);
dataArr[i][1] = s1[i].employee_name;
dataArr[i][2] = s1[i].designation;
dataArr[i][3] = String.valueOf(s1[i].monthly_salary);
}
s1[3].findDataAbove20000(dataArr);
}
}

Question 2

(a) Explain method overriding and method overloading with the help of examples.

class H2EA
{
int a,b;
H2EA(int i,int j)
{
a=i;
b=j;
}
void inside()
{
System.out.println("Inside H2EA");
}
int Multiplication()
{
return a*b;
}
}
class H2EB extends H2EA
{
int c;
H2EB(int i,int j,int k)
{
super(i,j);
c=k;
}
void inside()
{
System.out.println("Inside H2EB");
}
int Multiplication(int x)
{
return x*c;
}
}
class methodOverloadingAndOverridingDifferenceH2E
{
public static void main(String args[])
{
H2EB Obj = new H2EB(5,6,7);
Obj.inside(); // Method Overriding
System.out.println("Multiplication = "+Obj.Multiplication()); // Method Overloading
System.out.println("Multiplication = "+Obj.Multiplication(8)); // Method Overloading
}
}

(b) Write a method for computing xy by doing repetitive multiplication. x and y are of type integer and are to be given as command line arguments. Raise and handle exception(s) for invalid values of x and y. Also define method main. Use finally in above program and explain its usage.

class powerExampleInJavaH2E
{
public static void main(String args[])
{
int x,y,mul;
try
{
x = Integer.parseInt(args[0]);
y = Integer.parseInt(args[1]);
mul = 1;
for(int i=0;i<y;i++)
mul = mul*x;
System.out.println(x+"^"+y+" : " + mul);
}
catch(NumberFormatException e)
{
System.out.println("Exception : "+e);
}
}
} (b) Explain package and interface by giving examples.

// Package Example class packageExampleImplementH2E
{
public static void main(String args[])
{
int x;
help2engg.packageExampleH2E pe = new help2engg.packageExampleH2E();
pe.show();
pe.setMember(15);
x = pe.getMember();
System.out.println("Member of Inside Package : "+x);
}
}
// The file packageExampleH2E.java must be in help2engg folder package help2engg;
public class packageExampleH2E
{
String msg = "Inside Package Of Help2Engg";
int x;
public void show()
{
System.out.println("Message From Inside Package : "+msg);
}
public void setMember(int x)
{
this.x = x;
}
public int getMember()
{
return x;
}
}

//interface Example interface interfaceClass
{
void interfaceMethod(int p);
}
class interfaceImplement implements interfaceClass
{
public void interfaceMethod(int p1)
{
System.out.println("Interface Class Called with "+p1);
}
public void nonInterfaceMethod(int p1)
{
System.out.println("Interface Implement Class Called with "+p1);
}
}
class interfaceSimpleExampleH2E
{
public static void main(String args[])
{
interfaceImplement IIO = new interfaceImplement();
IIO.interfaceMethod(15);
IIO.nonInterfaceMethod(15);
}
}

Question 3

(a) Explain inner class and working of concatenation operator + by giving examples.
//Inner Class Example class outer
{
int o_x = 52;

void test()
{
Inner inner = new Inner();
inner.show();
}
class Inner
{
void show()
{
System.out.println("Show : X of Outer Class : "+o_x);
}
}
}
class innerClassExampleH2E
{
public static void main(String args[])
{
outer outObj = new outer();
outObj.test();
}
}
//concatenation operator +
public class concatenationOperatorExampleH2E
{
public static void main(String args[])
{
String str1 = "Welcome to : ";
String str2 = "Help2Engg";
System.out.println(str1+str2);
System.out.println("GTU's No.1 Website is : "+str2);
}
}

Question 4
(a) Explain various methods called during execution cycle of the applet.



import java.awt.*;
import java.applet.*;
/*
<applet code="AppletLifeCycle" width=300 height=300>
</applet>
*/
public class AppletLifeCycle extends Applet
{
String msg1,msg2,msg3,msg4;
// called first
public void init()
{
// Initialization
msg1="init section begins";
}
// called second
public void start()
{
// start or resume execution
msg2="start section";
}
// called when applet stopped
public void stop()
{
// suspends execution
msg3="stop section";
}
// called when applet
public void destroy()
{
// execute shutdown activities
msg4="destroy section";
}
public void paint(Graphics g)
{
// redisplay content of window
g.drawString("Demo for basic methods of applet",20,40);
g.drawString(msg1,20,80);
g.drawString(msg2,20,90);
g.drawString(msg3,20,100);
g.drawString(msg4,20,120);
}
}



(b) Write a program to create a frame with exit capabilities. Handle events for mouse pressed, mouse released, mouse clicked and mouse dragged by displaying appropriate message describing the event at the coordinates where the event has taken place.


import java.awt.*;
import java.awt.event.*;
public class HandlingMouseEventWindowEventMouseMotionEventInFramExampleH2E extends Frame
{
String msg = "";
int mouseX=30;
int mouseY=30;
public HandlingMouseEventWindowEventMouseMotionEventInFramExampleH2E()
{
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
addWindowListener(new MyWindowAdapter());
}
public void paint(Graphics g)
{
g.drawString(msg,mouseX,mouseY);
}
public static void main(String[] args)
{
HandlingMouseEventWindowEventMouseMotionEventInFramExampleH2E f = new HandlingMouseEventWindowEventMouseMotionEventInFramExampleH2E();
f.setSize(new Dimension(300,300));
f.setTitle("HandlingMouseEventWindowEventMouseMotionEventInFramExampleH2E");
f.setVisible(true);
}
}
class MyMouseAdapter extends MouseAdapter
{
HandlingMouseEventWindowEventMouseMotionEventInFramExampleH2E f1;
public MyMouseAdapter(HandlingMouseEventWindowEventMouseMotionEventInFramExampleH2E f1)
{
this.f1 = f1;
}
public void mousePressed(MouseEvent me)
{
f1.mouseX = me.getX();
f1.mouseY = me.getY();
f1.msg = "Mouse Down at "+f1.mouseX+","+f1.mouseY;
f1.repaint();
}
public void mouseClicked(MouseEvent me)
{
f1.mouseX = me.getX();
f1.mouseY = me.getY();
f1.msg = "Mouse Clicked at "+f1.mouseX+","+f1.mouseY;
f1.repaint();
}
public void mouseReleased(MouseEvent me)
{
f1.mouseX = me.getX();
f1.mouseY = me.getY();
f1.msg = "Mouse Released at "+f1.mouseX+","+f1.mouseY;
f1.repaint();
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter
{
HandlingMouseEventWindowEventMouseMotionEventInFramExampleH2E f1;
public MyMouseMotionAdapter(HandlingMouseEventWindowEventMouseMotionEventInFramExampleH2E f1)
{
this.f1 = f1;
}
public void mouseDragged(MouseEvent me)
{
f1.mouseX = me.getX();
f1.mouseY = me.getY();
f1.msg = "Mouse Dragged at "+f1.mouseX+","+f1.mouseY;
f1.repaint();
}
}
class MyWindowAdapter extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}



(b) Write a complete program to create a frame for providing GUI to implement a stack for storing integer numbers. There are two buttons called PUSH & POP and a text field. Clicking of button PUSH pushes the number entered in the text field onto the stack. The click of button POP pops an element from the stack and displays that in the text field.


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class stackUsingJFrameInJavaPushPopExampleH2E
{
JLabel lbl;
JButton pop,push;
JTextField text;
String stackArr[] = new String[10];
int top=-1;
CopyOfstackUsingJFrameInJavaPushPopExampleH2E()
{
JFrame frm = new JFrame("Stack Implementation In Frame - Help2Engg");
frm.setLayout(new FlowLayout());
frm.setSize(300,300);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
push = new JButton("PUSH");
pop = new JButton("POP");
text = new JTextField(12);
push.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
++top;
if(top < 10)
{
stackArr[top] = text.getText();
lbl.setText("Push Element : "+text.getText());
}
else
lbl.setText("Stack is Full");
}
}
);
pop.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if(top >= 0)
{
lbl.setText("Pop Element : "+stackArr[top]);
--top;
}
else
lbl.setText("Stack is Empty");
}
}
);
frm.add(text);
frm.add(push);
frm.add(pop);
lbl = new JLabel("Press a Button");
frm.add(lbl);
frm.setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CopyOfstackUsingJFrameInJavaPushPopExampleH2E();
}
}
);
}
}

Question 5
(a) It is required to have total two threads, both capable of acting as a produce as well as a consumer. If first thread acts as a producer then, the second thread becomes the consumer and vice-versa. They communicate with each other through a buffer, storing one integer number. One of the threads initiates the communication by sending 1 to the other thread. The second thread, on receiving 1 sends 2 to the first thread. On receiving 2, the first thread sends three integer numbers, one by one to the second thread. The second thread consumes the numbers by displaying them. Both threads terminate after that. Note that both threads must be capable of initiating the communication. Write complete multi-threaded program to meet above requirements.

class CI

{
int n;
boolean valueSet = false;
synchronized int recieve()
{
while(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Recieve : " + n);
valueSet = false;
notify();
return n;
}
synchronized void send(int n)
{
while(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Send : "+n);
notify();
}
}
class Producer implements Runnable
{
CI ci;
Producer(CI ci)
{
this.ci = ci;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
{
ci.send(i++);
}
}
}
class Consumer implements Runnable
{
CI ci;
Consumer(CI ci)
{
this.ci = ci;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
ci.recieve();
}
}
}
class multithreadedProgramProducerConsumerExampleH2E
{
public static void main(String args[])
{
CI ci = new CI();
new Producer(ci);
new Consumer(ci);
System.out.println("Press Control-C to Stop.");
}
}
(b) Explain utility class Hashtable and instanceof operator by giving examples.
// utility class Hashtable Example import java.io.*;
import java.util.*;
class utilityClassHashtableExampleH2E
{
public static void main(String args[]) throws IOException
{
Hashtable<String,Integer> ht = new Hashtable<String,Integer>();
ht.put("Jaydip",88);
ht.put("Arpan",89);
ht.put("Praik",90);
System.out.println("The Students names : ");
Enumeration e = ht.keys();
while(e.hasMoreElements())
System.out.println(e.nextElement());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Student Name : ");
String name = br.readLine();
name = name.trim();
Integer mark = ht.get(name);
if(mark != null)
{
int mv = mark.intValue();
System.out.println(name + " mark : "+mv);
}
else
System.out.println("Student Not Found");
}
}
// Instanceof Operator Example class A
{
int i,j;
}
class B
{
int i,j;
}
class C extends A
{
int k;
}
class D extends A
{
int k;
}
class instanceofOperatorExampleH2E
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
D d = new D();
if(a instanceof A)
System.out.println("a is instance of A");
if(b instanceof B)
System.out.println("b is instance of B");
if(c instanceof C)
System.out.println("c is instance of C");
if(d instanceof D)
System.out.println("d is instance of D");
System.out.println();
A ob;
ob = d;
System.out.println("ob is now refers to d");
System.out.println();
if(ob instanceof D)
System.out.println("ob is instance of D");
ob = c;
System.out.println();
System.out.println("ob is now refers to C");
System.out.println();
if(ob instanceof D)
System.out.println("ob can cast to D");
else
System.out.println("ob can not cast to D");
}
}