You are on page 1of 35

2.

(a)

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Scanner;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;

/**
*
*/

/**
* @author siva
*
*/
public class Employee {

private static Scanner input;


/**
* @param args
*/
public static Connection getDBConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=(Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/sample_db","root","siva");

return con;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;

}
public static int updateEmployee() {
String id,name;
System.out.println("Enter ID : ");
id=input.nextLine();
System.out.println("Enter New name : ");
name=input.nextLine();
Connection con=Employee.getDBConnection();
PreparedStatement ps;
try {
ps = (PreparedStatement) con.prepareStatement("update employee set name =
? where id = ?");
ps.setString(1, name);
ps.setString(2, id);
int result=ps.executeUpdate();
if(result > 0)
return 1;
else

return 0;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 1;

}
public static int insertEmployee() {
String id,name,address,phone,email;
System.out.println("Enter ID : ");
id=input.nextLine();
System.out.println("Enter Name : ");
name=input.nextLine();
System.out.println("Enter Address : ");
address=input.nextLine();
System.out.println("Enter Phone Number : ");
phone=input.nextLine();
System.out.println("Enter Email ID : ");
email=input.nextLine();
Connection con=Employee.getDBConnection();
PreparedStatement ps;
try {
ps = (PreparedStatement) con.prepareStatement("insert into employee
values(?,?,?,?,?)");
ps.setString(1, id);
ps.setString(2, name);
ps.setString(3, address);
ps.setString(4, phone);

ps.setString(5, email);
int result=ps.executeUpdate();
if(result > 0)
return 1;
else
return 0;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return 0;

}
public static void displayEmployee() {
Connection con=Employee.getDBConnection();
PreparedStatement ps;
try {
ps = (PreparedStatement) con.prepareStatement("select * from employee");
ResultSet rs=(ResultSet) ps.executeQuery();
while(rs.next())
{
System.out.println("ID : "+rs.getString(1)+"\tName :
"+rs.getString(2)+"\tAddress : "+rs.getString(3)+"\tPhone : "+rs.getString(4)+"\tEmail : "+rs.getString(5));
System.out.println();
}

} catch (SQLException e) {
// TODO Auto-generated catch block

e.printStackTrace();
}

}
public static void main(String[] args) {
input = new Scanner(System.in);
int choice,result;
do
{
System.out.println("1.Insert\n2.Update\n3.Display\n4.Exit\nEnter your choice :
");
choice=input.nextInt();
input.nextLine();
switch(choice)
{
case 1: result=Employee.insertEmployee();
if(result==1)
System.out.println("Employee Inserted
Successfully..!!");
else
System.out.println("Employee Not Inserted..!!");
break;
case 2: result=Employee.updateEmployee();
if(result==1)
System.out.println("Employee Details Updated
Successfully..!!");
else
System.out.println("Employee Detail not Updated..");
break;
case 3: Employee.displayEmployee();

break;
case 4: System.exit(0);
break;

}
}while(choice!=4);

Note :
All the JDBC related programs are similar to the above program.
Refer the above program for JDBC connection and Database retrival.
The connection string alone varies depends on the databases like mysql,oracle etc..
1.b
Get the input string.
Convert into array by using toCharArray() method.
Extend the class Stack.
Insert the characters into the stack by using push() method.
Then pop the characters from the stack and store it in the char array.
Compare the strings , if it is equal then it is palindrome.
2.b
Get the input string.
Get the input word.
Using charAt() method find the 1st occurrence of the word in the string by continuously checking
through the looping constructs.
3.b
Use the same code as used in 2.b and by using the temporary count variable count the occurrences.

For Encryption ,Decryption related programs


Convert the string into character array by using toCharArray().
Then convert the charcter into ascii values by typecasting.
For decryption,
Do the reverse process above procedure.
7.b
For GP series,
Use the following formula,

Sum= a (

Where,
a first term
r common ratio
n number of elements.
8.b
Create the thread either by extending Thread class or by implementing Runnable interface.
To set the priority level use the method called setPriority(arg)
Where arg MAX_PRIORITY or NORM_PRIORITY or MIN_PRIORITY
To get the priority of the thread use the method called getPriority().
9.b
Get the array of N elements.
Sort the elements by using Array.sort() method or Collections.sort() method.
5.b

import java.util.Scanner;
/**
*

*/
/**
* @authorsiva
*
*/
publicclass Main {
/**
* @param args
*/
privateintid;
private String name;
privatestatic Scanner input;
/**
* @return the id
*/
publicint getId() {
returnid;
}
/**
* @param id the id to set
*/
publicvoid setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
returnname;
}
/**
* @param name the name to set
*/
publicvoid setName(String name) {
this.name = name;
}
publicstaticvoid main(String[] args) {
input = new Scanner(System.in);
System.out.println("Enter the Employee ID : ");
int id=input.nextInt();
input.nextLine();
System.out.println();
String name=input.nextLine();
Main emp=new Main();
//hiding
emp.setId(id);
emp.setName(name);
//accessing hided data
System.out.println("Employee ID : "+emp.getId());
System.out.println("Enter Name : "+emp.getName());

}
}

6.b

import java.util.Scanner;
/**
*
*/
/**
* @authorsiva
*
*/
publicclass Main {
privatestatic Scanner input;
/**
* @param args
*/
publicstaticint[][] addMatrix(int[][] a,int[][] b) {
int[][] c=newint[3][3];
int loop1,loop2;
for(loop1=0;loop1<3;loop1++)
{
for(loop2=0;loop2<3;loop2++)
{
c[loop1][loop2]=a[loop1][loop2]+b[loop1][loop2];
}
}
return c;
}
publicstaticvoid main(String[] args) {
input = new Scanner(System.in);
int[][] a=newint[3][3];
int[][] b=newint[3][3];
int[][] c=newint[3][3];
System.out.println("Enter the elements of the first matrix..");
int loop1,loop2;
for(loop1=0;loop1<3;loop1++)
{
for(loop2=0;loop2<3;loop2++)
{
a[loop1][loop2]=input.nextInt();
}
}
System.out.println("Enter the elements of the second matrix..");
for(loop1=0;loop1<3;loop1++)

{
for(loop2=0;loop2<3;loop2++)
{
b[loop1][loop2]=input.nextInt();
}
}
c=Main.addMatrix(a, b);
System.out.println("Resultant Matrix..");
for(loop1=0;loop1<3;loop1++)
{
for(loop2=0;loop2<3;loop2++)
{
System.out.print(c[loop1][loop2]+"\t");
}
System.out.println();
}
}
}

11.a

import java.util.Scanner;
/**
*
*/
/**
* @authorsiva
*
*/
publicclass Main {
intkilometer;
intmeter;
privatestatic Scanner input;
/**
* @param args
*/
public Main(int kilometer, int meter) {
super();
this.kilometer = kilometer;
this.meter = meter;
}
public Main() {
// TODO Auto-generated constructor stub
}
/**

* @return the kilometer


*/
publicint getKilometer() {
returnkilometer;
}
/**
* @param kilometer the kilometer to set
*/
publicvoid setKilometer(int kilometer) {
this.kilometer = kilometer;
}
/**
* @return the meter
*/
publicint getMeter() {
returnmeter;
}
/**
* @param meter the meter to set
*/
publicvoid setMeter(int meter) {
this.meter = meter;
}
publicstatic Main addDistance(Main d1,Main d2) {
Main d3=new Main();
int meter=0;
meter=d1.getMeter()+d2.getMeter();
int km=0;
if(meter>=1000)
{
km+=1;
meter-=1000;
}
d3.setKilometer(d1.getKilometer()+d2.getKilometer()+km);
d3.setMeter(meter);
return d3;
}
publicstatic Main subDistance(Main d1,Main d2) {
Main d4=new Main();
int meter=d1.getMeter()-d2.getMeter();
int km=d1.getKilometer()-d2.getKilometer();
if(meter<0)
{
km-=1;
meter=(d1.getMeter()+1000)-d2.getMeter();
}
d4.setKilometer(km);
d4.setMeter(meter);
return d4;

}
publicstaticvoid main(String[] args) {
input = new Scanner(System.in);
int km,meter;
System.out.println("Enter Distance 1");
System.out.println("Enter Kilometer : ");
km=input.nextInt();
System.out.println("Enter Meter : ");
meter=input.nextInt();
Main d1=new Main(km, meter);
System.out.println("Enter Distance 2");
System.out.println("Enter Kilometer : ");
km=input.nextInt();
System.out.println("Enter Meter : ");
meter=input.nextInt();
Main d2=new Main(km, meter);
Main d3=new Main();
Main d4=new Main();
d3=Main.addDistance(d1, d2);
d4=Main.subDistance(d1, d2);
System.out.println("Addition Result\nKilometer :
"+d3.getKilometer()+"\nMeter : "+d3.getMeter());
System.out.println("Subtraction Result\nKilometer :
"+d4.getKilometer()+"\nMeter : "+d4.getMeter());
}
}

20.b)Write a program to handle events for a calculator with the following buttons i)add
ii)subtract iii)multiply.
21.a.Calculator Application using Swing/Applet

import java.awt.*;
import java.awt.event.*;
// class CalcFrame for creating a calculator frame and added windolistener to
// close the calculator
class CalcFrame extends Frame {
CalcFrame( String str) {
// call to superclass
super(str);
// to close the calculator(Frame)
addWindowListener(new WindowAdapter() {
public void windowClosing (WindowEvent we) {
System.exit(0);
}
});
}

}
// main class Calculator implemnets two
// interfaces ActionListener
// and ItemListener
public class Calculator implements ActionListener, ItemListener {
// creating instances of objects
CalcFrame fr;
TextField display;
Button key[] = new Button[20]; // creates a button object array of 20
Button clearAll, clearEntry, round;
Button scientificKey[] = new Button[10]; // creates a button array of 8
// declaring variables
boolean addButtonPressed, subtractButtonPressed, multiplyButtonPressed;
boolean divideButtonPressed, decimalPointPressed, powerButtonPressed;
boolean roundButtonPressed = false;
double initialNumber;// the first number for the two number operation
double currentNumber = 0; // the number shown in the screen while it is being
pressed
int decimalPlaces = 0;
// main function
public static void main (String args[]) {
// constructor
Calculator calc = new Calculator();
calc.makeCalculator();
}
public void makeCalculator() {
// size of the button
final int BWIDTH = 25;
final int BHEIGHT = 25;
int count =1;
// create frame for the calculator
fr = new CalcFrame("Scientific Calculator");
// set the size
fr.setSize(300,350);
fr.setBackground(Color.blue);;
fr.setLayout(null);
// set the initial numbers that is 1 to 9
for (int row = 0; row < 3; ++row) {
for (int col = 0; col < 3; ++col) {
// this will set the key from 1 to 9

key[count] = new Button(Integer.toString(count));


key[count].addActionListener(this);
// set the boundry for the keys
key[count].setBounds(30*(col + 1), 30*(row + 4),BWIDTH,BHEIGHT);
key[count].setBackground(Color.yellow);
// add to the frame
fr.add(key[count++]);
}
}
// Now create, addlistener and add to frame all other keys
//0
key[0] = new Button("0");
key[0].addActionListener(this);
key[0].setBounds(30,210,BWIDTH,BHEIGHT);
key[0].setBackground(Color.yellow);
fr.add(key[0]);
//decimal
key[10] = new Button(".");
key[10].addActionListener(this);
key[10].setBounds(60,210,BWIDTH,BHEIGHT);
key[10].setBackground(Color.yellow);
fr.add(key[10]);
//equals to
key[11] = new Button("=");
key[11].addActionListener(this);
key[11].setBounds(90,210,BWIDTH,BHEIGHT);
key[11].setBackground(Color.yellow);
fr.add(key[11]);
//multiply
key[12] = new Button("*");
key[12].addActionListener(this);
key[12].setBounds(120,120,BWIDTH,BHEIGHT);
key[12].setBackground(Color.yellow);
fr.add(key[12]);
//divide
key[13] = new Button("/");
key[13].addActionListener(this);
key[13].setBounds(120,150,BWIDTH,BHEIGHT);
key[13].setBackground(Color.yellow);
fr.add(key[13]);

//addition
key[14] = new Button("+");
key[14].addActionListener(this);
key[14].setBounds(120,180,BWIDTH,BHEIGHT);
key[14].setBackground(Color.yellow);
fr.add(key[14]);
//subtract
key[15] = new Button("-");
key[15].addActionListener(this);
key[15].setBounds(120,210,BWIDTH,BHEIGHT);
key[15].setBackground(Color.yellow);
fr.add(key[15]);
//reciprocal
key[16] = new Button("1/x");
key[16].addActionListener(this);
key[16].setBounds(150,120,BWIDTH,BHEIGHT);
key[16].setBackground(Color.yellow);
fr.add(key[16]);
//power
key[17] = new Button("x^n");
key[17].addActionListener(this);
key[17].setBounds(150,150,BWIDTH,BHEIGHT);
key[17].setBackground(Color.yellow);
fr.add(key[17]);
//change sign
key[18] = new Button("+/-");
key[18].addActionListener(this);
key[18].setBounds(150,180,BWIDTH,BHEIGHT);
key[18].setBackground(Color.yellow);
fr.add(key[18]);
//factorial
key[19] = new Button("x!");
key[19].addActionListener(this);
key[19].setBounds(150,210,BWIDTH,BHEIGHT);
key[19].setBackground(Color.yellow);
fr.add(key[19]);
// CA
clearAll = new Button("CA");
clearAll.addActionListener(this);
clearAll.setBounds(30, 240, BWIDTH+20, BHEIGHT);

clearAll.setBackground(Color.yellow);
fr.add(clearAll);
// CE
clearEntry = new Button("CE");
clearEntry.addActionListener(this);
clearEntry.setBounds(80, 240, BWIDTH+20, BHEIGHT);
clearEntry.setBackground(Color.yellow);
fr.add(clearEntry);
// round
round = new Button("Round");
round.addActionListener(this);
round.setBounds(130, 240, BWIDTH+20, BHEIGHT);
round.setBackground(Color.yellow);
fr.add(round);
// set display area
display = new TextField("0");
display.setBounds(30,90,150,20);
display.setBackground(Color.white);
// key for scientific calculator
// Sine
scientificKey[0] = new Button("Sin");
scientificKey[0].addActionListener(this);
scientificKey[0].setBounds(180, 120, BWIDTH + 10, BHEIGHT);
scientificKey[0].setVisible(true);
scientificKey[0].setBackground(Color.yellow);
fr.add(scientificKey[0]);
// cosine
scientificKey[1] = new Button("Cos");
scientificKey[1].addActionListener(this);
scientificKey[1].setBounds(180, 150, BWIDTH + 10, BHEIGHT);
scientificKey[1].setBackground(Color.yellow);
scientificKey[1].setVisible(true);
fr.add(scientificKey[1]);
// Tan
scientificKey[2] = new Button("Tan");
scientificKey[2].addActionListener(this);
scientificKey[2].setBounds(180, 180, BWIDTH + 10, BHEIGHT);
scientificKey[2].setBackground(Color.yellow);
scientificKey[2].setVisible(true);
fr.add(scientificKey[2]);

// PI
scientificKey[3] = new Button("Pi");
scientificKey[3].addActionListener(this);
scientificKey[3].setBounds(180, 210, BWIDTH + 10, BHEIGHT);
scientificKey[3].setBackground(Color.yellow);
scientificKey[3].setVisible(true);
fr.add(scientificKey[3]);
// aSine
scientificKey[4] = new Button("aSin");
scientificKey[4].addActionListener(this);
scientificKey[4].setBounds(220, 120, BWIDTH + 10, BHEIGHT);
scientificKey[4].setBackground(Color.yellow);
scientificKey[4].setVisible(true);
fr.add(scientificKey[4]);
// aCos
scientificKey[5] = new Button("aCos");
scientificKey[5].addActionListener(this);
scientificKey[5].setBounds(220, 150, BWIDTH + 10, BHEIGHT);
scientificKey[5].setBackground(Color.yellow);
scientificKey[5].setVisible(true);
fr.add(scientificKey[5]);
// aTan
scientificKey[6] = new Button("aTan");
scientificKey[6].addActionListener(this);
scientificKey[6].setBounds(220, 180, BWIDTH + 10, BHEIGHT);
scientificKey[6].setBackground(Color.yellow);
scientificKey[6].setVisible(true);
fr.add(scientificKey[6]);
// E
scientificKey[7] = new Button("E");
scientificKey[7].addActionListener(this);
scientificKey[7].setBounds(220, 210, BWIDTH + 10, BHEIGHT);
scientificKey[7].setBackground(Color.yellow);
scientificKey[7].setVisible(true);
fr.add(scientificKey[7]);
// to degrees
scientificKey[8] = new Button("todeg");
scientificKey[8].addActionListener(this);
scientificKey[8].setBounds(180, 240, BWIDTH + 10, BHEIGHT);
scientificKey[8].setBackground(Color.yellow);

scientificKey[8].setVisible(true);
fr.add(scientificKey[8]);
// to radians
scientificKey[9] = new Button("torad");
scientificKey[9].addActionListener(this);
scientificKey[9].setBounds(220, 240, BWIDTH + 10, BHEIGHT);
scientificKey[9].setBackground(Color.yellow);
scientificKey[9].setVisible(true);
fr.add(scientificKey[9]);
fr.add(display);
fr.setVisible(true);
} // end of makeCalculator
public void actionPerformed(ActionEvent ae) {
String buttonText = ae.getActionCommand();
double displayNumber = Double.valueOf(display.getText()).doubleValue();
// if the button pressed text is 0 to 9
if((buttonText.charAt(0) >= '0') & (buttonText.charAt(0) <= '9')) {
if(decimalPointPressed) {
for (int i=1;i <=decimalPlaces; ++i)
currentNumber *= 10;
currentNumber +=(int)buttonText.charAt(0)- (int)'0';
for (int i=1;i <=decimalPlaces; ++i) {
currentNumber /=10;
}
++decimalPlaces;
display.setText(Double.toString(currentNumber));
}
else if (roundButtonPressed) {
int decPlaces = (int)buttonText.charAt(0) - (int)'0';
for (int i=0; i< decPlaces; ++i)
displayNumber *=10;
displayNumber = Math.round(displayNumber);
for (int i = 0; i < decPlaces; ++i) {
displayNumber /=10;
}
display.setText(Double.toString(displayNumber));
roundButtonPressed = false;
}
else {
currentNumber = currentNumber * 10 + (int)buttonText.charAt(0)-(int)'0';

display.setText(Integer.toString((int)currentNumber));
}
}
// if button pressed is addition
if(buttonText == "+") {
addButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
// if button pressed is subtract
if (buttonText == "-") {
subtractButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
// if button pressed is divide
if (buttonText == "/") {
divideButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
// if button pressed is multiply
if (buttonText == "*") {
multiplyButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
// if button pressed is reciprocal
if (buttonText == "1/x") {
// call reciprocal method
display.setText(reciprocal(displayNumber));
currentNumber = 0;
decimalPointPressed = false;
}
// if button is pressed to change a sign
//

if (buttonText == "+/-") {
// call changesign meyhod to change the
// sign
display.setText(changeSign(displayNumber));
currentNumber = 0;
decimalPointPressed = false;
}
// factorial button
if (buttonText == "x!") {
display.setText(factorial(displayNumber));
currentNumber = 0;
decimalPointPressed = false;
}
// power button
if (buttonText == "x^n") {
powerButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
// now for scientific buttons
if (buttonText == "Sin") {
display.setText(Double.toString(Math.sin(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;
}
if (buttonText == "Cos") {
display.setText(Double.toString(Math.cos(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;
}
if (buttonText == "Tan") {
display.setText(Double.toString(Math.tan(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;
}
if (buttonText == "aSin") {
display.setText(Double.toString(Math.asin(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;

}
if (buttonText == "aCos") {
display.setText(Double.toString(Math.acos(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;
}
if (buttonText == "aTan") {
display.setText(Double.toString(Math.atan(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;
}
// this will convert the numbers displayed to degrees
if (buttonText == "todeg")
display.setText(Double.toString(Math.toDegrees(displayNumber)));
// this will convert the numbers display
// ed to radians
if (buttonText == "torad")
display.setText(Double.toString(Math.toRadians(displayNumber)));
if (buttonText == "Pi") {
display.setText(Double.toString(Math.PI));
currentNumber =0;
decimalPointPressed = false;
}
if (buttonText == "Round")
roundButtonPressed = true;
// check if decimal point is pressed
if (buttonText == ".") {
String displayedNumber = display.getText();
boolean decimalPointFound = false;
int i;
decimalPointPressed = true;
// check for decimal point
for (i =0; i < displayedNumber.length(); ++i) {
if(displayedNumber.charAt(i) == '.') {
decimalPointFound = true;
continue;
}
}
if (!decimalPointFound)
decimalPlaces = 1;

}
if(buttonText == "CA"){
// set all buttons to false
resetAllButtons();
display.setText("0");
currentNumber = 0;
}
if (buttonText == "CE") {
display.setText("0");
currentNumber = 0;
decimalPointPressed = false;
}
if (buttonText == "E") {
display.setText(Double.toString(Math.E));
currentNumber = 0;
decimalPointPressed = false;
}
// the main action
if (buttonText == "=") {
currentNumber = 0;
// if add button is pressed
if(addButtonPressed)
display.setText(Double.toString(initialNumber + displayNumber));
// if subtract button is pressed
if(subtractButtonPressed)
display.setText(Double.toString(initialNumber - displayNumber));
// if divide button is pressed
if (divideButtonPressed) {
// check if the divisor is zero
if(displayNumber == 0) {
MessageBox mb = new MessageBox ( fr, "Error ", true, "Cannot divide by zero.");
mb.show();
}
else
display.setText(Double.toString(initialNumber/displayNumber));
}
// if multiply button is pressed
if(multiplyButtonPressed)
display.setText(Double.toString(initialNumber * displayNumber));
// if power button is pressed

if (powerButtonPressed)
display.setText(power(initialNumber, displayNumber));
// set all the buttons to false
resetAllButtons();
}
} // end of action events
public void itemStateChanged(ItemEvent ie)
{
} // end of itemState
// this method will reset all the button
// Pressed property to false
public void resetAllButtons() {
addButtonPressed = false;
subtractButtonPressed = false;
multiplyButtonPressed = false;
divideButtonPressed = false;
decimalPointPressed = false;
powerButtonPressed = false;
roundButtonPressed = false;
}
public String factorial(double num) {
int theNum = (int)num;
if (theNum < 1) {
MessageBox mb = new MessageBox (fr, "Facorial Error", true,
"Cannot find the factorial of numbers less than 1.");
mb.show();
return ("0");
}
else {
for (int i=(theNum -1); i > 1; --i)
theNum *= i;
return Integer.toString(theNum);
}
}
public String reciprocal(double num) {
if (num ==0) {
MessageBox mb = new MessageBox(fr,"Reciprocal Error", true,
"Cannot find the reciprocal of 0");
mb.show();
}

else
num = 1/num;
return Double.toString(num);
}
public String power (double base, double index) {
return Double.toString(Math.pow(base, index));
}
public String changeSign(double num) {
return Double.toString(-num);
}
}
class MessageBox extends Dialog implements ActionListener {
Button ok;
MessageBox(Frame f, String title, boolean mode, String message) {
super(f, title, mode);
Panel centrePanel = new Panel();
Label lbl = new Label(message);
centrePanel.add(lbl);
add(centrePanel, "Center");
Panel southPanel = new Panel();
ok = new Button ("OK");
ok.addActionListener(this);
southPanel.add(ok);
add(southPanel, "South");
pack();
addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent we) {
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae) {
dispose();
}
}
21.b.Implementation of Vehicle class using Abstract class and Interface

interface Vehicle {
public void color();

public void wheels();


public void speed();
public void seats();
public void breake();
}

class Car implements Vehicle{


car ()
{
System.out.println("Enter the details of car");
System.out.println("Enter the color");
String color =sc.next();
System.out.println("Enter the maximum speed");
int speed=sc.nextInt();
System.out.println("Enter the number of seats");
int seats =sc.nextInt();
System.out.println("Enter the number of wheels");
int wheels =sc.nextInt();
System.out.println("Enter the status of AC(true/false)");
String ac =sc.nextInt();
}

public void Color(){


System.out.println("Color : "+color);
}

public void speed(){

System.out.println("Maximum Speed : "+speed);


}

public void seats(){


System.out.println("Number of Seats : "+seats);
}
public void wheels(){
System.out.println("Number of Wheels : "+wheels);
}
public void breake(){
System.out.println("Disk Break : "+break);
}
}

class Bike extends Car {


car ()
{
System.out.println("Enter the details of bike");
System.out.println("Enter the color");
String color =sc.next();
System.out.println("Enter the maximum speed");
int speed=sc.nextInt();
System.out.println("Enter the number of seats");
int seats =sc.nextInt();
System.out.println("Enter the number of wheels");
int seats =sc.nextInt();
System.out.println("Enter the status of diskbreak(true/false)");

String seats =sc.nextInt();


}

public void Color(){


System.out.println("Color : "+color);
}

public void speed(){


System.out.println("Maximum Speed : "+speed);
}

public void seats(){


System.out.println("Number of Seats : "+seats);
}
public void wheels(){
System.out.println("Number of Wheels : "+wheels);
}
public void breake(){
System.out.println("Ac: "+ac);
}
}

public class Main {


public static void main(String[] args) {
Vehicle v1= new Car();
Vehicle v2= new Bike();
System.out.println("Car Details:");

v1.color();
v1.doors();
v1.seats();
v1.wheels();
v1.breake();
System.out.println("Bike Details:");
v2.color();
v2.doors();
v2.seats();
v2.wheels();
v2.ac();
}
}
19. Design a java interface for ADT queue. Develop classes that implement this interface using
array and linked list. Throw exception if the Queue is empty().
import java.util.*;
publicclass Main implementsQueue {
publicstaticvoid main(String[] args) {
LinkedList<String> ll=new LinkedList <String>();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the maximum size of queue");
int stacksize=sc.nextInt();
if(stacksize<0){
System.out.println("Error : Underflow Exception");
} else {
int currentStackSize=0;
int iChoice;
String iNum;
do{
System.out.println("Linked Queue Operations");
System.out.println("1.INSERT\n2.REMOVE\n3.Display\n4.Exit\nEnter the
option");
System.out.println("");
System.out.println("");
iChoice=sc.nextInt();
switch(iChoice)
{
case 1:
if(currentStackSize!=stacksize){
currentStackSize++;
System.out.println("Enter integer element to push");
ll.add(sc.next());

} else {
System.out.println(" OverFlow");
} break;
case 2:
if(currentStackSize!=0){
System.out.println("Popped Element = "+ll.removeFirst());
ll.removeFirst();
currentStackSize--;
} else {
System.out.println("Stack = Empty");
} break;
case 3:
if(currentStackSize!=0){
Collections.reverse(ll);
System.out.println("Elements in the stack are");
for(String i:ll)
System.out.print(i+" ");
Collections.reverse(ll);
}else {
System.out.println("Stack = Empty");
} break;
}
}while(iChoice<=3);
}
}
@Override
publicboolean addAll(Collection arg0) {
// TODO Auto-generated method stub
returnfalse;
}
@Override
publicvoid clear() {
// TODO Auto-generated method stub
}
@Override
publicboolean contains(Object arg0) {
// TODO Auto-generated method stub
returnfalse;
}
@Override
publicboolean containsAll(Collection arg0) {
// TODO Auto-generated method stub
returnfalse;
}
@Override
publicboolean isEmpty() {
// TODO Auto-generated method stub
returnfalse;
}
@Override

publicIterator iterator() {
// TODO Auto-generated method stub
returnnull;
}
@Override
publicboolean remove(Object arg0) {
// TODO Auto-generated method stub
returnfalse;
}
@Override
publicboolean removeAll(Collection arg0) {
// TODO Auto-generated method stub
returnfalse;
}
@Override
publicboolean retainAll(Collection arg0) {
// TODO Auto-generated method stub
returnfalse;
}
@Override
publicint size() {
// TODO Auto-generated method stub
return 0;
}
@Override
public Object[] toArray() {
// TODO Auto-generated method stub
returnnull;
}
@Override
public Object[] toArray(Object[] arg0) {
// TODO Auto-generated method stub
returnnull;
}
@Override
publicboolean add(Object arg0) {
// TODO Auto-generated method stub
returnfalse;
}
@Override
public Object element() {
// TODO Auto-generated method stub
returnnull;
}
@Override
publicboolean offer(Object arg0) {
// TODO Auto-generated method stub
returnfalse;

}
@Override
public Object peek() {
// TODO Auto-generated method stub
returnnull;
}
@Override
public Object poll() {
// TODO Auto-generated method stub
returnnull;
}
@Override
public Object remove() {
// TODO Auto-generated method stub
returnnull;
}
}

15.b) Write a program to change the color of the ball when the user clicks the ball using
mouse.
NOTE:This program I am using Button above program we must use circle

import
import
import
import
import
import

java.awt.Color;
java.awt.Container;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.awt.event.WindowAdapter;
java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonSettingBackground extends JPanel imple
ments ActionListener {
private JButton yellowButton = new JButton("Yellow");
private JButton blueButton = new JButton("Blue");
private JButton redButton = new JButton("Red");
public ButtonSettingBackground() {

add(yellowButton);
add(blueButton);
add(redButton);
yellowButton.addActionListener(this);
blueButton.addActionListener(this);
redButton.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
Color color = getBackground();
if (source == yellowButton)
color = Color.yellow;
else if (source == blueButton)
color = Color.blue;
else if (source == redButton)
color = Color.red;
setBackground(color);
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("ButtonTest");
frame.setSize(300, 200);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(new ButtonSettingBackground());
frame.show();
}
}
18b)Write a java program to change the shapes of the object by pressing the button
importjava.awt.BorderLayout;

import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
importjava.awt.event.MouseAdapter;
importjava.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
publicclass DisposeShape{
booleandrawRectangle = false;
booleandrawCircle = false;
booleandrawSquare = false;
JLabel label = new JLabel();
JButton addRectangle;
JButton addSquare;
JButton addCircle;
Rectangle rectangle;
Graphics2D g2;
JPanel panel = new JPanel();
publicvoid paintComponent(Graphics g)
{
//super.paintComponent(g);
myPaint(g);
}
publicvoid myPaint(Graphics g)
{
if (drawRectangle)
{
g.drawRect(10,10,100,100);
}
if (drawCircle)
{
g.drawOval(10,10, 100, 100);
}
if (drawSquare)
{
}
}
public DisposeShape()
{
JFrame frame = new JFrame("Dispose shapes");
addRectangle = new JButton("Add Rectangle");
addRectangle.setSize(50, 100);

addRectangle.addActionListener(new ButtonListener());
addSquare = new JButton("Add Square");
addSquare.setSize(50,100);
addSquare.addActionListener(new ButtonListener());
addCircle = new JButton("Add Circle");
addCircle.setSize(50,100);
addCircle.addActionListener(new ButtonListener());
panel.setLayout(new FlowLayout());
panel.add(addRectangle);
panel.add(addSquare);
panel.add(addCircle);
panel.add(label);
frame.getContentPane().add(panel);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
}
publicclass ButtonListener implements ActionListener
{
publicvoid actionPerformed(ActionEvent e)
{
if(e.getSource() == addRectangle)
{
drawRectangle = true;
}
elseif (e.getSource() == addSquare)
{
}
elseif(e.getSource() == addCircle)
{
}
}
}
publicstaticvoid main(String[] args)
{
DisposeShape disposeShapes = new DisposeShape();
}
}

17b) Write a program that creates the button , label (to display greeting) and listener class for
a button that displays one of 10 randomly selected greetings.

Note: similar to the 18.b to create button,lable,and set


actionlistener.
----------------------------------------------------=-

-18. a)Design a Shape class hierarchy and write a test program to demonstrate polymorphism-----Note: Its similar to 18.b,but we use two other class
that extends same class check the polymorphism concept in
java lab record
-ite -------------------------------------------------16.16. b) Write a java program to simulate server-client communication using threads.
Note-Note: you check the CN lab 1st experiment and add the
thread concept also.
-12.b.Write a program to display text with 3 different colors and styles
Note :Refer the page number 390.you can cheack with output also.
5a.Write a program to merge two files in to a third file.
8a)Write a program to read a file and to edit the record of a particular student
9. a)Write a program to write the student record in to a file and to delete the record of a
particular student.
Note: Using FileInputStream and FileOutputStream we can read and write the file.
File CREATION: File obj=new File(filename.txt);
Obj.createNewFile();
File INPUT:FileInputStream fis=new FileInputStream(obj);
File OUTPUT:FileOutputStream fos=new FileOutputStream(obj);
13. Use Inheritance concepts.o

You might also like