Q. 01 WAP to print Fibonacci Series.
class Fibo
{
public static void main(String args[])
{
int a=0,b=1,c=0,i=1;
[Link]( a + " , " + b + " , ");
do
{
c=a+b;
[Link](c + " , ");
a=b;
b=c;
i++;
} while (i<=8);
}
}
OUTPUT :-
Q. 02 WAP to check that the given string is palindrome or not.
import [Link].*;
class PalinString
{
public static void main (String args[]) throws IOException
{
BufferedReader br = new BufferedReader (new InputStreamReader
([Link]));
[Link] ("enter the String:");
String str = [Link] ();
String temp = str;
StringBuffer sb = new StringBuffer (str);
[Link] ();
str = [Link] ();
if ([Link](str))
[Link] (temp + " is palindrome");
else
[Link] (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 [Link].*;
public class Vector1
{
public static void main(String args[])
{
Vector list = new Vector(5);
int len = [Link]();
for(int i=0;i<len;i++)
{
[Link](args[i]);
}
[Link]("JAVA",2);
int size = [Link]();
String[] listArray = new String[size];
[Link](listArray);
[Link]("List of languages");
for(int i=0;i<size;i++)
{
[Link](listArray[i]);
}
OUTPUT :-
Q. 4.1 WAP to arrange the strings in alphabetical order.
//Sorting of String//
import [Link].*;
class StringSort
{
public static void main(String args[])
{
String arg[] = {"Graps","Pine Apple","Orange","Apple","Mango"};
int len = [Link];
[Link]("Original contents :");
for(int i=0 ; i<[Link] ; i++)
{
[Link](arg[i]);
}
[Link](arg);
[Link]();
[Link]("Sorted :");
for(int i=0 ; i<[Link] ; i++)
{
[Link](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");
[Link]("Original String :" + str);
//obtaining string length//
[Link]("Length of string :" + [Link]());
//accessing characters in a string//
[Link]("Character at position 10 :" + [Link](10));
//inserting string in middle//
String st = new String([Link]());
int pos = [Link]("language");
[Link](pos," Oriented");
[Link]("Modified string :" + str);
//Modifying characters
[Link](6,'-');
[Link]("String now :" + str);
//Appending a string at the and
[Link](" imporves security.");
[Link]("Appended string :" + str);
}
}
OUTPUT :-
Q. 5 WAP to calculate Simple Interest using the Wrapper Class.
import [Link].*;
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([Link]);
[Link]("Enter principle amount");
[Link]();
String principleString = [Link]();
principleAmount = [Link](principleString);
[Link]("Enter interest rate");
[Link]();
String interestString = [Link]();
interestRate =[Link](interestString);
[Link]("Enter number of years");
[Link]();
String yearString = [Link]();
numYears = [Link](yearString);
}
catch(Exception e)
{
[Link]("input/output error");
[Link](1);
}
float value = loan( [Link](),
[Link](), numYears);
[Link]("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()
{
[Link]("Inside area for rectangle");
return dim1 * dim2;
}
}
class Triangle extends Figure
{
Triangle(double a , double b)
{
super(a,b);
}
double area()
{
[Link]("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;
[Link]("Area is :"+ [Link]());
f=t;
[Link]("Area is :"+[Link]());
}
}
OUTPUT :-
Q. 7 WAP to design a class using abstract methods and classes.
abstract class Animal
{
abstract void makeSound();
public void eat()
{
[Link]("I can eat.");
}
}
class Dog extends Animal
{
public void makeSound()
{
[Link]("Bark bark");
}
}
class ABsDemo
{
public static void main(String[] args)
{
Dog d1 = new Dog();
[Link]();
[Link]();
}
}
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()
{
[Link]("Maximum Speed: "+[Link]);
[Link]("Maximum Speed: "+[Link]);
}
}
class Test
{
public static void main(String[] args)
{
Car small = new Car();
[Link]();
}
}
Q. 9 WAP to demonstrate overriding method in Inheritance.
class Parent
{
void show()
{
[Link]("Parent's show()");
}
}
class Child extends Parent
{
// This method overrides show() of Parent
void show()
{
[Link]();
[Link]("Child's show()");
}
}
class Override {
public static void main(String[] args)
{
Parent obj2 = new Child();
[Link]();
}
}
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()
{
[Link]("Hello");
}
}
import [Link];
class PackB
{
public static void main(String args[])
{
PackA obj = new PackA();
[Link]();
}
}
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(){
[Link]("Roll No: " + rollNumber); }
}
class Test extends Student{
float part1,part2;
void getMarks(float m1,float m2){
part1 = m1;
part2 = m2; }
void putMarks(){
[Link]("Marks Obtained :");
[Link]("Part1 =" + part1);
[Link]("Part2 =" + part2);
}
}
interface Sports{
float sportWt = 6.0F;
void putWt();
}
class Results extends Test implements Sports{
float total;
public void putWt(){ [Link]("Sports WT = " + sportWt); }
void display(){
total = part1 + part2 + sportWt;
putNumber();
putMarks();
putWt();
[Link]("Total score =" + total);
}
}
class Hybrid{
public static void main(String[] args){
Results student1 = new Results();
[Link](1234);
[Link](27.5F,33.0F);
[Link]();
}
}
Q12. WAP for multithread using the isAlive(), join() and synchronized()
methods of the thread class.
class Callme
{
void call(String msg)
{
[Link]("[" + msg);
try
{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]("Interruped");
}
[Link]("]");
}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ,String s)
{
target = targ;
msg = s;
t = new Thread(this);
[Link]();
}
//synchronized calls to call()
public void run()
{
synchronized(target)
{
[Link](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");
[Link]("Thread Caller ob1 is alive :"+ [Link]());
[Link]("Thread Caller ob2 is alive :"+ [Link]());
[Link]("Thread Caller ob3 is alive :"+ [Link]());
//wait for threads to end//
try
{
[Link]();
[Link]();
[Link]();
}
catch(InterruptedException e)
{
[Link]("Interrrepted");
}
[Link]("Thread Caller ob1 is alive :"+ [Link]());
[Link]("Thread Caller ob2 is alive :"+ [Link]());
[Link]("Thread Caller ob3 is alive :"+ [Link]());
[Link]("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 = [Link](ar[0]);
int y = [Link](ar[1]);
int z = x/y;
[Link]("Result is :- " + z);
}catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBoundsException" + e);
}
catch(NumberFormatException e)
{
[Link]("Wrong conversion");
}
catch(ArithmeticException e)
{
[Link]("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 = [Link](ar[0]);
if(age<18 || age>56)
{
throw new AgeThrow1(age);
}
else
{
[Link]("Age = " + age);
}
}catch(Exception e)
{
[Link]("Exception is :- " + e);
}
}
}
OUTPUT :-
Q. 15. WAP for creating a file and to store data into that file.(Using the
FileWriterIOStream)
import [Link].*;
class FileWriterDemo{
public static void main(String[] args){
try{
File fread = new File("[Link]");
File fwrite = new File("[Link]");
BufferedReader br = new BufferedReader(new FileReader(fread));
FileWriter fw = new FileWriter(fwrite);
while(true){
String str = [Link]();
if(str==null)
break;
else
[Link](str+"\n");
}
[Link]("File Written Successfully");
[Link]();
[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
}
Output: Before Execution:
Compile & Run
After Execution:
Q16. WAP to illustrate the use of all methods of URL class.
import [Link].*;
import [Link].*;
public class ParseURL
{
public static void main(String ar[])
{
try{
URL aURL = new
URL("[Link]
[Link]("protocol = " + [Link]());
[Link]("Host = " + [Link]());
[Link]("File name = " + [Link]());
[Link]("Port = " + [Link]());
[Link]("Ref = " + [Link]());
} catch(Exception e)
{
[Link](e);
}
}
}
Q17. WAP for matrix multiplication using input/output stream.
import [Link].*;
class Matrix1
{
public static void main(String[] args)
{
try
{
DataInputStream din = new DataInputStream([Link]);
int m=0,n=0,p=0,q=0;
int i=0,j=0,k=0;
[Link]("Enter the order of matrix A: ");
m = [Link]([Link]());
n = [Link]([Link]());
[Link]("Enter the order of matrix B: ");
p = [Link]([Link]());
q = [Link]([Link]());
int[][] a = new int[m][n];
int[][] b = new int[p][q];
int[][] c = new int[10][10];
if(m == q)
{
[Link]("Matrix can be Multiplied");
[Link]("Enter the matrix A :");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j] = [Link]([Link]());
}
}
[Link]("Matrix A");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
[Link]( ""+a[i][j]);
[Link]("\t");
}
[Link]();
}
[Link]("Enter the matrix B :");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
b[i][j] = [Link]([Link]());
}
}
[Link]("Matrix B");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
[Link]( ""+b[i][j]);
[Link]("\t");
}
[Link]();
}
[Link]("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]);
}
}
}
[Link]("Matrix C");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
[Link]( ""+c[i][j]);
[Link]("\t");
}
[Link]();
}
}
}
catch(Exception e){}
}
}
OUTPUT :-
Q18. WAP to demonstrate the Border Layout using applet.
import [Link].*;
import [Link];
//<Applet code="BorderLayoutDemo" height=400 width=400></Applet>//
public class BorderLayoutDemo extends Applet {
public void init() {
setLayout(new BorderLayout());
add(new Button("North"), [Link]);
add(new Button("South"), [Link]);
add(new Button("East"), [Link]);
add(new Button("West"), [Link]);
add(new Button("Center"), [Link]);
}
}
Q19. WAP for APPLET that handle the keyboard events.
import [Link].*;
import [Link].*;
import [Link].*;
//<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([Link]()){
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 += [Link]();
repaint();
}
public void keyReleased(KeyEvent e){
showStatus("Key Released");
}
public void paint(Graphics g){
[Link](msg,10,20);
[Link](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 [Link];
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
/* 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();
[Link]( new BorderLayout() );
[Link]( new GridLayout( 2, 1 ) );
[Link]( new GridLayout( 2, 1 ) );
[Link]( new GridLayout( 2, 1 ) );
[Link]( new BorderLayout() );
[Link]( [Link], fontPanel );
[Link]( [Link], sizePanel );
[Link]( [Link], stylePanel );
[Link]( [Link], sizeAndStylePanel );
getContentPane().add( [Link], topPanel );
fontLabel = new JLabel();
[Link]("Fonts");
Font newFont = getFont().deriveFont(1);
[Link](newFont);
[Link]([Link]);
[Link](fontLabel);
sizeLabel = new JLabel();
[Link]("Sizes");
[Link](newFont);
[Link]([Link]);
[Link](sizeLabel);
styleLabel = new JLabel();
[Link]("Styles");
[Link](newFont);
[Link]([Link]);
[Link](styleLabel);
GraphicsEnvironment gEnv =
[Link]();
String envfonts[] = [Link]();
Vector vector = new Vector();
for ( int i = 1; i < [Link]; i++ ) {
[Link](envfonts[i]);
}
fonts = new JComboBox( vector );
[Link]( 9 );
[Link](this);
fontchoice = envfonts[0];
[Link](fonts);
sizes = new JComboBox( new Object[]{ "10", "12", "14", "16", "18"} );
[Link]( 9 );
[Link](this);
[Link](sizes);
styles = new JComboBox( new Object[]{
"PLAIN",
"BOLD",
"ITALIC",
"BOLD & ITALIC"} );
[Link]( 9 );
[Link](this);
[Link]( 9 );
[Link](styles);
fontC = new FontPanel();
[Link]([Link]);
getContentPane().add( [Link], 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 ( [Link]() != [Link] ) {
return;
}
Object list = [Link]();
if ( list == fonts ) {
fontchoice = (String)[Link]();
} else if ( list == styles ) {
index = [Link]();
stChoice = index;
} else {
siChoice = (String)[Link]();
}
[Link](fontchoice, stChoice, siChoice);
}
public static void main(String s[]) {
JFrame f = new JFrame("FontSelection");
[Link](new WindowAdapter() {
public void windowClosing(WindowEvent e) {[Link](0);}
});
JApplet fontSelection = new FontSelection();
[Link]().add(fontSelection, [Link]);
[Link]();
[Link](new Dimension(550,250));
[Link](true);
}
}
class FontPanel extends JPanel {
Font thisFont;
public FontPanel(){
thisFont = new Font("Arial", [Link], 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 = [Link]();
thisFont = new Font(f, st, size);
repaint();
}
public void paintComponent (Graphics g) {
[Link]( g );
Graphics2D g2 = (Graphics2D) g;
int w = getWidth();
int h = getHeight();
[Link]([Link]);
[Link](thisFont);
String change = "Pick a font, size, and style to change me";
FontMetrics metrics = [Link]();
int width = [Link]( change );
int height = [Link]();
[Link]( change, w/2-width/2, h/2-height/2 );
}
}
OUTPUT :-
Q21. WAP for display the checkboxes, Labels and TextFields on an AWT.
import [Link].*;
import java .[Link].*;
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");
[Link](l1);
l2 = new Label("This is Label2");
[Link](l2);
tf1 = new TextField("This is TextField1");
[Link](tf1);
tf2 = new TextField("This is TextField2");
[Link](tf2);
cb1 = new Checkbox("Red");
cb2 = new Checkbox("Yellow");
cb3 = new Checkbox("Orange");
[Link](new GridLayout(3,1));
[Link](cb1);
[Link](cb2);
[Link](cb3);
[Link](new BorderLayout());
[Link](lp,"North");
[Link](tfp,"Center");
[Link](cbp,"South");
add(p);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](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 [Link].*;
import [Link].*;
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",[Link]);
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");
[Link](fn1);
[Link](fo1);
[Link](this);
[Link](this);
[Link](fs);
[Link](this);
[Link](new MenuItem("-"));
[Link](fe);
[Link](this);
[Link](ec1);
[Link](ep1);
[Link](file);
[Link](edit);
setMenuBar(mbar);
[Link](fn2);
[Link](fo2);
[Link](new MenuItem("-"));
[Link](ec2);
[Link](ep2);
[Link](pm);
add(p);
[Link](
new MouseAdapter()
{
public void mouseReleased(MouseEvent e)
{
if([Link]() == MouseEvent.BUTTON3)
[Link](p,[Link](),[Link]());
}
});
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if([Link]() == fe)
[Link](0);
if([Link]() == fo1)
[Link](true);
if([Link]() == fs)
[Link](true);
if([Link]() == fo2)
[Link](true);
}
}
public class MenuDemo1
{
public static void main(String args[])
{
FrameDesign fd = new FrameDesign();
[Link](400,400);
[Link](true);
}
}
OUTPUT :-
Q23. WAP for applet who generate the MouseMotionListener Event.
import [Link].*;
import [Link].*;
import [Link].*;
//<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 = [Link]();
y = [Link]();
msg = "Mouse Moved at " + " x:"+ x +"y:" + y;
showStatus(msg);
repaint();
}
public void mouseDragged(MouseEvent e)
{
x = [Link]();
y = [Link]();
msg = "Mouse Dragged at " +"x : " + x +" y:"+ y;
showStatus(msg);
repaint();
}
public void paint(Graphics g)
{
[Link](msg,x,y);
}
}
OUTPUT :-
Q. 24 WAP to create a table using JDBC.
import [Link];
import [Link];
import [Link];
public class CreateTable
{
public static void main(String[] args)
{
try
{
[Link]("[Link]").newInstance();
//serverhost = localhost, port=3306, username=root,
password=123
Connection cn=[Link]( "jdbc:mysql://localhost:3306/demo"
,"root","123 ");
Statement smt=[Link]();
//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
[Link](q);
[Link]("Table Created. .. ");
[Link]();
}catch(Exception e){
[Link]([Link]());
}
}
Output
Table Created...
Q. 25 WAP to JDBC insert the values into the existing table by using preparing
statement.
import [Link].*;
public class Employee15
{
public static void main(String[] args)
{
try
{
[Link]("[Link]");
Connection con = [Link]("jdbc:odbc:jdbcdsn",
"","");
Statement s = [Link]();
[Link]("create table employee ( emp_id number,emp_name
varchar(20),emp_address varchar(30) )"); // create a table
[Link]("insert into employee values(001,'ARman','Delhi')"); // insert first
row into the table
[Link]("insert into employee values(002,'Robert','Canada')"); // insert
second row into the table
[Link]("insert into employee values(003,'Ahuja','Karnal')"); // insert third
row into the table
[Link]("select * from employee"); // select the data from the table
ResultSet rs = [Link](); // 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 ( [Link]() ) // By this line we will step through our data row-by-row
{
[Link](" " );
[Link]("Id of the employee: " + [Link](1) );
[Link]("Name of employee: " + [Link](2) );
[Link]("Address of employee: " + [Link](3) );
[Link](" " );
}
[Link](); // close the Statement to let the database know we're done with it
[Link](); // close the Connection to let the database know we're done
with it
}
catch (Exception err)
{
[Link]("ERROR: " + err);
}
}}
Output:
Q. 26 WAP to JDBC display the values from the existing Table.
import [Link].*;
public class select
{
public static void main(String args[]) throws Exception {
//Step-1
//load the class for driver
[Link]("[Link]");
//Step -2
Connection con = [Link]("jdbc:odbc:dsn1", "system",
"pintu");
//Step -3
[Link]("Connected to database");
Statement stmt = [Link]();
//Step-4
ResultSet rs = [Link]("select * from employee");
//Fetching data from ResultSet and display
while ([Link]())
{
//to fetch value from a column having number type of value
int x = [Link]("empno");
//to fetch value from a column having varchar/text type of value
String y = [Link]("empname");
//to fetch value from a column having number type of value
int z = [Link]("sal");
[Link](x + " " + y + " " + z);
}
//Step-5
[Link]();
}
}
Q. 27 WAP to JDBC delete the values from the existing Table.
import [Link];
import [Link];
import [Link];
public class DeleteDataDemo {
public static void main(String[] args) {
Connection connection = null;
Statement stmt = null;
try
{
[Link]("[Link]");
connection =
[Link]("jdbc:mysql://localhost:3306/JDBCDemo", "root",
"password");
stmt = [Link]();
[Link]("DELETE FROM EMPLOYEE WHERE ID >= 1");
}
catch (Exception e) {
[Link]();
}finally {
try {
[Link]();
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
}
Q28. WAP, which support the TCP/IP protocol where client gives the message
and server, will receive the message.
import [Link].*;
import [Link].*;
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([Link](),true);
in= new BufferedReader(new
InputStreamReader([Link]()));
}catch(UnknownHostException e)
{
[Link]("dont know about host:DESKTOP-D1UBD9V");
[Link](1);
}catch(IOException e)
{
[Link]("couldn't get I/o for the connection to :DESKTOP-
D1UBD9V");
[Link](1);
}
BufferedReader stdin= new BufferedReader(new
InputStreamReader([Link]));
String userInput;
while((userInput = [Link]()) != null)
{
[Link](userInput);
[Link]("echo"+[Link]());
}
[Link]();
[Link]();
[Link]();
[Link]();
}
}
OUTPUT :-
Q29. WAP to illustrate the use of all methods of URL class.
import [Link].*;
import [Link].*;
public class ParseURL
{
public static void main(String ar[])
{
try{
URL aURL = new URL("[Link]
[Link]("protocol = " + [Link]());
[Link]("Host = " + [Link]());
[Link]("File name = " + [Link]());
[Link]("Port = " + [Link]());
[Link]("Ref = " + [Link]());
} catch(Exception e)
{
[Link](e);
}
}
}
OUTPUT :-
Q30. WAP for writing and running a simple Servlet to handle Get and Post
Methods.
Login Page: Save as [Link]
<!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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
// 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 = [Link]("name");
String phNum = [Link]("phone");
String gender = [Link]("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<[Link];i++){
langSelect= langSelect + progLang[i]+ ", ";
}
}
String courseDur = [Link]("duration");
String comment = [Link]("comment");
// set the content type of response to 'text/html'
[Link]("text/html");
// Get the PrintWriter object to write
// the response to the text-output stream
PrintWriter out = [Link]();
// Print the data
[Link]("<html><body>");
[Link]("<h3>Details Entered</h3><br/>");
[Link]("Full Name: "+ name + "<br/>");
[Link]("Phone Number: "+ phNum +"<br/>");
[Link]("Gender: "+ gender +"<br/>");
[Link]("Programming languages selected: "+ langSelect
+"<br/>");
[Link]("Duration of course: "+ courseDur+"<br/>");
[Link]("Comments: "+ comment);
[Link]("</body></html>");