Java Practical File

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47
At a glance
Powered by AI
The document discusses various Java programs and concepts implemented through coding examples and their outputs. Programs include printing odd numbers, finding factorials recursively, command line arguments, Fibonacci series, checking for prime numbers, object oriented concepts like constructors, overloading, overriding etc.

Programs discussed include printing odd numbers between 1 to 10, finding factorial recursively, accepting command line arguments, printing Fibonacci series, checking if a number is prime, implementing classes with constructors, methods, overloading and overriding methods.

Java concepts demonstrated include object oriented programming concepts like classes, objects, constructors, methods, overloading, overriding, interfaces, inheritance, exception handling, file handling, AWT, applets, strings, arrays, JDBC, RMI, threads.

VIVEKANANDA INSTITUTE OF PROFESSIONAL STUDIES

VIVEKANANDA SCHOOL OF INFORMATION TECHNOLOGY

MASTER OF COMPUTER APPLICATION


JAVA PROGRAMMING LAB FILE

Guru Gobind Singh Indraprastha University


Sector-16C, Dwarka, Delhi-110078

SUBMITTED TO: SUBMITTED BY:

Ms. KIRTI SHARMA DEVENDER RAGHAV


ASSISTANT PROFESSOR 00817704419
rd
VSIT MCA III SEM
INDEX

S.NO. PRACTICAL QUESTION TEACHER’S


SIGN

1 WAP to print all odd numbers between 1 to 10.

2 WAP to find out factorial of a number through recursion.


3 WAP to accept Command line arguments & print them.
4 WAP to print Fibonacci series.
5 WAP to obtain a number by a user & check if it is prime or
not.
6 WAP that creates a class Accounts with following details:
Instance variables: ac_no., name, ac_name, balance
Methods: withdrawal (), deposit (), display ().Use
constructors to initialize members.
7 WAP to implement constructor overloading.
8 WAP to count the no. of objects created in a program.
9 WAP to implement method overriding & method
overloading.
10 Create a class box having height, width, depth as the
instance variables & calculate its volume. Implement
constructor overloading in it. Create a subclass named
box_new that has weight as an instance variable. Use super
in the box_new class to initialize members of the base class.
11 WAP to implement Runtime polymorphism.
12 WAP to implement interface. Create an interface named
Shape having area () & perimeter () as its methods. Create
three classes circle, rectangle & square that implement this
interface.
13 WAP to show multiple inheritance.
14 WAP to implement exception handling. Use try, catch &
finally.
15 Create a user defined exception named
“NoMatchException” that is fired when the string entered
by the user is not “india”.
16 WAP to show even & odd numbers by thread.
17 WAP that draws different color shapes on an applet .Set the
foreground & background color as red & blue.
18 WAP to show moving banner by applet.
19 WAP to implement Matrix multiplication by 2D array.
20 WAP to demonstrate the use of equals(), trim() ,length() ,
substring(), compareTo() of String class.
21 WAP to implement file handling(both reading & writing to
a file)
22 WAP to implement all mouse events and mouse motion
events.
23 WAP to implement keyboard events.
24 WAP using AWT to create a simple calculator.
25 Create a login form using AWT controls like labels,
buttons, textboxes, checkboxes, list, checkboxgroup. The
selected checkbox item names should be displayed.
26 WAP to show Border Layout manager.
1. BoxLayout
2. CardLayout

27 WAP to show Grid Layout manager.


28 WAP to show Flow Layout manager.
29 WAP to show Border Layout manager.
30 Create a simple JDBC program that creates a table, stores
data into it, retrieves & prints the data.
31 Create an Applet with two buttons named ‘Audio’ and
‘Image’.
When user will press button ‘audio’ then an audio file
should play in applet, and if user press button ‘Image’ then
an image should see in applet window.
32 WAP in Java to demonstrate the application of RMI
(Remote Method Invocation).

33 Create a Java applet with three buttons


‘Red’,’Green’,’Blue’. Whenever user press any button the
corresponding color should be seen as background color in
an applet window.
34 WAP in java to implement the concept of ‘synchronization’
using thread.

Q1.Write a program to print odd numbers between 1 to 10.

CODING-

class OddNumber
{
public static void main(String args[])
{
System.out.println("The Odd Numbers are:");
for (int i = 1; i <= 10; i++)
{
if (i % 2 != 0)
{
System.out.println(i + " ");
}
}
}
}

OUTPUT-
Q2.Write a program to find out factorial of a number through recursion.

CODING-

class Facto
{
static int factorial(int n)
{
int p;
if (n == 0)
return 1;
else
p=n*factorial(n-1);
return p;
}
public static void main(String args[])
{
int i,fact=1;
int number=7;
fact = factorial(number);
System.out.println("Factorial of "+number+" is: "+fact);
}
}

OUTPUT-

Q3. Write a program to accept command line argument and print them.

CODING-

class Add
{
public static void main(String[] args)
{
int sum = 0;
for (int i = 0; i < args.length; i++)
{
sum = sum + Integer.parseInt(args[i]);
}
System.out.println("The sum of the arguments passed is " + sum);
}
}

OUTPUT-
Q4.Write a program to print a Fibonacci series.

CODING-

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

OUTPUT-

Q5.Write a program to obtain a number by a user & check if it’s prime or not.
CODING-
import java.util.Scanner;
class Prime
{
public static void main(String[] args)
{
int n,a,i,c=0;
boolean b=true;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
i=2;
while(i<n)
{
if(n%i==0)
{
c=1;
break;
}
i++;
}
if(c==0)
{
System.out.println("Entered no. is prime");
}
else
{
System.out.println("Entered no. is not prime");
}
}
}

OUTPUT-

Q6.Write a program that creates a class Accounts with following details:


Instance variables: ac_no., name, ac_name, balance.
Methods: withdrawal (), deposit (), display ().Use constructors to initialize
members.
CODING-
class Accounts
{
String name,ac_name;
int ac_no;
float balance;
Accounts()
{
name="Rohan Singh";
ac_no=124265;
ac_name="Savings";
}
void deposit(int n)
{
balance=balance+n;
}
void withdrawal(int n)
{
balance=balance-n;
}
void display()
{
System.out.println("Name:" + name);
System.out.println("Account no.: " + ac_no);
System.out.println("Account type:" + ac_name);
System.out.println("Balance: " + balance);
}
}
class UseAccount
{
public static void main(String args[])
{
Accounts ob = new Accounts();
ob.display();
ob.deposit(10000);
ob.display();
ob.withdrawal(500);
ob.display();
}
}

OUTPUT-

Q7.Write a program to implement constructor overloading.

CODING-
class Box
{
double width, height, depth;
Box()
{
width = height = depth = 0;
}

Box(double w, double h, double d)


{
width = w;
height = h;
depth = d;
}

Box(double len)
{
width = height = depth = len;
}

double volume()
{
return width * height * depth;
}
}

class overload_const
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box(20, 30, 25);
Box mybox3 = new Box(6);

double vol;

vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);

vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);

vol = mybox3.volume();
System.out.println(" Volume of mybox3 is " + vol);
}
}

OUTPUT-
Q8.Write a program to count the number of objects created in a program .

CODING-
class Count
{
static int noOfObjects = 0;

public Count()
{
noOfObjects += 1;
}

public static void main(String args[])


{
Count c1 = new Count();
Count c2 = new Count();
Count c3 = new Count();

System.out.println(Count.noOfObjects);
}
}

OUTPUT-

Q9.Write a program to implement Method Over ridding & Method


Overloading .
CODING-
Method Overloading-
class MethodOverload
{
void test()
{
System.out.println("No parameters");
}
void test(int a)
{
System.out.println("a: " + a);
}
void test(int a,int b)
{
System.out.println("a and b: "+ a + " " + b );
}
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
}
class UseOverload
{
public static void main(String args[])
{
MethodOverload ob = new MethodOverload();
double result;
ob.test();
ob.test(10);
ob.test(10,20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}

Method Overriding-

class A
{
int i,j;
A(int a, int b)
{
i=a;
j=b;
}
void show()
{
System.out.println("I ="+i+" J="+j);
}
}
class B extends A
{
int k;
B(int a,int b,int c)
{
super(a,b);
k=c;
}
void show()
{
super.show();
System.out.println("k="+k);
}
}
class Override
{
public static void main(String args[] )
{
B subob=new B(1,2,3);
subob.show();
}
}
Q10. Create a class box having height, width, depth as the instance variables
& calculate its volume. Implement constructor overloading in it. Create a
subclass named box_new that has weight as an instance variable. Use super in
the box_new class to initialize members of the base class.

CODING-
class Box
{
int height,width,depth;
Box()
{
height=width=depth=4;
}
Box(int h, int w,int d)
{
height=h;
width=w;
depth=d;
}
int volume()
{
return(height*width*depth);
}
}
class Box_new extends Box
{
int weight;
Box_new(int wei)
{
super();
weight=wei;
int vol1=volume();
System.out.println(" Volume1:"+ (vol1*weight));
}
Box_new(int h,int w, int d, int wei)
{
super(h,w,d);
weight=wei;
int vol2=volume();
System.out.println(" Volume2:"+ (vol2*weight));
}
}
class Box_value

{
public static void main(String args[])
{
Box_new b1= new Box_new(7);
Box_new b2= new Box_new(10,14,2,5);
}
}

OUTPUT-
Q11.Write a program to implement Run time polymorphism.

CODING-
class A
{
void Callme()
{
System.out.println("Inside A's Call me Method");
}
}
class B extends A
{
void Callme()
{
System.out.println("Inside B's Call me Method");
}
}
class C extends B
{
void Callme()
{
System.out.println("Inside C's Call me Method");
}
}
class Dispatch
{
public static void main(String args[])
{
A a=new A();
B b=new B();
C c=new C();
A r;
r=a;
r.Callme();
r=b;
r.Callme();
r=c;
r.Callme();
}
}
OUTPUT-
Q12. WAP to implement interface. Create an interface named Shape having
area () & perimeter () as its methods. Create three classes circle, rectangle &
square that implement this interface.

CODING-
interface Shape ​
{
float pi=3.14f;
float area();
float perimeter();
}
class Circle implements Shape
{
int radius=6;
public float perimeter()
{
return(2*pi*radius);
}
public float area()
{
return(pi*radius*radius);
}
}
class Rectangle implements Shape
{
int length=12;
int breadth=21;
public float perimeter()
{
return(2*(length+breadth));
}
public float area()
{
return(length*breadth);
}
}
class Square implements Shape
{
int side=18;
public float perimeter()
{
return(4*side);
}
public float area()
{
return(side*side);
}
}
class Test
{
public static void main(String args[])
{
Circle C1=new Circle();
Rectangle R1=new Rectangle();
Square S1=new Square();
Shape S;
S=C1;
System.out.println("Perimeter of Circle: "+S.perimeter());
System.out.println("Area of Circle: "+S.area());
S=R1;
System.out.println("Perimeter of Circle: "+S.perimeter());
System.out.println("Area of Circle: "+S.area());
S=S1;
System.out.println("Perimeter of Circle: "+S.perimeter());
System.out.println("Area of Circle: "+S.area());
}
}
OUTPUT-

Q13.Write a program to show multiple inheritance

CODING-
class Student
{
int rollno;
void getno(int n)
{
rollno=n;
}
void putno()
{
System.out.println("Roll number="+rollno);
}
}
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 sportswt=6.0F;
void putwt();
}
class Result extends Test implements sports
{
float total;
public void putwt()
{
System.out.println("Sports WT=" +sportswt);
}
void display()
{
total=part1 + part2 + sportswt;
putno();
putmarks();
putwt();
System.out.println("Total=" +total);
}
}
class MI
{
public static void main(String args[])
{
Result R=new Result();
R.getno(27);
R.getmarks(30.5F,33.0F);
R.display();
}
}

OUTPUT-

Q14. WAP to implement exception handling. Use try, catch & finally.

CODING-

class ExcepDemo
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("Finally block is always executed");
}
System.out.println("rest of the code...");
}
}

OUTPUT-

Q15.Create a user defined exception named “NoMatchException” that is fired


when the string entered by the user is not “India”.
CODING-

import java.util.*;
class NoMatchException extends Exception
{
NoMatchException(String msg)
{
super(msg);
}
}
class Demo
{
public static void main(String args[])
{
String str1="India";
try
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the name of Country:");
String str2=sc.next();
if(str2.equals(str1)==false)
{
throw new NoMatchException("You have entered wrong country name.");
}
else
{
System.out.println("Country Name is Valid");
}
}
catch(NoMatchException e)
{
System.out.println(e);
}
}
}
OUTPUT-

Q16. WAP to show even & odd numbers by thread.

CODING-
class PrintEvnOdd
{
public static void main(String args[])
{
Printer print = new Printer();
Thread t1 = new Thread(new TaskEvenOdd(print, 10, false));
Thread t2 = new Thread(new TaskEvenOdd(print, 10, true));
t1.start();
t2.start();
}
}

class TaskEvenOdd implements Runnable {


private int max;
private Printer print;
private boolean isEvenNumber;
TaskEvenOdd(Printer print, int max, boolean isEvenNumber) {
this.print = print;
this.max = max;
this.isEvenNumber = isEvenNumber;
}

public void run() {


int number = isEvenNumber == true ? 2 : 1;
while (number <= max) {
if (isEvenNumber) {
print.printEven(number);
} else {
print.printOdd(number);
}
number += 2;
}
}
}

class Printer {
boolean isOdd = false;
synchronized void printEven(int number) {
while (isOdd == false) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Even:" + number);
isOdd = false;
notifyAll();
}
synchronized void printOdd(int number) {
while (isOdd == true) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Odd:" + number);
isOdd = true;
notifyAll();
}
}

OUTPUT-
Q17. WAP that draws different color shapes on an applet .Set the foreground
& background color as red & blue.

CODING-

import java.awt.*;
import java.applet.*;
/*
<applet code="Setcolor" width=300 height=200>
</applet>
*/
public class Setcolor extends Applet
{
public void init()
{
setBackground(Color.blue);
setForeground(Color.red);
}
public void paint(Graphics g)
{
g.drawRect(10, 10, 60, 50);
g.fillRect(100, 10, 60, 50);
g.setColor(Color.cyan);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
g.fillRoundRect(70, 90, 140, 100, 30, 40);
}
}

OUTPUT-
Q18. WAP to show moving banner by applet.

CODING-

import java.awt.*;
import java.applet.*;
/*
<applet code="Movingbanner1" width=300 height=50>
</applet>
*/
public class Movingbanner1 extends Applet implements Runnable
{
String msg="A SIMPLE MOVING BANNER.";
Thread t =null;
boolean stopflag;
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
}
public void start()
{
t=new Thread(this);
stopflag= false;
t.start();
}
public void run()
{
char ch;
for(;;)
{
try
{
repaint();
Thread.sleep(250);
ch= msg.charAt(0);
msg=msg.substring(1,msg.length());
msg +=ch;
if(stopflag)
break;
}
catch(InterruptedException e)
{
}
}
}
public void stop()
{
stopflag= true;
t=null;
}
public void paint(Graphics g)
{
g.drawString(msg,50,30);
}
}
OUTPUT-
Q19. WAP to implement Matrix multiplication by 2D array.
CODING-
import java.util.Scanner;
class TwoDArray
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;
Scanner in = new Scanner(System.in);
System.out.println("Enter no. of rows & columns of 1st matrix:");
m = in.nextInt();
n = in.nextInt();
int first[][] = new int[m][n];
System.out.println("Enter elements of 1st matrix:");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
first[c][d] = in.nextInt();
System.out.println("Enter no. of rows & columns of 2nd matrix");
p = in.nextInt();
q = in.nextInt();
if (n != p)
System.out.println("The matrices can't be multiplied with each other.");
else{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
System.out.println("Enter elements of 2nd matrix:");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
second[c][d] = in.nextInt();
for (c = 0; c < m; c++)
{
for (d = 0; d < q; d++)
{
for (k = 0; k < p; k++)
{
sum = sum + first[c][k]*second[k][d];
}

multiply[c][d] = sum;
sum = 0;
}
}
System.out.println("Product of the matrices:");
for (c = 0; c < m; c++)
{
for (d = 0; d < q; d++)
System.out.print(multiply[c][d]+"\t");
System.out.print("\n");
}
}
}
}
OUTPUT-

Q20. WAP to demonstrate the use of equals(), trim() ,length() , substring(),


compareTo() of String class.

CODING-
class Strings
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +s1.equals(s3));
String str1 = "Java";
System.out.println("Length of the String is: "+str1.length());
String tr1 = " HELLO WORLD ";
System.out.println("Before trim:"+tr1);
System.out.println("After trim:"+tr1.trim());
String sub1= "Substring";
System.out.println("Substring :"+sub1.substring(1,5));
String com1 = "java programming";
String com2 = "java programming";
String com3 = "Object Oriented Language";
System.out.println(com1.compareTo(com2));
System.out.println(com1.compareTo(com3));
System.out.println(com3.compareTo(com1));
}
}
OUTPUT-

Q21. WAP to implement file handling(both reading & writing to a file).


FileWriter

CODING-

import java.io.FileWriter;
import java.io.IOException;
class CreateFile
{
public static void main(String[] args) throws IOException
{
String str = "File Handling in Java using "+
" FileWriter and FileReader";
FileWriter fw=new FileWriter("output.txt");
for (int i = 0; i < str.length(); i++)
fw.write(str.charAt(i));
System.out.println("Writing successful");
fw.close();
}
}

OUTPUT-

CODING-
FileReader

import java.io.*;
class FileReaderDemo
{
public static void main(String args[]) throws IOException
{
FileReader fr = new FileReader("output.txt");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
}
OUTPUT-

Q22. WAP to implement all mouse events and mouse motion events.

CODING-
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet implements MouseListener, MouseMotionListener
{
String msg = "";
int mouseX = 0, mouseY = 0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
public void mouseEntered(MouseEvent me)
{
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
public void mouseExited(MouseEvent me)
{
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
public void mousePressed(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint(); ​
}
public void mouseReleased(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
public void mouseDragged(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
public void mouseMoved(MouseEvent me)
{
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}

OUTPUT-
Q23.WAP to implement keyboard events.

CODING-
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Keyboardevents" width=300 height=50>
</applet>
*/
public class Keyboardevents extends Applet implements KeyListener
{
String msg = "";
int X = 10, Y = 20;
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}
OUTPUT-

Q24. WAP using AWT to create a simple calculator.


CODING-

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="cal" width=250 height=70>
</applet>
*/
public class cal extends Applet implements
ActionListener
{

Button add, sub, mul, div,clr;


TextField t1,t2,t3;
public void init()
{
Label num1 = new Label("1st No.:",Label.RIGHT);
Label num2 = new Label("2nd No.:",Label.RIGHT);
Label result = new Label("Result:",Label.RIGHT);
t1 = new TextField();
t2= new TextField();
t3 = new TextField();
add = new Button("ADD");
sub = new Button("SUBTRACT");
mul = new Button("MULTIPLY");
div = new Button("DIVIDE");
clr = new Button("CLEAR");
add(num1);
add(t1);
add(num2);
add(t2);
add(result);
add(t3);
add(add);
add(sub);
add(mul);
add(div);
add(clr);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
clr.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
int n1=Integer.parseInt(t1.getText());
int n2=Integer.parseInt(t2.getText());
if(ae.getSource()==add)
​{
​ ​t3.setText(String.valueOf(n1+n2));
​} ​ ​
​if(ae.getSource()==sub)
​{
​ ​t3.setText(String.valueOf(n1-n2));
​} ​
​if(ae.getSource()==mul)
​{
​ ​t3.setText(String.valueOf(n1*n2));
​}
​if(ae.getSource()==div)
​{
​ ​t3.setText(String.valueOf(n1/n2));
}​
if(ae.getSource()==clr)
{
t1.setText(" ");
t2.setText(" ");
t3.setText(" ");
} ​ ​ ​
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 6, 100);
}

OUTPUT-
Q25. Create a login form using AWT controls like labels, buttons, textboxes,
checkboxes, list, checkboxgroup. The selected checkbox item names should be
displayed.

CODING-
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="LoginForm" width=610 height=150>
</applet>
*/
public class LoginForm extends Applet implements ActionListener,ItemListener
{
List lang;
TextField n, p;
Button b1;
String msg="";
String msg1="";
Checkbox bca, btech,mca;
CheckboxGroup cbg;
public void init()
{
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
Label Lang1 = new Label("Select languages:",Label.LEFT);
n = new TextField(12);
p = new TextField(8);
lang = new List(4,true);
b1 = new Button("OK");
cbg = new CheckboxGroup();
bca = new Checkbox("BCA", cbg, true);
btech = new Checkbox("B.tech", cbg, false);
mca = new Checkbox("MCA", cbg, false);
p.setEchoChar('?');
add(namep);
add(n);
add(passp);
add(p);
add(Lang1);
lang.add("C++");
lang.add("Java");
lang.add("C#");
lang.add("Python");
add(lang);
add(bca);
add(btech);
add(mca);
add(b1);
n.addActionListener(this);
p.addActionListener(this);
lang.addActionListener(this);
bca.addItemListener(this);
btech.addItemListener(this);
mca.addItemListener(this);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str= ae.getActionCommand();
if(str.equals("OK"))
{
msg1 = "Login OK.";
}
repaint();
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 6, 100);
g.drawString(msg1, 6, 140);
}
}

OUTPUT-
26. WAP to show Border Layout manager.
1. BoxLayout
2. CardLayout

CODING-
import java.awt.*;
import javax.swing.*;
/*
<applet code="Cardlayout1" width=300 height=200>
</applet>
*/
public class Cardlayout1 extends JApplet {
JButton b1,b2,b3;
CardLayout c1;
JPanel P1;
public void init()
{
P1=new JPanel();
c1=new CardLayout();
P1.setLayout(c1);
getContentPane().add(P1);
b1=new JButton("BUTTON 1");
b2=new JButton("BUTTON 2");
b3=new JButton("BUTTON 3");
P1.add("BUTTON 1",b1);
P1.add("BUTTON 2",b2);
P1.add("BUTTON 3",b3);
}
}
OUTPUT-

Q27. WAP to show Grid Layout manager.

CODING-
import java.awt.*;
import javax.swing.*;
/*
<applet code="Gridlayout1" width=300 height=200>
</applet>
*/
public class Gridlayout1 extends JApplet
{
JButton b1,b2,b3,b4,b5,b6;
GridLayout g1;

public void init()


{
g1=new GridLayout(3,3);
JPanel P1=new JPanel();
getContentPane().add(P1);
P1.setLayout(g1);

b1=new JButton("Button 1");


b2=new JButton("Button 2");
b3=new JButton("Button 3");
b4=new JButton("Button 4");
b5=new JButton("Button 5");
b6=new JButton("Button 6");

P1.add(b1);
P1.add(b2);
P1.add(b3);
P1.add(b4);
P1.add(b5);
P1.add(b6);

}
}

OUTPUT-
Q28. WAP to show Flow Layout managers.

CODING-

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Flowlayout" width=250 height=200>
</applet>
*/
public class Flowlayout extends Applet
implements ItemListener {
String msg = "";
Checkbox winXP, winVista, solaris, mac;
public void init()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
add(winXP);
add(winVista);
add(solaris);
add(mac);

winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}

public void itemStateChanged(ItemEvent ie) {


repaint();
}

public void paint(Graphics g) {


msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac: " + mac.getState();
g.drawString(msg, 6, 160);
}
}

OUTPUT-
Q29. WAP to show Border Layout manager.

CODING-
import java.awt.*;
import javax.swing.*;
/*
<applet code="Borderlayout1" width=300 height=200>
</applet>
*/
public class Borderlayout1 extends JApplet
{
JButton b1,b2,b3,b4,b5;
BorderLayout bd1;
public void init()
{
bd1=new BorderLayout();
JPanel P1=new JPanel();
getContentPane().add(P1);
P1.setLayout(bd1);
b1=new JButton("This is across the Top");
b2=new JButton("This footer message might go here");
b3=new JButton("Right");
b4=new JButton("Left");
b5=new JButton("Center");
P1.add(BorderLayout.NORTH,b1);
P1.add(BorderLayout.SOUTH,b2);
P1.add(BorderLayout.EAST,b3);
P1.add(BorderLayout.WEST,b4);
P1.add(BorderLayout.CENTER,b5);
}
}

OUTPUT-
Q30. Create a simple JDBC program that creates a table, stores data into it,
retrieves & prints the data.

Q31. Create an Applet with two buttons named ‘Audio’ and ‘Image’.
When user will press button ‘audio’ then an audio file should play in applet,
and if user press button ‘Image’ then an image should see in applet window.
CODING-
/*
* <applet code="ImageLoad" width=255 height=300>
* <param name="img" value="musicimg.jpg">
* </applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ImageLoad extends Applet implements ActionListener
{
Button b1,b2;
Image img;
public void init()
{
b1 = new Button("IMAGE");
b2 = new Button("AUDIO");
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
{
img = getImage(getDocumentBase(), getParameter("img"));
}
if(ae.getSource()==b2)
{
AudioClip aud = getAudioClip(getDocumentBase(), "ATone.wav");
aud.play();
}
repaint();
}
public void paint(Graphics g)
{
g.drawImage(img, 0, 0, this);
}
}

OUTPUT-
Q32.WAP in Java to demonstrate the application of RMI (Remote Method
Invocation).
CODING-
AddServerIntf
import java.rmi.*;
public interface AddServerIntf extends Remote
{
double add(double d1, double d2) throws RemoteException;
}

AddServerImpl
import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject
implements AddServerIntf
{
public AddServerImpl() throws RemoteException {
}
public double add(double d1, double d2) throws RemoteException
{
return d1 + d2;
}
}

AddServer
import java.net.*;
import java.rmi.*;
public class AddServer
{
public static void main(String args[])
{
try
{
AddServerImpl addServerImpl = new AddServerImpl();
Naming.rebind("AddServer", addServerImpl);
}
catch(Exception e)
{
System.out.println("Exception:" + e);
}
}
}
AddClient
import java.rmi.*;
public class AddClient
{
public static void main(String args[])
{
try {
String addServerURL = "rmi://" + args[0] + "/AddServer";
AddServerIntf addServerIntf =(AddServerIntf)Naming.lookup(addServerURL);
System.out.println("The first number is: " + args[1]);
double d1 = Double.valueOf(args[1]).doubleValue();
System.out.println("The second number is: " + args[2]);
double d2 = Double.valueOf(args[2]).doubleValue();
System.out.println("The sum is: " + addServerIntf.add(d1, d2));
}
catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}
OUTPUT-

Q33. Create a Java applet with three buttons ‘Red’,’Green’,’Blue’. Whenever


user press any button the corresponding color should be seen as background
color in an applet window.

CODING-

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Color1" height=150 width=200></applet>*/
public class Color1 extends Applet implements ActionListener
{
Button b1,b2,b3;
public void init()
{
b1=new Button("RED");
b2=new Button("BLUE");
b3=new Button("GREEN");
add(b1);
add(b2);
add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("RED"))
setBackground(Color.red);
else if(str.equals("GREEN"))
setBackground(Color.green);
else if(str.equals("BLUE"))
setBackground(Color.blue);
}
}

OUTPUT-
Q34. WAP in java to implement the concept of ‘synchronization’ using thread.

CODING-

class Callme
{
void call(String msg)
{ System.out.print("[" + msg);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("Interrupted");
}
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();
}
public void run()
{ synchronized(target)
{
target.call(msg);
}
}
}
class Synch2
{
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");
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}

OUTPUT-

You might also like