You are on page 1of 52

Q. 01 WAP to print Fibonacci Series.

class Fibo
{
public static void main(String args[])
{
int a=0,b=1,c=0,i=1;
System.out.print( a + " , " + b + " , ");
do
{
c=a+b;
System.out.print(c + " , ");
a=b;
b=c;
i++;
} while (i<=8);
}
}

OUTPUT :-
Q. 02 WAP to check that the given string is palindrome or not.

import java.io.*;
class PalinString
{
public static void main (String args[]) throws IOException

{
BufferedReader br = new BufferedReader (new InputStreamReader
(System.in));
System.out.println ("enter the String:");
String str = br.readLine ();
String temp = str;
StringBuffer sb = new StringBuffer (str);
sb.reverse ();
str = sb.toString ();
if (temp.equals(str))
System.out.println (temp + " is palindrome");
else
System.out.println (temp + " is not palindrome");
}
}

OUTPUT :-
Q. 03 WAP to add the elements of Vector as arguments of main method (Run
Time) and rearrange them and copy it to an array.

import java.util.*;

public class Vector1


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

Vector list = new Vector(5);


int len = list.capacity();
for(int i=0;i<len;i++)
{
list.addElement(args[i]);
}
list.insertElementAt("JAVA",2);
int size = list.size();
String[] listArray = new String[size];
list.copyInto(listArray);
System.out.println("List of languages");
for(int i=0;i<size;i++)
{
System.out.println(listArray[i]);
}

OUTPUT :-
Q. 4.1 WAP to arrange the strings in alphabetical order.

//Sorting of String//
import java.util.*;

class StringSort
{
public static void main(String args[])
{
String arg[] = {"Graps","Pine Apple","Orange","Apple","Mango"};
int len = arg.length;
System.out.println("Original contents :");
for(int i=0 ; i<arg.length ; i++)
{
System.out.println(arg[i]);
}
Arrays.sort(arg);
System.out.println();
System.out.println("Sorted :");
for(int i=0 ; i<arg.length ; i++)
{
System.out.println(arg[i]);
}

}
}

OUTPUT :-
Q.4.2 WAP for StringBuffer class, which perform all the methods of that class.

class StringManipulation
{
public static void main(String[] args)
{
StringBuffer str = new StringBuffer("Object language");
System.out.println("Original String :" + str);
//obtaining string length//
System.out.println("Length of string :" + str.length());
//accessing characters in a string//
System.out.println("Character at position 10 :" + str.charAt(10));
//inserting string in middle//
String st = new String(str.toString());
int pos = st.indexOf("language");
str.insert(pos," Oriented");
System.out.println("Modified string :" + str);
//Modifying characters
str.setCharAt(6,'-');
System.out.println("String now :" + str);
//Appending a string at the and
str.append(" imporves security.");
System.out.println("Appended string :" + str);
}
}

OUTPUT :-
Q. 5 WAP to calculate Simple Interest using the Wrapper Class.

import java.io.*;
class SimpleInterest
{
public static void main(String[] args)
{

Float principleAmount = new Float(0);


Double interestRate = new Double(0);
int numYears = 0;
try
{
DataInputStream din = new DataInputStream(System.in);
System.out.println("Enter principle amount");
System.out.flush();
String principleString = din.readLine();
principleAmount = Float.valueOf(principleString);
System.out.println("Enter interest rate");
System.out.flush();
String interestString = din.readLine();
interestRate =Double.valueOf(interestString);
System.out.println("Enter number of years");
System.out.flush();
String yearString = din.readLine();
numYears = Integer.parseInt(yearString);
}

catch(Exception e)
{
System.out.println("input/output error");
System.exit(1);
}
float value = loan( principleAmount.floatValue(),
interestRate.floatValue(), numYears);
System.out.println("Final value " + value);
}
static float loan(float p, float r,int n){
int year = 1;
float sum = p;
while(year<=n)
{
sum = sum * (1+r);
year = year + 1;
}
return sum;
}
}
OUTPUT :-
Q. 6 WAP to calculate area of various geometrical figures using the abstract
class.

abstract class Figure


{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1 = a;
dim2 = b;
}
abstract double area();
}

class Rectangle extends Figure


{
Rectangle(double a , double b)
{
super(a,b);
}
double area()
{
System.out.println("Inside area for rectangle");
return dim1 * dim2;
}
}
class Triangle extends Figure
{
Triangle(double a , double b)
{
super(a,b);
}
double area()
{
System.out.println("Inside area for triangle");
return dim1 * dim2 / 2;
}
}

class AbstractClassDemo
{
public static void main(String[] args)
{
Rectangle r = new Rectangle(9,5);
Triangle t = new Triangle(10,8);
Figure f;
f=r;
System.out.println("Area is :"+ f.area());
f=t;
System.out.println("Area is :"+f.area());
}
}
OUTPUT :-
Q. 7 WAP to design a class using abstract methods and classes.

abstract class Animal


{
abstract void makeSound();
public void eat()
{
System.out.println("I can eat.");
}
}

class Dog extends Animal


{
public void makeSound()
{
System.out.println("Bark bark");
}
}

class ABsDemo
{
public static void main(String[] args)
{
Dog d1 = new Dog();
d1.makeSound();
d1.eat();
}
}
Q. 8 WAP to create a simple class to demonstrate Inheritance using super and
this keywords.

class Vehicle
{
int maxSpeed = 120;
}

class Car extends Vehicle {


int maxSpeed = 180;

void display()
{

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


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

class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Q. 9 WAP to demonstrate overriding method in Inheritance.

class Parent
{
void show()
{
System.out.println("Parent's show()");
}
}

class Child extends Parent


{
// This method overrides show() of Parent
void show()
{
super.show();
System.out.println("Child's show()");
}
}

class Override {
public static void main(String[] args)
{
Parent obj2 = new Child();
obj2.show();

}
}
Q. 10 WAP to create a package using command & one package using command
& one package will import another package.

package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

import pack.PackA;

class PackB
{
public static void main(String args[])
{
PackA obj = new PackA();
obj.msg();
}
}
Q11. WAP where single class implements more than one interfaces and with the
help of interfaces reference variable user call the methods.

class Student{
int rollNumber;
void getNumber(int n){
rollNumber = n;
}
void putNumber(){
System.out.println("Roll No: " + rollNumber); }
}
class Test extends Student{
float part1,part2;
void getMarks(float m1,float m2){
part1 = m1;
part2 = m2; }
void putMarks(){
System.out.println("Marks Obtained :");
System.out.println("Part1 =" + part1);
System.out.println("Part2 =" + part2);
}
}
interface Sports{
float sportWt = 6.0F;
void putWt();
}
class Results extends Test implements Sports{
float total;
public void putWt(){ System.out.println("Sports WT = " + sportWt); }
void display(){
total = part1 + part2 + sportWt;
putNumber();
putMarks();
putWt();
System.out.println("Total score =" + total);
}
}
class Hybrid{
public static void main(String[] args){
Results student1 = new Results();
student1.getNumber(1234);
student1.getMarks(27.5F,33.0F);
student1.display();
}
}
Q12. WAP for multithread using the isAlive(), join() and synchronized()
methods of the thread class.
class Callme
{
void call(String msg)
{
System.out.print("[" + msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interruped");
}
System.out.println("]");
}
}

class Caller implements Runnable


{
String msg;
Callme target;
Thread t;
public Caller(Callme targ,String s)
{
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
//synchronized calls to call()
public void run()
{
synchronized(target)
{
target.call(msg);
}
}
}

class ThreadDemo
{
public static void main(String[] args)
{
Callme target = new Callme();
Caller ob1 = new Caller(target,"Hello");
Caller ob2 = new Caller(target,"Synchronized");
Caller ob3 = new Caller(target,"World");
System.out.println("Thread Caller ob1 is alive :"+ ob1.t.isAlive());
System.out.println("Thread Caller ob2 is alive :"+ ob2.t.isAlive());
System.out.println("Thread Caller ob3 is alive :"+ ob3.t.isAlive());
//wait for threads to end//
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrrepted");
}
System.out.println("Thread Caller ob1 is alive :"+ ob1.t.isAlive());
System.out.println("Thread Caller ob2 is alive :"+ ob2.t.isAlive());
System.out.println("Thread Caller ob3 is alive :"+ ob3.t.isAlive());
System.out.println("Main Thread Exiting");
}
}
Q13. WAP that use the multiple catch statements with in the try-catch
mechanisms.

public class Exp4


{
public static void main(String ar[])
{
try{
int x = Integer.parseInt(ar[0]);
int y = Integer.parseInt(ar[1]);
int z = x/y;
System.out.println("Result is :- " + z);
}catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBoundsException" + e);
}
catch(NumberFormatException e)
{
System.out.println("Wrong conversion");
}
catch(ArithmeticException e)
{
System.out.println("Zero division Error");
}
}
}

OUTPUT :-
Q14. WAP where user will create a self-exception using the throw keyword.

class AgeThrow1 extends Exception


{
String str;
AgeThrow1()
{
str="Age should between 18 & 56";
}
AgeThrow1(int a)
{
str="u have entered(" +a+ ")" + ",But Age should between 18 & 56";;
}
public String toString()
{
return(str);
}
}
public class AgeExcep
{
public static void main(String ar[])
{
try{
int age = Integer.parseInt(ar[0]);
if(age<18 || age>56)
{
throw new AgeThrow1(age);
}
else
{
System.out.println("Age = " + age);
}
}catch(Exception e)
{
System.out.println("Exception is :- " + e);
}
}
}

OUTPUT :-
Q. 15. WAP for creating a file and to store data into that file.(Using the
FileWriterIOStream)
import java.io.*;
class FileWriterDemo{
public static void main(String[] args){
try{
File fread = new File("FileWriterDemo.java");
File fwrite = new File("FileDemo.java");
BufferedReader br = new BufferedReader(new FileReader(fread));
FileWriter fw = new FileWriter(fwrite);
while(true){
String str = br.readLine();
if(str==null)
break;
else
fw.write(str+"\n");
}
System.out.println("File Written Successfully");
br.close();
fw.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output: Before Execution:

Compile & Run


After Execution:
Q16. WAP to illustrate the use of all methods of URL class.

import java.net.*;
import java.io.*;
public class ParseURL
{
public static void main(String ar[])
{
try{
URL aURL = new
URL("http://java.sun.com:80/docs/books/tutorial/index.html/#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("Host = " + aURL.getHost());
System.out.println("File name = " + aURL.getFile());
System.out.println("Port = " + aURL.getPort());
System.out.println("Ref = " + aURL.getRef());
} catch(Exception e)
{
System.out.println(e);
}
}
}
Q17. WAP for matrix multiplication using input/output stream.

import java.io.*;
class Matrix1
{
public static void main(String[] args)
{
try
{
DataInputStream din = new DataInputStream(System.in);
int m=0,n=0,p=0,q=0;
int i=0,j=0,k=0;
System.out.println("Enter the order of matrix A: ");
m = Integer.parseInt(din.readLine());
n = Integer.parseInt(din.readLine());
System.out.println("Enter the order of matrix B: ");
p = Integer.parseInt(din.readLine());
q = Integer.parseInt(din.readLine());
int[][] a = new int[m][n];
int[][] b = new int[p][q];
int[][] c = new int[10][10];
if(m == q)
{
System.out.println("Matrix can be Multiplied");
System.out.println("Enter the matrix A :");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j] = Integer.parseInt(din.readLine());
}
}
System.out.println("Matrix A");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print( ""+a[i][j]);
System.out.print("\t");
}
System.out.println();
}
System.out.println("Enter the matrix B :");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
b[i][j] = Integer.parseInt(din.readLine());
}
}
System.out.println("Matrix B");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
System.out.print( ""+b[i][j]);
System.out.print("\t");
}
System.out.println();
}
System.out.println("matrix C:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j] = c[i][j] + (a[i][k] * b[k][j]);
}
}
}
System.out.println("Matrix C");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
System.out.print( ""+c[i][j]);
System.out.print("\t");
}
System.out.println();
}
}

}
catch(Exception e){}
}
}
OUTPUT :-
Q18. WAP to demonstrate the Border Layout using applet.

import java.awt.*;
import java.applet.Applet;
//<Applet code="BorderLayoutDemo" height=400 width=400></Applet>//
public class BorderLayoutDemo extends Applet {
public void init() {
setLayout(new BorderLayout());
add(new Button("North"), BorderLayout.NORTH);
add(new Button("South"), BorderLayout.SOUTH);
add(new Button("East"), BorderLayout.EAST);
add(new Button("West"), BorderLayout.WEST);
add(new Button("Center"), BorderLayout.CENTER);
}
}
Q19. WAP for APPLET that handle the keyboard events.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
//<Applet code="AppletKeyEvent" height=400 width=400></Applet>
public class AppletKeyEvent extends Applet implements KeyListener{
String msg,msg1 ;
public void init(){
msg = "";
msg1 = "";
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent e){
switch(e.getKeyCode()){
case KeyEvent.VK_ADD:
msg1 += "<+>";
break;
case KeyEvent.VK_F1:
msg1 += "<F1>";
break;
case KeyEvent.VK_F2:
msg1 += "<F2>";
break;
case KeyEvent.VK_PAGE_UP:
msg1 += "<Page Up>";
break;
case KeyEvent.VK_PAGE_DOWN:
msg1 += "<Page Down>";
break;
}
repaint();
}
public void keyTyped(KeyEvent e){
msg += e.getKeyChar();
repaint();
}
public void keyReleased(KeyEvent e){
showStatus("Key Released");
}
public void paint(Graphics g){
g.drawString(msg,10,20);
g.drawString(msg1,10,200);
}
}

OUTPUT :-
Q. 20 WAP to create an Applet using the HTML file, where parameter pass for
font size and font type and applet message will change to corresponding
parameters.

import java.lang.Integer;
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Vector;
/* This applet displays a String with the user's selected fontname, style and size
attributes. */
public class FontSelection extends JApplet implements ItemListener
{
JLabel fontLabel, sizeLabel, styleLabel;
FontPanel fontC;
JComboBox fonts, sizes, styles;
int index = 0;
String fontchoice = "fontchoice";
int stChoice = 0;
String siChoice = "10";
public void init() {
getContentPane().setLayout( new BorderLayout() );
JPanel topPanel = new JPanel();
JPanel fontPanel = new JPanel();
JPanel sizePanel = new JPanel();
JPanel stylePanel = new JPanel();
JPanel sizeAndStylePanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
fontPanel.setLayout( new GridLayout( 2, 1 ) );
sizePanel.setLayout( new GridLayout( 2, 1 ) );
stylePanel.setLayout( new GridLayout( 2, 1 ) );
sizeAndStylePanel.setLayout( new BorderLayout() );
topPanel.add( BorderLayout.WEST, fontPanel );
sizeAndStylePanel.add( BorderLayout.WEST, sizePanel );
sizeAndStylePanel.add( BorderLayout.CENTER, stylePanel );
topPanel.add( BorderLayout.CENTER, sizeAndStylePanel );
getContentPane().add( BorderLayout.NORTH, topPanel );
fontLabel = new JLabel();
fontLabel.setText("Fonts");
Font newFont = getFont().deriveFont(1);
fontLabel.setFont(newFont);
fontLabel.setHorizontalAlignment(JLabel.CENTER);
fontPanel.add(fontLabel);
sizeLabel = new JLabel();
sizeLabel.setText("Sizes");
sizeLabel.setFont(newFont);
sizeLabel.setHorizontalAlignment(JLabel.CENTER);
sizePanel.add(sizeLabel);
styleLabel = new JLabel();
styleLabel.setText("Styles");
styleLabel.setFont(newFont);
styleLabel.setHorizontalAlignment(JLabel.CENTER);
stylePanel.add(styleLabel);
GraphicsEnvironment gEnv =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String envfonts[] = gEnv.getAvailableFontFamilyNames();
Vector vector = new Vector();
for ( int i = 1; i < envfonts.length; i++ ) {
vector.addElement(envfonts[i]);
}
fonts = new JComboBox( vector );
fonts.setMaximumRowCount( 9 );
fonts.addItemListener(this);
fontchoice = envfonts[0];
fontPanel.add(fonts);
sizes = new JComboBox( new Object[]{ "10", "12", "14", "16", "18"} );
sizes.setMaximumRowCount( 9 );
sizes.addItemListener(this);
sizePanel.add(sizes);
styles = new JComboBox( new Object[]{
"PLAIN",
"BOLD",
"ITALIC",
"BOLD & ITALIC"} );
styles.setMaximumRowCount( 9 );
styles.addItemListener(this);
sizes.setMaximumRowCount( 9 );
stylePanel.add(styles);
fontC = new FontPanel();
fontC.setBackground(Color.white);
getContentPane().add( BorderLayout.CENTER, fontC);
}
/* * Detects a state change in any of the Lists. Resets the variable corresponding
* to the selected item in a particular List. Invokes changeFont with the currently
* selected fontname, style and size attributes.
*/
public void itemStateChanged(ItemEvent e) {
if ( e.getStateChange() != ItemEvent.SELECTED ) {
return;
}

Object list = e.getSource();

if ( list == fonts ) {
fontchoice = (String)fonts.getSelectedItem();
} else if ( list == styles ) {
index = styles.getSelectedIndex();
stChoice = index;
} else {
siChoice = (String)sizes.getSelectedItem();
}
fontC.changeFont(fontchoice, stChoice, siChoice);
}
public static void main(String s[]) {
JFrame f = new JFrame("FontSelection");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
JApplet fontSelection = new FontSelection();
f.getContentPane().add(fontSelection, BorderLayout.CENTER);
fontSelection.init();
f.setSize(new Dimension(550,250));
f.setVisible(true);
}
}
class FontPanel extends JPanel {
Font thisFont;
public FontPanel(){
thisFont = new Font("Arial", Font.PLAIN, 10);
}
// Resets thisFont to the currently selected fontname, size and style attributes.
public void changeFont(String f, int st, String si){
Integer newSize = new Integer(si);
int size = newSize.intValue();
thisFont = new Font(f, st, size);
repaint();
}
public void paintComponent (Graphics g) {
super.paintComponent( g );
Graphics2D g2 = (Graphics2D) g;
int w = getWidth();
int h = getHeight();
g2.setColor(Color.darkGray);
g2.setFont(thisFont);
String change = "Pick a font, size, and style to change me";
FontMetrics metrics = g2.getFontMetrics();
int width = metrics.stringWidth( change );
int height = metrics.getHeight();
g2.drawString( change, w/2-width/2, h/2-height/2 );
}
}

OUTPUT :-
Q21. WAP for display the checkboxes, Labels and TextFields on an AWT.

import java.awt.*;
import java .awt.event.*;
class FrameDesign extends Frame
{
Panel p,lp,tfp,cbp;
Label l1,l2;
TextField tf1,tf2;
Checkbox cb1,cb2,cb3;
FrameDesign()
{
super("Components Demo");
p = new Panel();
lp = new Panel();
tfp = new Panel();
cbp = new Panel();
l1 = new Label("This is Label1");
lp.add(l1);
l2 = new Label("This is Label2");
lp.add(l2);
tf1 = new TextField("This is TextField1");
tfp.add(tf1);
tf2 = new TextField("This is TextField2");
tfp.add(tf2);
cb1 = new Checkbox("Red");
cb2 = new Checkbox("Yellow");
cb3 = new Checkbox("Orange");
cbp.setLayout(new GridLayout(3,1));
cbp.add(cb1);
cbp.add(cb2);
cbp.add(cb3);
p.setLayout(new BorderLayout());
p.add(lp,"North");
p.add(tfp,"Center");
p.add(cbp,"South");
add(p);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
pack();
setVisible(true);
}
}
public class Display
{
public static void main(String[] args)
{
new FrameDesign();
}
}

OUTPUT :-
Q22. WAP for AWT to create Menu and Popup Menu for frame.

import java.awt.*;
import java.awt.event.*;
class FrameDesign extends Frame implements ActionListener
{
MenuBar mbar;
Menu file,edit;
MenuItem fn1,fo1,fn2,fo2,fs,fe;
MenuItem ec1,ep1,ec2,ep2;
Panel p;
PopupMenu pm;
FileDialog fid1 = new FileDialog(this,"Open");
FileDialog fid2 = new FileDialog(this,"Save",FileDialog.SAVE);
FrameDesign()
{
p = new Panel();
pm = new PopupMenu();
mbar = new MenuBar();
file = new Menu("File");
edit = new Menu("Edit");
fn1 = new MenuItem("New");
fn2 = new MenuItem("New");
fo1 = new MenuItem("Open");
fo2 = new MenuItem("Open");
fs = new MenuItem("Save");
fe = new MenuItem("Exit");
ec1 = new MenuItem("Copy");
ep1 = new MenuItem("Paste");
ec2 = new MenuItem("Copy");
ep2 = new MenuItem("Paste");
file.add(fn1);
file.add(fo1);
fo1.addActionListener(this);
fo2.addActionListener(this);
file.add(fs);
fs.addActionListener(this);
file.add(new MenuItem("-"));
file.add(fe);
fe.addActionListener(this);
edit.add(ec1);
edit.add(ep1);
mbar.add(file);
mbar.add(edit);
setMenuBar(mbar);
pm.add(fn2);
pm.add(fo2);
pm.add(new MenuItem("-"));
pm.add(ec2);
pm.add(ep2);
p.add(pm);
add(p);
p.addMouseListener(
new MouseAdapter()
{
public void mouseReleased(MouseEvent e)
{
if(e.getButton() == MouseEvent.BUTTON3)
pm.show(p,e.getX(),e.getY());
}
});
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == fe)
System.exit(0);
if(e.getSource() == fo1)
fid1.setVisible(true);
if(e.getSource() == fs)
fid2.setVisible(true);
if(e.getSource() == fo2)
fid1.setVisible(true);
}
}
public class MenuDemo1
{
public static void main(String args[])
{
FrameDesign fd = new FrameDesign();
fd.setSize(400,400);
fd.setVisible(true);
}
}
OUTPUT :-
Q23. WAP for applet who generate the MouseMotionListener Event.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
//<Applet code="MouseEvent1" height=300 width=300></Applet>
public class MouseEvent1 extends Applet implements MouseMotionListener
{
int x = 0;int y = 0;
String msg = "";
public void init()
{
addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent e)
{
x = e.getX();
y = e.getY();
msg = "Mouse Moved at " + " x:"+ x +"y:" + y;
showStatus(msg);
repaint();
}
public void mouseDragged(MouseEvent e)
{
x = e.getX();
y = e.getY();
msg = "Mouse Dragged at " +"x : " + x +" y:"+ y;
showStatus(msg);
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}
OUTPUT :-
Q. 24 WAP to create a table using JDBC.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class CreateTable


{
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
//serverhost = localhost, port=3306, username=root,
password=123

Connection cn=DriverManager.getConnection( "jdbc:mysql://localhost:3306/demo"


,"root","123 ");
Statement smt=cn.createStatement();
//query to create table Employees with fields
name(empid,empname,dob,city,salary)
String q="create table Employees(empid varchar(10) primary
key,empname varchar(45),dob date,city varchar(45),salary varchar(45))";
//to execute the update
smt.executeUpdate(q);
System.out.println("Table Created. .. ");
cn.close();

}catch(Exception e){
System.out.println(e.getMessage());
}
}

Output

Table Created...
Q. 25 WAP to JDBC insert the values into the existing table by using preparing
statement.

import java.sql.*;
public class Employee15
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:jdbcdsn",
"","");
Statement s = con.createStatement();
s.execute("create table employee ( emp_id number,emp_name
varchar(20),emp_address varchar(30) )"); // create a table
s.execute("insert into employee values(001,'ARman','Delhi')"); // insert first
row into the table
s.execute("insert into employee values(002,'Robert','Canada')"); // insert
second row into the table
s.execute("insert into employee values(003,'Ahuja','Karnal')"); // insert third
row into the table
s.execute("select * from employee"); // select the data from the table
ResultSet rs = s.getResultSet(); // get the ResultSet that will generate from our
query
if (rs != null) // if rs == null, then there is no record in ResultSet to show
while ( rs.next() ) // By this line we will step through our data row-by-row
{
System.out.println(" " );
System.out.println("Id of the employee: " + rs.getString(1) );
System.out.println("Name of employee: " + rs.getString(2) );
System.out.println("Address of employee: " + rs.getString(3) );
System.out.println(" " );
}
s.close(); // close the Statement to let the database know we're done with it
con.close(); // close the Connection to let the database know we're done
with it
}
catch (Exception err)
{
System.out.println("ERROR: " + err);
}
}}
Output:
Q. 26 WAP to JDBC display the values from the existing Table.
import java.sql.*;
public class select
{
public static void main(String args[]) throws Exception {
//Step-1
//load the class for driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Step -2
Connection con = DriverManager.getConnection("jdbc:odbc:dsn1", "system",
"pintu");
//Step -3
System.out.println("Connected to database");
Statement stmt = con.createStatement();
//Step-4
ResultSet rs = stmt.executeQuery("select * from employee");
//Fetching data from ResultSet and display
while (rs.next())
{
//to fetch value from a column having number type of value
int x = rs.getInt("empno");
//to fetch value from a column having varchar/text type of value
String y = rs.getString("empname");
//to fetch value from a column having number type of value
int z = rs.getInt("sal");
System.out.println(x + " " + y + " " + z);
}
//Step-5
con.close();
}
}
Q. 27 WAP to JDBC delete the values from the existing Table.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class DeleteDataDemo {


public static void main(String[] args) {
Connection connection = null;
Statement stmt = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/JDBCDemo", "root",
"password");

stmt = connection.createStatement();
stmt.execute("DELETE FROM EMPLOYEE WHERE ID >= 1");
}
catch (Exception e) {
e.printStackTrace();
}finally {
try {
stmt.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Q28. WAP, which support the TCP/IP protocol where client gives the message
and server, will receive the message.

import java.io.*;
import java.net.*;
public class EchoClient
{
public static void main (String ar[]) throws IOException
{
Socket echosocket =null;
PrintWriter out =null;
BufferedReader in =null;
try{
echosocket = new Socket ("DESKTOP-D1UBD9V",7);
out= new PrintWriter(echosocket.getOutputStream(),true);
in= new BufferedReader(new
InputStreamReader(echosocket.getInputStream()));
}catch(UnknownHostException e)
{
System.out.println("dont know about host:DESKTOP-D1UBD9V");
System.exit(1);
}catch(IOException e)
{
System.out.println("couldn't get I/o for the connection to :DESKTOP-
D1UBD9V");
System.exit(1);
}
BufferedReader stdin= new BufferedReader(new
InputStreamReader(System.in));
String userInput;
while((userInput = stdin.readLine()) != null)
{
out.println(userInput);
System.out.println("echo"+in.readLine());
}
out.close();
echosocket.close();
in.close();
echosocket.close();
}
}
OUTPUT :-
Q29. WAP to illustrate the use of all methods of URL class.

import java.net.*;
import java.io.*;
public class ParseURL
{
public static void main(String ar[])
{
try{
URL aURL = new URL("http://www.ssmv.ac.in/Computer");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("Host = " + aURL.getHost());
System.out.println("File name = " + aURL.getFile());
System.out.println("Port = " + aURL.getPort());
System.out.println("Ref = " + aURL.getRef());
} catch(Exception e)
{
System.out.println(e);
}
}
}

OUTPUT :-
Q30. WAP for writing and running a simple Servlet to handle Get and Post
Methods.
Login Page: Save as FormData.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>User Details</title>
</head>
<body >
<h3>Fill in the Form</h3>

<form action="FormData" method="post">


<table>

<tr>
<td>Full Name:</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>Phone Number:</td>
<td><input type="text" name="phone" /></td>
</tr>
<tr>
<td>Gender:</td>
<td><input type="radio" name="gender" value="male"
/>Male
<input type="radio" name="gender" value="female"
/>Female</td>
</tr>
<tr>
<td>Select Programming Languages to learn:</td>
<td><input type="checkbox" name="language" value="java"
/>Java
<input type="checkbox" name="language"
value="python" />Python
<input type="checkbox" name="language" v alue="sql"
/>SQL
<input type="checkbox" name="language" value="php"
/>PHP</td>
</tr>
<tr>
<td>Select Course duration:</td>
<td><select name="duration">
<option value="3months">3 Months</option>
<option value="6months">6 Months</option>
<option value="9months">9
Months</option></select></td>
</tr>
<tr>
<td>Anything else you want to share:</td>
<td><textarea rows="5" cols="40"
name="comment"></textarea></td>
</tr>

</table>

<input type="submit" value="Submit Details">

</form>

</body>
</html>
Java Code:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Servlet implementation class FormDataHandle

// Annotation to map the Servlet URL


@WebServlet("/FormData")
public class FormDataHandle extends HttpServlet {
private static final long serialVersionUID = 1L;

// Auto-generated constructor stub


public FormDataHandle() {
super();
}
// HttpServlet doPost(HttpServletRequest request,
HttpServletResponse response) method
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

// Get the values from the request using 'getParameter'


String name = request.getParameter("name");
String phNum = request.getParameter("phone");
String gender = request.getParameter("gender");

// To get all the values selected for


// programming language, use 'getParameterValues'
String progLang[] = request. getParameterValues("language");

// Iterate through the String array to


// store the selected values in form of String
String langSelect = "";
if(progLang!=null){
for(int i=0;i<progLang.length;i++){
langSelect= langSelect + progLang[i]+ ", ";
}
}

String courseDur = request.getParameter("duration");


String comment = request.getParameter("comment");

// set the content type of response to 'text/html'


response.setContentType("text/html");

// Get the PrintWriter object to write


// the response to the text-output stream
PrintWriter out = response.getWriter();

// Print the data


out.print("<html><body>");
out.print("<h3>Details Entered</h3><br/>");

out.print("Full Name: "+ name + "<br/>");


out.print("Phone Number: "+ phNum +"<br/>");
out.print("Gender: "+ gender +"<br/>");
out.print("Programming languages selected: "+ langSelect
+"<br/>");
out.print("Duration of course: "+ courseDur+"<br/>");
out.print("Comments: "+ comment);
out.print("</body></html>");

You might also like