You are on page 1of 40

PART-A

Write a program to print sample program

class HelloWorld

public static void main(String[] args)

System.out.println("Hello, World!");

OUTPUT:

Hello, World!
1. Program to assign two integer values to X and Y. Using the ‘if’
statement the output of the program should display a message
whether X is greater than Y.
import java.util.Scanner;
class BiggestOfTwoNos
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Input Two Numbers ");
int x=s.nextInt();
int y=s.nextInt();
if(x>y)
System.out.println("X is Greater than Y");
else
System.out.println("Y is Greater than X");
}
}

Output:
Input Two Numbers
10
11
Y is Greater than X
2. Program to list the factorial of the numbers 1 to 10. To calculate the
factorial value, use while loop. (Hint: Fact of 4 = 4*3*2*1)
class Factorial
{
public static void main(String args[])
{
int n=1;
while(n<=10)
{
int fact=1;
int i=1;
while(i<=n)
{
fact=fact*i;
i++;
}
System.out.println("Factorial of "+n+" = "+fact);
n++;
}
}
}
OUTPUT:
Factorial of 1 = 1

Factorial of 2 = 2

Factorial of 3 = 6

Factorial of 4 = 24

Factorial of 5 = 120

Factorial of 6 = 720

Factorial of 7 = 5040

Factorial of 8 = 40320

Factorial of 9 = 362880

Factorial of 10 = 3628800
3. Program to find the area and circumference of the circle by accepting the
radius from the user.
import java.util.*;

public class AreaCircle {

public static void main(String[] args) {


double radius, area, circumference;
Scanner in = new Scanner(System.in);
System.out.println("Enter Radius of Circle:");
radius = in.nextDouble();
// Calculate area and circumference of circle
area = Math.PI * radius * radius;
circumference = 2 * Math.PI * radius;

System.out.println("Area of Circle : " + area);


System.out.println("Circumference of Circle : " + circumference);
}
}

Output:
Enter Radius of Circle:
5
Area of Circle : 78.53981633974483
Circumference of Circle : 31.41592653589793
4. Program to add two integers and two float numbers. When no arguments
are supplied, give a default value to calculate the sum. Use function
overloading.
import java.util.Scanner;
class FunOverload
{
int add(int a,int b)
{
int sum=a+b;
return(sum);
}
float add(float a,float b)
{
float sum=a+b;
return(sum);
}
double add()
{
double a=23.45,b=56.56;
double sum=a+b;
return(sum);
}
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
FunOverload obj=new FunOverload();
System.out.println("Input two integers ");
int i1=s.nextInt();
int i2=s.nextInt();
System.out.println("Sum of two integers = "+obj.add(i1,i2));
System.out.println("Input two float values ");
float f1=s.nextFloat();
float f2=s.nextFloat();
System.out.println("Sum of two float values = "+obj.add(f1,f2));
System.out.println("Sum of two Double values = "+obj.add());
}
}
OUTPUT:
Input two integers
10
20
Sum of two integers = 30
Input two float values
2.1
3.2
Sum of two float values = 5.3
Sum of two Double values = 80.01
5. Program to perform mathematical operations. Create a class called AddSub
with methods to add and subtract. Create another class called MulDiv that
extends from AddSub class to use the member data of the super class.
MulDiv should have methods to multiply and divide A main function should
access the methods and perform the mathematical operations.
class addsub
{ int num1;
int num2;
addsub(int n1, int n2)
{
num1 = n1;
num2 = n2;
} int add()
{ return num1+num2;
} int sub()
{
return num1-num2;
}
}
class multdiv extends addsub
{ public multdiv(int n1, int n2)
{
super(n1, n2);
}
int mul()
{return num1*num2;}
float div()
{return num2/num1;}
public void display()
{
System.out.println("Number 1 :" + num1);
System.out.println("Number 2 :" + num2);
}
}
public class adsb
{ public static void main(String arg[])
{
addsub r1=new addsub(50,20);
int ad = r1.add();
int sb = r1.sub();
System.out.println("Addition =" +ad);
System.out.println("Subtraction =" +sb);
multdiv r2 =new multdiv(4,20);
int ml = r2.mul();
float dv =r2.div();
System.out.println("Multiply =" +ml);
System.out.println("Division =" +dv);
}}
Save Your File as adsb.java
OUTPUT:
Addition =70
Subtraction =30
Multiply =80
Division =5.0
6.Write a program with class variable that is available for
all instances of a class. Use static variable declaration. Observe
the changes that occur in the object’s member variable values.
class Staticvar
{
public static int a,b;
public void display()
{
System.out.println(" A value ="+a+" B value ="+b);
}
}
class Demo
{
public static void main(String args[])
{
Staticvar sv=new Staticvar();
sv.a=10;
sv.b=20;
sv.display();
Staticvar sv1=new Staticvar();
sv.display();
}}
Save your file as Demo
Output:
A value =10 B value =20

A value =10 B value =20


7.Write a java program to create a student class with following attributes:
Enrollment_id:Name, Mark of sub1, Mark of sub2, mark of sub3, Total Marks. Total of the
three marksmust be calculated only when the student passes in all three subjects. The pass
mark foreach subject is 50. If a candidate fails in any one of the subjects his total mark must
bedeclaredas zero. Using this condition write a constructor for this class. Write
separatefunctions for accepting and displaying student details. In the main method create
anarray of three student objects and display the details.

import java.util.*;

class Student

Scanner sc = new Scanner(System.in);

String Enrollment_id;

String Name;

int sub1, sub2, sub3, total;

Student()

readStudentInfo();

public void readStudentInfo()

System.out.println("Enter Student Details");

System.out.println("EnrolmentNo: ");

Enrollment_id = sc.next();

System.out.println("Name: ");

Name = sc.next();

System.out.print(" Enter marks of 3 subjects:");

sub1 = sc.nextInt();

sub2 = sc.nextInt();

sub3 = sc.nextInt();

if (sub1 >= 50 && sub2 >= 50 && sub3 >= 50)

total = sub1 + sub2 + sub3;

else
total = 0;

public void displayInfo() {

System.out.println(Enrollment_id+"\t\t"+Name+"\t"+total);

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

Student s[] = new Student[3];

for (int i = 0; i < 3; i++)

s[i] = new Student();

System.out.println("\t\tStudentDetails");

System.out.println("EnrollmentNo\tName\tTotal");

for(int i = 0;i < 3; i++)

s[i].displayInfo();

}
Save Your File : StudentInfo

Output:

Enter Student Details

EnrolmentNo:1001

Name:Ram

Enter marks of 3 subjects:95,92,96

Enter Student Details

EnrolmentNo:1002

Name:Anoop

Enter marks of 3 subjects:98,97,93

Enter Student Details

EnrolmentNo:1003

Name:Manvith

Enter marks of 3 subjects:94,92,91

StudentDetails

EnrollmentNo Name Total

1001 Ram 283

1002 Anoop 288

1003 Manvith 277


8. Write a program to demonstrate multiple inheritance and use of
Implementing Interfaces
import java.util.Scanner;

interface Circle

static double pi=3.14;

double areaCircle(int r);

class Rectangle

int length,width;

void setValues(int l,int w)

length=l; width=w;

void areaRect()

int area=length*width;

System.out.println("Area of a Rectangle = "+area);

class AreaShapes extends Rectangle implements Circle

public double areaCircle(int r)

double area=pi*r*r;

return(area);

public static void main(String args[])

Scanner s=new Scanner(System.in);


AreaShapes shapes=new AreaShapes();

System.out.println("Input the Radius ");

int r=s.nextInt();

System.out.println("Area of a Circle = "+shapes.areaCircle(r));

System.out.println("Input Length and Width ");

int l=s.nextInt();

int w=s.nextInt();

shapes.setValues(l,w);

shapes.areaRect();

Save Your File as AreaShapes

Output:

Input the Radius

Area of a Circle = 78.5

Input Length and Width

Area of a Rectangle = 48
9. Illustrate creation of thread by a) Extending Thread class. b) Implementing
Runnable Interfaces .
a) Extending Thread class
class ThreadA extends Thread

public void run()

for(int i=1; i<=40; i++)

System.out.print(" i = "+i);

class ThreadB extends Thread

public void run()

for(int j=1; j<=50; j++)

System.out.print(" j = "+j);

class ThreadC extends Thread

public void run()

for(int k=1; k<=40; k++)

System.out.print(" k = "+k);

}
}

class MainThread

public static void main(String args[])

ThreadA th1=new ThreadA();

ThreadB th2=new ThreadB();

ThreadC th3=new ThreadC();

th1.start();

th2.start();

th3.start();

Save You program: MainThread.java

Output:

k=1k=2j=1i=1k=3j=2j=3i=2k=4j=4i=3k=5j=5i=4k=6j=6i=5k=7k=8j=7i
= 6 k = 9 j = 8 i = 7 k = 10 j = 9 i = 8 k = 11 j = 10 i = 9 i = 10 k = 12 j = 11 i = 11 k = 13 j = 12 i = 12 k = 14
k = 15 j = 13 i = 13 k = 16 j = 14 i = 14 k = 17 j = 15 i = 15 k = 18 j = 16 i = 16 k = 19 k = 20 j = 17 i = 17 k
= 21 k = 22 j = 18 i = 18 k = 23 k = 24 j = 19 i = 19 k = 25 k = 26 j = 20 i = 20 k = 27 k = 28 j = 21 i = 21 k
= 29 k = 30 j = 22 j = 23 i = 22 k = 31 j = 24 i = 23 k = 32 j = 25 i = 24 i = 25 k = 33 j = 26 i = 26 k = 34 j =
27 i = 27 k = 35 j = 28 i = 28 k = 36 j = 29 i = 29 k = 37 j = 30 j = 31 i = 30 k = 38 j = 32 i = 31 k = 39 j = 33
i = 32 k = 40 j = 34 i = 33 i = 34 j = 35 i = 35 j = 36 i = 36 j = 37 i = 37 j = 38 i = 38 j = 39 i = 39 j = 40 i =
40 j = 41 j = 42 j = 43 j = 44 j = 45 j = 46 j = 47 j = 48 j = 49 j = 50
9.b) Implementing Runnable Interface
import java.lang.Thread;

class ThreadA implements Runnable

public void run()

for(int i=1; i<=40; i++)

System.out.print(" i = "+i);

class ThreadB implements Runnable

public void run()

for(int j=1; j<=50; j++)

System.out.print(" j = "+j);

class ThreadC implements Runnable

public void run()

for(int k=1; k<=40; k++)

System.out.print(" k = "+k);

}
}

class MainThreadRun

public static void main(String args[])

ThreadA th1=new ThreadA();

ThreadB th2=new ThreadB();

ThreadC th3=new ThreadC();

Thread thread1=new Thread(th1);

Thread thread2=new Thread(th2);

Thread thread3=new Thread(th3);

thread1.start();

thread2.start();

thread3.start();

Save your file : MainThreadRun

Output:

k=1k=2k=3i=1j=1k=4i=2j=2k=5i=3j=3k=6i=4j=4j=5k=7k=8i=5j=6k=9i
= 6 i = 7 j = 7 k = 10 i = 8 j = 8 k = 11 i = 9 j = 9 k = 12 i = 10 j = 10 k = 13 i = 11 j = 11 k = 14 i = 12 j = 12
k = 15 i = 13 j = 13 k = 16 i = 14 i = 15 j = 14 k = 17 i = 16 j = 15 k = 18 i = 17 j = 16 k = 19 i = 18 j = 17 k
= 20 i = 19 j = 18 k = 21 i = 20 i = 21 j = 19 k = 22 i = 22 i = 23 j = 20 k = 23 i = 24 j = 21 k = 24 i = 25 j =
22 k = 25 i = 26 j = 23 k = 26 k = 27 i = 27 j = 24 k = 28 i = 28 j = 25 k = 29 i = 29 j = 26 k = 30 i = 30 j =
27 k = 31 i = 31 j = 28 k = 32 i = 32 i = 33 j = 29 k = 33 k = 34 i = 34 j = 30 k = 35 i = 35 i = 36 i = 37 i = 38
j = 31 j = 32 j = 33 j = 34 k = 36 i = 39 i = 40 j = 35 j = 36 j = 37 j = 38 j = 39 j = 40 j = 41 j = 42 k = 37 j =
43 k = 38 j = 44 k = 39 j = 45 k = 40 j = 46 j = 47 j = 48 j = 49 j = 50
/*10.Write a program to demonstrate multilevel inheritance using abstract
class*/
// Abstract class

abstract class Animal {

// Abstract method (does not have a body)

public abstract void animalSound();

// Regular method

public void sleep() {

System.out.println("Zzz");

// Subclass (inherit from Animal)

class Pig extends Animal {

public void animalSound() {

// The body of animalSound() is provided here

System.out.println("The pig says: wee wee");

class Main {

public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound();

myPig.sleep();

Save your File As:Main

OUTPUT

The pig says: wee wee

Zzz
PART-B
1. Program to catch Negative Array Size Exception. This exception is caused when the array size is
initialized to negative values.

import java.util.Scanner;
class DemoExcpt
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
try
{
System.out.println("Input array size ");
int n=s.nextInt();
int []A=new int[n];
System.out.println("Input Array Elements ");
for(int i=0; i<n; i++)
A[i]=s.nextInt();
System.out.println("Array Elements ");
for(int i=0; i<n; i++)
System.out.print(A[i]+" ");
}catch(NegativeArraySizeException e)
{
System.out.println("Error: Negative Array Size Exception is Raised .....");
}
catch(Exception e)
{
System.out.println("Error: Other Error has been occured ....");
}
}
}
SAVE YOUR FILE: DemoExcpt
OUTPUT

Input array size

Input Array Elements

10

20

45

Array Elements

10 20 3 45 8

C:\Users\gpunh\Desktop>java DemoExcpt

Input array size

-4

Error: Negative Array Size Exception is Raised .....


2. Program to demonstrate exception handling with try, catch and finally

import java.util.Scanner;

class ErrorHandling

public static void main(String args[])

Scanner s=new Scanner(System.in);

int a=0,b=0,result=0;

try

System.out.println("Input First number ");

a=s.nextInt();

System.out.println("Input Second number ");

b=s.nextInt();

result=a/b;

}catch(ArithmeticException e)

System.out.println("Divide By Zero Exception is Raised ...");

finally

System.out.println("Result = "+result);

Save your File: ErrorHandling

OUTPUT:

Input First number

12

Input Second number

0
Divide By Zero Exception is Raised ...

Result = 0

C:\Users\gpunh\Desktop>java ErrorHandling

Input First number

12

Input Second number

Result = 2
3.Write a program which create and displays a message on the window

import java.awt.*;

public class FrameDemo

FrameDemo()

Frame fm = new Frame();

fm.setTitle("My First Frame");

Label lb = new Label("Welcome to GUI Programming");

fm.add(lb);

fm.setSize(300,300);

fm.setVisible(true);

public static void main(String args[])

FrameDemo ta = new FrameDemo();

Save Your file : FrameDemo


4. Write a program which creates a frame with two buttons father and
mother. Whenwe click the father button the name of the father, his age and
designation must appear.When we click mother similar details of mother
also appear.
import java.awt.*;
import java.awt.event.*;
public class ButtonClickActionEvents
{
public static void main(String args[])
{
Frame f=new Frame("Button Event");
Label l=new Label("DETAILS OF PARENTS");
l.setFont(new Font("Calibri",Font.BOLD, 16));
Label nl=new Label();
Label dl=new Label();
Label al=new Label();
l.setBounds(20,20,500,50);
nl.setBounds(20,110,500,30);
dl.setBounds(20,150,500,30);
al.setBounds(20,190,500,30);
Button mb=new Button("Mother");
mb.setBounds(20,70,50,30);
mb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
nl.setText("NAME:"+" "+"Aishwarya");
dl.setText("DESIGNATION:"+" "+"Professor");
al.setText("AGE:"+" "+"42");
}
});
Button fb=new Button("Father");
fb.setBounds(80,70,50,30);
fb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
nl.setText("NAME:"+" "+"Ram");
dl.setText("DESIGNATION:"+" "+"Manager");
al.setText("AGE:"+" "+"44");
}
});
//adding elements to the frame
f.add(mb);
f.add(fb);
f.add(l);
f.add(nl);
f.add(dl);
f.add(al);
// setting size,layout, and visibility
f.setSize(250,250);
f.setLayout(null);
f.setVisible(true);
}
}
Save your File As
ButtonClickActionEvents
OUTPUT:
5.Create a frame which displays your personal details with respect to a button click
//5.Create a frame which displays your personal details with respect to a button click
import java.awt.*;
import java.awt.event.*;
public class PersonalDetails
{
public static void main(String args[])
{
Frame f = new Frame("Button Example");
Label l = new Label("Welcome TO MY PAGE");
l.setFont(new Font("Calibri",Font.BOLD,16));
Label fnl= new Label();
Label mnl = new Label();
Label lnl = new Label();
Label rl = new Label();
Label al = new Label();
l.setBounds(250,30,600,50);
fnl.setBounds(20,120,600,30);
mnl.setBounds(20,160,600,30);
lnl.setBounds(20,200,600,30);
rl.setBounds(20,240,600,30);
al.setBounds(20,280,600,30);
Button mb = new Button ("Click Here FOR MY PERSONAL DETAILS");
mb.setFont(new Font ("Calibri",Font.BOLD,14));
mb.setBounds(210,70,320,30);
mb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
fnl.setText("FULL NAME: Aishwarya Rao");

mnl.setText("Father Name: Ranjit Mother Name: Vijetha Age:19");


lnl.setText("Roll No: BNU35628 College Name: Jain Degree College");
rl.setText("Nationality : Indian Contact No: 9999988888");
al.setText("Address : 7th Cross,Indira Nagar,Bangalore");
}
});
//adding elements to the frame
f.add(mb);
f.add(l);
f.add(fnl);
f.add(mnl);
f.add(lnl);
f.add(rl);
f.add(al);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
}f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
}
SAVE YOUR FILE: PersonalDetails
OUTPUT:
6.Program to create a window with textfields and
Buttons.The “ADD” button adds the two integers and
display the result.
import java.awt.*;

import java.awt.event.*;

// Our class extends Frame class and implements ActionListener interface

public class TextFieldExample2 extends Frame implements ActionListener {

// creating instances of TextField and Button class

TextField tf1, tf2, tf3;

Button b1, b2;

// instantiating using constructor

TextFieldExample2() {

// instantiating objects of text field and button

// setting position of components in frame

tf1 = new TextField();

tf1.setBounds(50, 50, 150, 20);

tf2 = new TextField();

tf2.setBounds(50, 100, 150, 20);

tf3 = new TextField();

tf3.setBounds(50, 150, 150, 20);

tf3.setEditable(false);

b1 = new Button("+");

b1.setBounds(50, 200, 50, 50);

b2 = new Button("-");

b2.setBounds(120,200,50,50);

// adding action listener

b1.addActionListener(this);

b2.addActionListener(this);

// adding components to frame

add(tf1);

add(tf2);
add(tf3);

add(b1);

add(b2);

// setting size, layout and visibility of frame

setSize(300,300);

setLayout(null);

setVisible(true);

// defining the actionPerformed method to generate an event on buttons

public void actionPerformed(ActionEvent e) {

String s1 = tf1.getText();

String s2 = tf2.getText();

int a = Integer.parseInt(s1);

int b = Integer.parseInt(s2);

int c = 0;

if (e.getSource() == b1){

c = a + b;

else if (e.getSource() == b2){

c = a - b;

String result = String.valueOf(c);

tf3.setText(result);

// main method

public static void main(String[] args) {

new TextFieldExample2();

SAVE FILE: TextFieldExample2()


//7.Write a java Program to create a window when we press M or m the window displaysGood Morning,
A or a the window displays Good After Noon E or e the windowdisplays Good Evening, N or n the
window displays Good Night

import java.awt.*;

import java.awt.event.*;

public class KeysDemo extends Frame implements KeyListener

Label lbl;

KeysDemo()

addKeyListener(this);

requestFocus();

lbl=new Label();

lbl.setBounds(100,100,200,40);

lbl.setFont(new Font("Calibri",Font.BOLD,16));

add(lbl);setSize(400,300);

setLayout(null);

setVisible(true);

public void keyPressed(KeyEvent e)

if(e.getKeyChar() == 'M' || e.getKeyChar() == 'm')

lbl.setText("Good morning");

else if

(e.getKeyChar() == 'A'||e.getKeyChar() == 'a')

lbl.setText("Good afternoon");

else if

(e.getKeyChar() == 'N' || e.getKeyChar() =='n')

lbl.setText("Good night");

else if(e.getKeyChar() == 'E' || e.getKeyChar() == 'e')

lbl.setText("good evening");

public void keyReleased(KeyEvent e)

}
public void keyTyped (KeyEvent e)

public static void main(String[] args)

new KeysDemo();

Save your file As:

KeysDemo
8.Demonstrate the various mouse handling events using suitable example
import java.awt.*;

import java.awt.event.*;

public class MouseListenerExample1 extends Frame implements MouseListener{

Label l;

MouseListenerExample1(){

addMouseListener(this);

l=new Label();

l.setBounds(20,50,100,20);

add(l);

setSize(300,300);

setLayout(null);

setVisible(true);

public void mouseClicked(MouseEvent e) {

l.setText("Mouse Clicked");

public void mouseEntered(MouseEvent e) {

l.setText("Mouse Entered");

public void mouseExited(MouseEvent e) {

l.setText("Mouse Exited");

public void mousePressed(MouseEvent e) {

l.setText("Mouse Pressed");

public void mouseReleased(MouseEvent e) {

l.setText("Mouse Released");

public static void main(String[] args) {

new MouseListenerExample1();

Save your File As: MouseListenerExample1


Output:

9./*Program to create Menu bar with Label name*/


import java.awt.*;

class MenuExample

MenuExample()

Frame f= new Frame("Menu and MenuItem Example");

MenuBar mb=new MenuBar();

Menu menu=new Menu("Menu");

Menu submenu=new Menu("Sub Menu");

MenuItem i1=new MenuItem("Item 1");

MenuItem i2=new MenuItem("Item 2");

MenuItem i3=new MenuItem("Item 3");

MenuItem i4=new MenuItem("Item 4");

MenuItem i5=new MenuItem("Item 5");

menu.add(i1);

menu.add(i2);
menu.add(i3);

submenu.add(i4);

submenu.add(i5);

menu.add(submenu);

mb.add(menu);

f.setMenuBar(mb);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

public static void main(String args[])

new MenuExample();

SAVE FILE: MenuExample


10.Write a program to create menu bar and pull-down menus.
import java.awt.*;
public class MenuDemo
{
MenuDemo()
{
Frame fr = new Frame("Menu Demo");
MenuBar mb = new MenuBar();
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
Menu viewMenu = new Menu("View");
mb.add(fileMenu);
mb.add(editMenu);
mb.add(viewMenu);
MenuItem a1 = new MenuItem("New");
MenuItem a2 = new MenuItem("Open");
MenuItem a3 = new MenuItem("Save");
MenuItem b1 = new MenuItem("Copy");
MenuItem b2 = new MenuItem("Find");
MenuItem c1 = new MenuItem("Show");
fileMenu.add(a1);
fileMenu.add(a2);
fileMenu.add(a3);
editMenu.add(b1);
editMenu.add(b2);
viewMenu.add(c1);
fr.setMenuBar(mb);
fr.setSize(300,300);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
new MenuDemo();
}
}

SAVE YOUR FILE:


MenuDemo

OUTPUT:

You might also like