Vous êtes sur la page 1sur 60

# BSC III-Year V-Semester (OU) Programming in JAVA

## 1Q: Write java program to find the following,

(a) Largest of given three numbers.
Program:
import java.io.*;
import java.util.*;
public class NestedExample
{
public static void main(String[] args)
{
int a, b, c;
a=7;
b=8;
c=9;
if(a>b)
{
if(a>c)
{
System.out.println("a is greater");
}
else
{
System.out.println("c is greater");
}
}
else
{
if(b>c)
{
System.out.println("b is greater");
}
else
{
System.out.println("c is greater");
}
}
}
}
Output:

1
BSC III-Year V-Semester (OU) Programming in JAVA

## (b) Reverse the digits of a number.

Program:
import java.io.*;
public class Reverse
{
public static void main(String[] args)
{
int n=725,rev=0;
while(n!=0)
{
int digit=n%10;
rev=rev*10+digit;
n/=10;
}
System.out.println("Reversed Number:"+rev);
}
}
Output:

## (c) Given number is not a prime or not.

Program:
import java.io.*;
class Prime
{
public static void main(String[] args)
{
int n=121;
boolean flag=false;
for(int j=2;j<=n/2;++j)
{
if(n%j==0)
{
flag=true;
break;

2
BSC III-Year V-Semester (OU) Programming in JAVA

}
}
if(!flag)
System.out.println(n+"is a prime number.");
else
System.out.println(n+"is not a prime number.");
}
}
Output:

## (d) GCD of given two integers.

Program:
import java.io.*;
public class GCD
{
public static void main(String[] args)
{
int a=24,b=8,r;
while(b!=0)
{
r=a%b;
a=b;
b=r;
}
System.out.println("G.C.D of two numbers is="+b);
}
}
Output:

3
BSC III-Year V-Semester (OU) Programming in JAVA

## 2) Write a java program that implements the following

(a) Default constructor.
Program:
import java.io.*;
class Fruits
{
public Fruits()
{
System.out.println("This is a default constructor");
}
public static void main(String args[])
{
Fruits f=new Fruits();
}
}
Output:

## (b) Parameterized constructor.

Program:
import java.io.*;
class Square
{
int side;
Square(int s)
{
side=s;
}
}
class Demo
{
public static void main(String args[])
{
Square sq=new Square(20);
System.out.println("Side of Square:"+sq.side);

4
BSC III-Year V-Semester (OU) Programming in JAVA

}
}

Output:

Program:
import java.io.*;
class Box
{
double width, height, depth;
Box(double w, double h, double d)
{
width=w;
height=h;
depth=d;
}
Box()
{
width=-1;
height=-1;
depth=-1;
}
Box(double 1)
{
width=height=depth=1;
}
double volume()
{
return width*height*depth;
}
}

5
BSC III-Year V-Semester (OU) Programming in JAVA

{
public static void main(String args[])
{
Box b1=new Box(10,20,30);
Box b2=new Box();
Box b3=new Box(7);
double vol;
vol=b1.volume();
System.out.println("B1 volume:" +vol);
vol=b2.volume();
System.out.println("B2 volume:" +vol);
vol=b3.volume();
System.out.println("B3 volume:" +vol);
}
}
Output:

6
BSC III-Year V-Semester (OU) Programming in JAVA

3Q: (a) Write a java program to find the smallest of given list integers using
arrays and scanner class.
Program:
import java.io.*;
import java.util.Scanner;
class Smallest
{
public static void main(String args[])
{
int arr[]=new int[5];
int x,j;
Scanner elem=new Scanner(System.in);
System.out.println("Enter any five elements:");
for(j=0;j<5;j++)
arr[j]=elem.nextInt();
x=arr[0];
for(j=0;j<5;j++)
{
if(x<arr[j])
continue;
else
x=arr[j];
}
System.out.println("The Smallest value in the given list of arrays is:"+x);
}
}

Output:

7
BSC III-Year V-Semester (OU) Programming in JAVA

## (b) Write a java program for Multiplication of two matrices.

Program:
Import java.io.*;
public class Multiplication
{
Public static void main(String args[])
{
int[][] x={{1,2,3},{4,5,6},{7,8,9}};
int[][] y={{9,8,7},{6,5,4},{3,2,1}};
int[][] z=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
for(int k=0;k<3;k++)
{
z[i][j]=z[i][j]+x[i][k]*y[k][j];
}
}
}
System.out.println(“The Multiplication of two matrices is:”);
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.println(z[i][j]+ “ ”);
}
System.out.println();
}
}
}
Output:

8
BSC III-Year V-Semester (OU) Programming in JAVA

4Q: (a) Write a java program for demonstrating an inner classes or nested
classes.
Program:
My_class.java
import java.io.*;
class Outer
{
int n;
private class Inner
{
public void print( )
{
System.out.println("This is an inner class");
}
}
void display( )
{
Inner i=new Inner( );
i.print( );
}
}
public class My_class
{
public static void main(String args[])
{
Outer o=new Outer( );
o.display( );
}
}
Output:

9
BSC III-Year V-Semester (OU) Programming in JAVA

overriding, Dynamic method dispatch.
Program:
import java.io.*;
class Method
{
void Sum(int x,int y)
{
int res=x + y;
System.out.println(“Sum:” + res);
}
void Sum(double x, double y)
{
double res=x + y;
System.out.println(“Sum:”+res);
}
}
class Example
{
public static void main(String args[ ])
{
Method m=new Method( );
m.Sum(5,9);
m.Sum(3,7,4.2);
}
}
Output:

10
BSC III-Year V-Semester (OU) Programming in JAVA

Method overriding
Program:
import java.io.*;
import java.util.*;
class Baseclass
{
final void display( )
{
System.out.println("Hello");
}
}
class Derivedclass extends Baseclass
{
void display()
{
System.out.println("Welcome");
}
}
Output:

11
BSC III-Year V-Semester (OU) Programming in JAVA

## Dynamic Method dispatch

Program:
import java.io.*;
class Organization
{
public void type( )
{
System.out.println("Govt & private");
}
}
class Bsnl extends Organization
{
public void type( )
{
System.out.println("Govt");
}
public static void main(String[] args)
{
Organization o=new Organization( );
Bsnl b=new Bsnl( );
o.type( );
b.type( );
o=b;
o.type( );
}
}
Output:

12
BSC III-Year V-Semester (OU) Programming in JAVA

## 5Q: Write a java program to implement Single, Multilevel, Hierarical,

Multiple, Hybrid Inheritances.
Single Inheritance:
Program:
import java.io.*;
class Shape
{
public int side=10;
}
class Square extends Shape
{
void area()
{
int area=side*side;
System.out.println("Area of square:"+area);
}
}
class InheritanceDemo
{
public static void main(String[] args)
{
Square s=new Square();
s.area();
}
}

Output:

13
BSC III-Year V-Semester (OU) Programming in JAVA

Multilevel inheritance
Program:
import java.io.*;
import java.util.*;
class Student
{
String sname="John";
int sid=101;
}
class Department extends Student
{
String dept="IT";
}
class Marks extends Department
{
int sub1=50,sub2=80,sub3=40;
void total()
{
int total=sub1+sub2+sub3;
}
void display()
{
System.out.println("student name:" +sname+ "\n student id:"+ "\n
Department:" +dept+ "\n Marks of subject1:"+sub1+ "\n Marks of
subject2:"+sub2+ "\n Marks of subject3:" +sub3);
}
}
class Multilevel
{
public static void main(String args[])
{
Marks m=new Marks();
m.total();
m.dispaly();
}
}
Output:

14
BSC III-Year V-Semester (OU) Programming in JAVA

Hirerarchical inheritance
Program:
import java.io.*;
import java.util.*;
class Student
{
void Display1()
{
System.out.println("I am a Student");
}
}
class dept extends Student
{
void Display2()
{
System.out.println("I belongs to CSE");
}
}
class sid extends Student
{
void Display3()
{
System.out.println("My id is 101");
}
}
class MainClass1
{
public static void main(String args[])
{
System.out.println("Calling for subclass C");
sid s=new sid();
s.Display1();
s.Display3();
System.out.println("Calling for subclass B");
dept d=new dept();
d.Display1();
d.Display2();
}
}
Output:

15
BSC III-Year V-Semester (OU) Programming in JAVA

Multiple Inheritance
Program:
import java.io.*;
import java.util.*;
interface Test
{
public abstract void display();
}
interface Hello
{
public abstract void show();
}
public class MultipleDemo implements Test,Hello
{
public void display()
{
System.out.println("Hello 1");
}
public void show()
{
System.out.println("Hello 2");
}
public static void main(String args[])
{
MultipleDemo md=new MultipleDemo();
md.display();
md.show();
}
}
Output:

16
BSC III-Year V-Semester (OU) Programming in JAVA

Hybrid Inheritance
Program:
import java.io.*;
class P
{
public void show()
{
System.out.println("Good Morning");
}
}
class Q extends P
{
public void show()
{
System.out.println("Good Afternoon");
}
}
class R extends P
{
public void show()
{
System.out.println("Good Evening");
}
}
class S extends Q
{
public void show()
{
System.out.println("Good Night");
}
public static void main(String args[])
{
S o=new S();
o.show();
}
}
Output:

17
BSC III-Year V-Semester (OU) Programming in JAVA

6Q: Write java programs that demonstrate the use of abstract, this, super,
static, final Keywords.
Abstract Keyword
Program:
import java.io.*;
import java.util.*;
abstract class Baseclass
{
abstract void display();
}
class Derivedclass extends Baseclass
{
void display()
{
System.out.println("Derivedclass");
}
}
class Demo2
{
public static void main(String args[])
{
Derivedclass dc=new Derivedclass();
dc.display();
}
}
Output:

18
BSC III-Year V-Semester (OU) Programming in JAVA

Super Keyword
(i)‘Super’ Keyword to call the Super class Constructor.
Program:
import java.io.*;
class A
{
private double width, height, depth;
A(double w, double h, double d)
{
width=w;
height=h;
depth=d;
}
double volume()
{
return width*height*depth;
}
}
class B extends A
{
double weight;
B(double w, double h, double d, double m)
{
super(w,h,d);//calls superclass Constructor
weight=m;
}
}
class FirstUse
{
public static void main(String args[])
{
B b=new B(20.5,10.2,15.1,50.6);
System.out.println("volume is:"+b.volume());
}
}
Output:

19
BSC III-Year V-Semester (OU) Programming in JAVA

## (ii) ‘Super’ Keyword to Access Class Members.

Program:
import java.io.*;
class A
{
int x;
void show()
{
System.out.println("This is superclass method");
}
}
class B extends A
{
int x;
B(int a, int b)
{
super.x=a;
x=b;
}
void show()
{
super.show();
System.out.println("This is subclass method");
System.out.println("x in superclass:"+super.x);
System.out.println("x in subclass:"+x);
}
}
class SecondUse
{
public static void main(String args[])
{
B b=new B(10,20);
b.show();
}
}
Output:

20
BSC III-Year V-Semester (OU) Programming in JAVA

## (iii) ‘Super’ Keyword to Call Methods of Superclass.

Program:
class RED
{
void display()
{
System.out.println("Superclass display method");
}
}
class BLUE extends RED
{
void display()
{
super.display();
System.out.println("Subclass display method");
}
public static void main(String args[])
{
BLUE b=new BLUE();
b.display();
}
}

Output:

21
BSC III-Year V-Semester (OU) Programming in JAVA

Static Keyword
Program:
class StaticExample
{
static int i=10;
static int j;
static
{
System.out.println("Static variable initialization.");
j=i*4;
}
public static void main(String[]args)
{
System.out.println("from main");
System.out.println("The Value of i is :"+i);
System.out.println("The Value of j is :"+j);
}
}

Output:

22
BSC III-Year V-Semester (OU) Programming in JAVA

Final Keyword
Program:
import java.io.*;
class example
{
final double r=4.5f;
final void area()
{
double a=3.14*r*r;
System.out.println("Area of circle:"+ a);
}
}
class circle extends example
{
public static void main(String args[])
{
circle c=new circle();
c.area();
}
}

Output:

23
BSC III-Year V-Semester (OU) Programming in JAVA

7Q: (a) Write a java program for creating package and using a package.
Program:
package mypack1;
import java.io.*;
public class Student
{
public static void main(String args[])
{
System.out.println(“Welcome to package program”);
}
}

Output:

24
BSC III-Year V-Semester (OU) Programming in JAVA

## b) Write a java program to demonstrate the use of wrapper class.

Program:
Import java.io.*;
Import java.util.*;
class WrapperExample
{
public static void main(String[] args)throws IOException
{
byte x=10;
float y=25.07f;
double z=4654321.68;
Byte r=new Byte(x);
Float f=new Float(y);
Double d=new Double(z);
System.out.println("Byte to Int value" + r.intValue());
System.out.println("Float to Int value" + f.intValue());
System.out.println("Double to Long value" + d.longValue());
}
}

Output:

25
BSC III-Year V-Semester (OU) Programming in JAVA

## 8Q (a) Write a java program using all keywords of exception handiling

mechanism.
Program:
import java.io.*;
public class MultipleExceptions
{
public static void main(String[] args)
{
try
{
MultipleExceptions.checkPass("pwd");
}
catch (NoPassException e1)
{
e1 .printStackTrace();
}
catch(ShortPassException e1)
{
e1.printStackTrace();
}
finally
{
System.out.println("Finally block is eventually executed");
}
try
{
MultipleExceptions.checkPass(null);
}
catch(NoPassException e1)
{
e1.printStackTrace();
}
catch(ShortPassException e1)
{
e1.printStackTrace();
}
finally
{
System.out.println("Finally block is eventually executed");
}

26
BSC III-Year V-Semester (OU) Programming in JAVA

try
{
MultipleExceptions.checkPass("787974");
}
catch(NoPassException e1)
{
e1.printStackTrace();
}
catch(ShortPassException e1)
{
e1.printStackTrace();
}
finally
{
System.out.println("Finally block is eventually executed");
}
}
public static void checkPass(String pwd)throws
NoPassException,ShortPassException
{
int size=5;
if(pwd==null)
throw new NoPassException("No password is given");
if(pwd.length()<size)
throw new ShortPassException("The password provided is very short");
}
}
class NoPassException extends Exception
{
NoPassException()
{
}
NoPassException(String msg)
{
super(msg);
}
NoPassException(String msg,Throwable reason)
{
super(msg,reason);

27
BSC III-Year V-Semester (OU) Programming in JAVA

}
}
class ShortPassException extends Exception
{
ShortPassException()
{
String msg;
}
ShortPassException(String msg)
{
super(msg);
}
ShortPassException(String msg,Throwable reason)
{
super(msg,reason);
}
}

Output:

28
BSC III-Year V-Semester (OU) Programming in JAVA

## (b) Write a java program for creating customized (user)Exception.

Program:
class MyException extends Exception
{
int x;
MyException(int i)
{
x=i;
}
public String toString()
{
return "MyException" +x+ " ";
}
}
public class UserDefinedExample
{
static void calculate(int i) throws MyException
{
System.out.println("Calculate" +i);
if(i>20)
{
throw new MyException(i);
}
System.out.println("Terminate");
}
public static void main(String[] args)
{
try
{
calculate(10);
calculate(35);
}
catch(MyException ex)
{
System.out.println("An exception" +ex+ "caught");
}
}
}
Output:

29
BSC III-Year V-Semester (OU) Programming in JAVA

9) (a) Write a java program that check whether a given string is palindrome
or not.
Program:
import java.io.*;
class Palindrome
{
public static void main(String args[])
{
StringBuffer S2;
System.out.println(“String=” +S1);
S2=S1.reverse();
if(S1.equals(S2)==true)
System.out.println("String is a Palindrome");
else
System.out.println("String is not a Palindrome");
}
}
Output:

30
BSC III-Year V-Semester (OU) Programming in JAVA

(b) Write a java program for sorting a given list of names is ascending order.
Program:
import java.io.*;
import java.util.*;
class Sorting
{
static String names[]={"PINKY","NANDY","CHAITU","NETRA"," SHONA"};
public static void main(String args[])
{
int len=names.length;
String tmp=null;
for(int i=0;i<len;i++)
{
for(int k=i+1;k<len;k++)
{
if(names[k].compareTo(names[i])<0)
{
tmp=names[i];
names[i]=names[k];
names[k]=tmp;
}
}
}
for(int i=0;i<len;i++)
{
System.out.println(names[i]);
}
}
}
Output:

31
BSC III-Year V-Semester (OU) Programming in JAVA

10Q: (a) Write a java program to create a file, write the data and display the
data.
Program:
import java.io.*;
import java.io.IOException;
import java.io.FileWriter;
public class Main2
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter("C:/mydir/text2.txt");
fw.write("Welcome to SIA");
fw.close();
FileInputStream fis=new FileInputStream("C:/mydir/text2.txt");
int ch;
{
System.out.print((char) ch);
}
isr.close();
}
catch (IOException e)
{
e.printstack Trace():
}
}
}
Output:

32
BSC III-Year V-Semester (OU) Programming in JAVA

(b) Write a java program that reads a file name from user and display the
data.
Program:
import java.io.*;
class UsingFile
{
public static void main(String args[])throws IOException
{
String s;
File f=new File("c:/mydir/text.txt");
s=f.exists()?"File exists" : "file does not exist";
System.out.println(s);
s=f.isFile( )?"Is a normal file" : "Is a special file";
System.out.println(s);
File f1=new File("c:/mydir/subdir");
f1.mkdir( );
if(f1.isDirectory( ))
{
System.out.println("Directory name:"+f1.getName( ))
System.out.println("Directory contents:");
String str[ ]=f1.list( );
if(str.length==0)
System.out.println("Directory is empty");
else
for(int i=0;i<str.length;i++)
System.out.println(str[i]);
}
else
System.out.println('Is not a directory");
}
}
Output:

33
BSC III-Year V-Semester (OU) Programming in JAVA

## 11Q: (a) Write a java program for controlling main thread.

Program:
import java.io.*;
{
public static void main(String args[])
{
//change the name of the thread
try
{
for(int i=5; i>0; i--)
{
System.out.println(i);
}
}catch(InterruptedException e)
{
}
}
}
Output:

34
BSC III-Year V-Semester (OU) Programming in JAVA

(b) Write a java program for creating a new thread by extending thread class.
Program:
import.java.io.*;
{
public void run()
{
}
public static void main(String args[])
{
th1.start();
}
}

Output:

35
BSC III-Year V-Semester (OU) Programming in JAVA

## 12Q: (a)Write a java program for creating a new thread by implementing

Runnable interface.
Program:
import java.io.*;
{
public void run()
{
System.out.println("The thread is created using runnable interface”);
}
public static void main(String args[])
{
th1.start();
}
}

Output:

36
BSC III-Year V-Semester (OU) Programming in JAVA

## (b) Write a java program for thread synchronization.

Program:
import java.io.*;
import java.util.*;
class First
{
synchronized void call(String str)
{
System.out.println("["+str);
try
{
}
catch(InterruptedException ie)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Second implements Runnable
{
String str;
First f;
public Second(First fir,String S)
{
f=fir;
str=S;
t.start();
}
public void run()
{
f.call(str);
}
}
class SynchDemo
{
public static void main(String args[])

37
BSC III-Year V-Semester (OU) Programming in JAVA

{
First f=new First();
Second s1=new Second(f,"SIA");
Second s2=new Second(f,"GROUP");
Second s3=new Second(f,"COMPANY");
try
{
s1.t.join();
s2.t.join();
s3.t.join();
}
catch(InterruptedException ie)
{
System.out.println("interrupted");
}
}
}
Output:

38
BSC III-Year V-Semester (OU) Programming in JAVA

## 13Q: (a) Write a java program to create following AWT components:

Button, checkbox, choice and list.
Program:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Buttons" width=200 height=100>
</applet>
*/
public class Buttons extends Applet implements ActionListener
{
String msg =" ";
Button a, b, c;
public void init()
{
c=new Button("Taj Uddin");
}
public void actionperformed(ActionEvent ae)
{
String s=ae.getActionCommand();
{
}
{
}
else
{
msg="U pressed Taj Uddin";

39
BSC III-Year V-Semester (OU) Programming in JAVA

}
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,6,100);
}
}

Output:

40
BSC III-Year V-Semester (OU) Programming in JAVA

Check box
Program:
import java.awt.*;
import java.applet.*;
/*
<APPLET Code="CheckboxTest"Width=500 Height=200>
</APPLET>
*/
public class CheckboxTest extends Applet
{
public void init()
{
/*The statement creates an object and adds the checkbox on the applet.*/
Checkbox chkbx1, chkbx2, chkbx3;
chkbx1=new Checkbox("Checkbox 1");
chkbx2=new Checkbox("Checkbox 2", true);//This checkbox is checked
chkbx3=new Checkbox("Checkbox 3");
}
}
Output:

41
BSC III-Year V-Semester (OU) Programming in JAVA

Choice
Program:
import java.applet.Applet;
import java.awt.Choice;
/*
<applet code="ChoiceExample"width=200 height=200>
</applet>
*/
import java.applet.Applet;
import java.awt.Choice;
public class ChoiceExample extends Applet
{
public void init()
{
Choice c=new Choice();
}
}

Output:

42
BSC III-Year V-Semester (OU) Programming in JAVA

List
Program:
import java.awt.*;
import java.applet.*;
/*
<APPLET code="CountryList"Width=500 Height=200>
</APPLET>
*/
public class CountryList extends Applet
{
List lst=new List(5,true);
public void init()
{
}
}
Output:

43
BSC III-Year V-Semester (OU) Programming in JAVA

(b) Write java programs to create AWT application using containers and
layouts.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.Frame;
/*
<applet code="AppletFrame" width=400 height=60>
</applet>
*/
Class Sample extends Frame
{
Sample(String title)
{
super(title);
}
public void paint(Graphics gr)
{
gr.drawString(“This is shown in an Frame Window”,30,40);
}
}
{
Sample sam;
{
this.sam = sam;
}
public void windowClosing(WindowEvent w)
{
sam.setVisible(false);
}
}
public class AppletFrame extends Applet
{
Frame fr;
public void init()

44
BSC III-Year V-Semester (OU) Programming in JAVA

{
fr=new Sample(“This is a Frame Window”);
fr.setSize(300,200);
fr.setVisible(true);
}
public void start()
{
fr.setVisible(true);
}
public void stop()
{
fr.setVisible(false);
}
public void paint(Graphics gr)
{
gr.drawString(“This is Shown in an Applet Window”,10,20);
}
}
Output:

FlowLayout
Program:
import java.awt.*;
import java.applet.Applet;
/*
<applet code = “FlowLayout” width=300 height=200>
</applet>
*/
public class FlowLayout extends Applet
{
Button b1,b2,b3,b4;
public void init()
{
b1= new Button(“Button1”);

45
BSC III-Year V-Semester (OU) Programming in JAVA

## b2= new Button(“Button2”);

b3= new Button(“Button3”);
b4= new Button(“Button4”);
}
}
Output:

BorderLayout
Program:
import java.awt.*;
import java.awt.BorderLayout;
import java.applet.*;
import java.util.*;
/*
<applet code=”BoderLayoutDemo” width=500 height=250>
</applet>
*/
public class BorderLayoutDemo extends Applet
{
public void init()
{
setLayout(new BorderLayout());
}

46
BSC III-Year V-Semester (OU) Programming in JAVA

}
Output:

CardLayout
Program:
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.CardLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.ActionListener;
/*
<applet code=”CardLayoutDemo” width=300 height=300></applet>
*/
Public class CardLayoutDemo extends Applet
{
CardLayout c;
Panel p;
Button b;
Int n=0;
final int num = 4;
String values[]=new String[num];
public void init()
{
p=new Panel();
c=new CardLayout();
b=new Button(“Next”);
{
public void actionPerformed(ActionEvent ae)
{
if(++n>=num)

47
BSC III-Year V-Semester (OU) Programming in JAVA

n=0;
c.show(p,vlues[n]);
}
});
values[0]=”Card-1”;
values[1]=”Card-2”;
values[2]=”Card-3”;
values[3]=”Card-4”;
p.setLayout(c);
for(int i=0;i<num;i++)
c.show(p,values[0]);
setLayout(new BorderLayout());
}
}
Output:

GridLayout
Program:
import java.awt.*;
import java.applet.Applet;
/*
<applet code=”GridLayoutDemo” width=300 height=300></applet>
*/
public class GridLayoutDemo extends Applet
{
public void init()

48
BSC III-Year V-Semester (OU) Programming in JAVA

{
setLayout(new GridLayout(2,2));
}
}
Output:

GridBagLayout
Program:
import java.awt.*;
import java.util.*;
import java.applet.Applet;
/*
<applet code=“GridBagDemo” width=“300” height=“350”>
</applet>
*/
public class GridBagDemo extends Applet
{
protected void makebutton(String text, GridBagLayout gridbag,
GridBagConstraints c)
{
Button b=new Button(text);
gridbag.setConstraints(b,c);
}
public void init()
{
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();

49
BSC III-Year V-Semester (OU) Programming in JAVA

setFont(new Font(“Helvetica”,Font.PLAN,14));
setLayout(gridbag);
c.fill = GridBagConstraints.BOTH;
c.weightx=1.0;
makebutton(“Colors”,gridbag,c);
c.gridwidth= GridBagConstraints.REMAINDER;
makebutton(“Fruits”,gridbag,c);
c.weightx=0.0;
makebutton(“Vegetables”,gridbag,c);
c.gridwidth= GridBagConstraints.RELATIVE;
makebutton(“Chocolates”,gridbag,c);
c.gridwidth= GridBagConstraints.REMAINDER;
makebutton(“Ice-Cream”,gridbag,c);
c.gridwidth=1;
c.gridheight=2;
resize(300,100);
}
public static void main(String args[])
{
GridBagDemo gb = new GridBagDemo();
gb.init();
}
}
Output:

50
BSC III-Year V-Semester (OU) Programming in JAVA

14Q (a) Write java programs to create a simple applet and create swing
based applet.
Simple Applet
Program:
import java.awt.*;
import java.applet.*;
/*
<applet code="Demo"width=500 height=500>
</applet>
*/
public class Demo extends Applet
{
public void paint(Graphics g)
{
g.drawString("Welcome",20,30);
}
}
Output:

51
BSC III-Year V-Semester (OU) Programming in JAVA

## Swing Based Applet

Program:
import javax.swing.*;
import java.awt.*;
/*
</applet>
*/
{
JButton b,p;
public void init()
{
Container c= getContentPane();
c.setLayout(new FlowLayout());
b=new JButton("BLUE");
p=new JButton("PINK");
}
}

Output:

52
BSC III-Year V-Semester (OU) Programming in JAVA

## (b) Java Program to jandle Different Types of Events in a Swing Appliction.

Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingEventDemo
{
private JFrame Fr;
private JPanel panel;
public SwingEventDemo()
{
SwingApp();
}
public static void main(String[] args)
{
SwingEventDemo d = new SwingEventDemo();
d.showEvent();
}
private void SwingApp()
{
Fr=new JFrame(“Swing Application”);
Fr.setSize(400,400);
Fr.setLayout(new GridLayout(3,1));
statusl=new JLabel(“”,JLabel.CENTER);
status.setSize(250,100);
{
public void windowClosing(WindowEvent windowEvent)
{
System.exit(0);
}
});
panel=new LPanel();
Fr.setVisible(true);
}

53
BSC III-Year V-Semester (OU) Programming in JAVA

## private void showEvent()

{
JButton b1=new JButton(“OK”);
JButton b2=new JButton(“Submit”);
JButton b1=new JButton(“Cancel”);
b1.setActionCommand(“OK”);
b2.setActionCommand(“Submit”);
b3.setActionCommand(“Cancel”);
Fr.setVisible(true);
}
private class ButtonClickListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String cmd=ae.getActionCommand();
if(cmd.equals(“OK”))
{
status.setText(“Ok Button is clicked.”);
} else if(cmd.equals(“Submit”))
{
status.setText(“Submit Button is clicked.”);
} else
{
Status.setText(“Cancel Button is clicked.”);
}
}
}
}
Output:

54
BSC III-Year V-Semester (OU) Programming in JAVA

## 15Q: Write java programs to create a swing application using string

components and Layouts.
Using components
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JCBDemo extends JFrame implements itemListener
{
JCheckBox cb1,cb2;
JToggleButton t;
Container c;
JLable l;
void JCDBDemo()
{
setTitle("Demo for showing Checkbox,Radiobutton & Togglebutton");
c=getContentPane();
setSize(300,200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
cb2=new JCheckBox("WRITING");
ButtonGroup bg=new ButtonGroup();
t=new JToggleButton("change colour");
l=new JLabel();

55
BSC III-Year V-Semester (OU) Programming in JAVA

setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
if(e.getItem()==t&&e.getStateChange()==itemEvent.SELECTED)
c.setBackground(color.blue);
if(e.getItem()==t&&e.getStateChange()==itemEvent.SELECTED)
c.setBackground(color.red);
if(e.getItem()==cb1&&e.getStateChange()==itemEvent.SELECTED)
if(e.getItem()==cb2&&e.getStateChange()==itemEvent.SELECTED)
l.setText("WRITING");
if(e.getItem()==r1&&e.getStateChange()==itemEvent.SELECTED)
l.setText("KITKAT");
if(e.getItem()==r2&&e.getStateChange()==itemEvent.SELECTED)
l.setText("MUNCH");
}
public static Void main(string[]args)
{
JCBDemo d=new JCBDemo();
d.JCBDemo();
}
}

Output:

56
BSC III-Year V-Semester (OU) Programming in JAVA

Using Layouts
(i)SpringLayout
Program:
import java.awt.Component;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
public class SpringExample{
public static void main(string args[]}
{
JFrame fr=new JFrame("SpringLayout");
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c=fr.getContentPane();
SpringLayout layt=new SpringLayout();
c.setLayout(layt);
Component left=new JLabel("Left");
Component right=new JTextField(15);
layt.putConstraint(SpringLayout.WEST,left,10,SpringLayout.WEST,c);
layt.putConstraint(SpringLayout.NORTH,left,25,SpringLayout.NORTH,C);
layt.putConstraint(SpringLayout.NORTH,right,25,SpringLayout.NORTH,c);
layt.putConstraint(SpringLayout.WEST,right,20.SpringLayout,EAST,left);
fr.setSize(300,100);
fr.setVisible(true);
}
}
Output

57
BSC III-Year V-Semester (OU) Programming in JAVA

(ii)BoxLayout
Program:
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class BoxLayoutExample
{
public static void main(String[]args)
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame fr=new JFrame("BoxLyout Example");
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BoxLayout boxLyout=new
BoxLayout(fr.getContentPane(),BoxLayout.Y_AXIS);//top to bottom
fr.setLayout(boxLayout);
fr.pack();
fr.setVisible(true);
}
}
Output

58
BSC III-Year V-Semester (OU) Programming in JAVA

16Q: Write a java program to store and retrieve data from database using
JDBC.
Program:
import java.io.*;
import java.sql.*;
public class JDBCDriveExample
{
static final String JDBC-DRIVER="con.mysql.jdbc.Driver";
static final String DB-URL="jdbc:mysql;//localhost/";
public final String void main(string[] args)
{
connection con=null;
statement st=null;
try
{
class.forName("con.mysql.jdbc.Driver");
System.out.println("DataBase Connection");
con=DriverManager.getConnection(DB-URL,urs,pwd);
System.out.println("Accessing data");
st=con.createStatement();
String sq="insert into student values(11,"Nymisha");
st.executeQuery(sq);
System.out.println("Data retrieved successfully");
}
catch(SQLException ex)
{
ex.PrintStackTrace();
}
catch(Exception e)
ex.printstackTrace();
}
finally
{
try
{
if(st!=null)
{
st.close();

59
BSC III-Year V-Semester (OU) Programming in JAVA

}
catch(SQLException ex)
{
}
try
{
if(con!=null)
con.close();
}
catch(SQLException ex)
{
ex.PrintStackTrace();
}
}
}
Output:

60