0% found this document useful (0 votes)
57 views35 pages

(Noc) - Java Lab Programs

java lab bca

Uploaded by

ga568798
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
57 views35 pages

(Noc) - Java Lab Programs

java lab bca

Uploaded by

ga568798
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 35

JAVA LAB PROGRAMS

1. Write a simple Java application to print the message, "Welcome to


Java"

public class Welcome


{
public static void main(String[] args)
{
System.out.println("Welcome to JAVA");
}
}

Output

2. Write a program to display the month of a year. Months of the year


should be held in an array.

import java.util.Calendar;
class dateDemo
{
public static void main(String[] args)
{
Calendar calendar = Calendar.getInstance();
String[] month = { "January", "February", "March", "April",
"May","June", "July", "August", "September", "October",
"November", "December" };
System.out.println("Current Month = "+month[calendar.get
(calendar.MONTH)]);
}
}

Output
3. Write a program to demonstrate a division by zero exception

public class DivisionByZeroDemo


{
public static void main (String args[])
{
int a = 5;
int b = 0;
try
{
System.out.println(a/b);
}
catch (ArithmeticException e)
{
System.out.println ("Division by zero is not possible");
}
}
}

Output

4. Write a program to create a user defined exception say Pay Out of


Bounds

import java.util.*;
class PayoutOfBoundsException extends Exception
{
PayoutOfBoundsException(String msg)
{
System.out.println("Pay Out of Bounds Exception : " +msg);
}
}

public class UserDefinedExceptionDemo


{
public static void main(String args[]) throws
PayoutOfBoundsException
{
System.out.println("Enter the employee Salary : ");
Scanner sc = new Scanner(System.in);
int pay = sc.nextInt();
if(pay<10000 || pay>50000)
{
throw new PayoutOfBoundsException("Salary not in the
valid range");
}
else
System.out.println("Employee eligible for 30% hike");
}
}

Output

5. Write a java 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.

class OverLoad
{
int addition()
{
return(10+10);
}

int addition(int x, int y)


{
return(x+y);
}

float addition(float a, float b)


{
return(a+b);
}

public static void main(String args[])


{
OverLoad l = new OverLoad();
System.out.println("By using default values sum is (10+10)
: "+l.addition());
System.out.println("Sum of two integer values (20+20)
: "+l.addition(20,20));
System.out.println("Sum of two float values (15.5+20.5)
: "+l.addition(15.23f,20.45f));
}
}

Output

6. Write a 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 n1, n2;
public AddSub(int x, int y)
{
n1 = x;
n2 = y;
}

public int add()


{
return(n1+n2);
}

public int sub()


{
return(n1-n2);
}
}

class MulDiv extends AddSub


{
public MulDiv(int x, int y)
{
super(x,y);
}

public int mul()


{
return(n1*n2);
}

public int div()


{
return(n1/n2);
}
}
public class AirthmeticOperations
{
public static void main(String args[])
{
MulDiv obj = new MulDiv(20,10);
System.out.println("Sum of 20 and 10 : "+obj.add());
System.out.println("Difference of 20 and 10 : "+obj.sub());
System.out.println("Product of 20 and 10 : "+obj.mul());
System.out.println("Division 20 and 10 : "+obj.div());
}
}

Output

7. 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 objects member variable values.

class Student
{
static String collegeName = "PES college";
int rollNo;
String name;
Student(int rollno, String name)
{
this.rollNo = rollno;
this.name = name;
}
void display()
{
System.out.println(collegeName + " " + rollNo + " " + name);
}
}
public class StaticDemo
{
public static void main(String args[])
{
System.out.println("\nObjects Sharing the Static Varibale -
College Name\n");
Student s1 = new Student(1001, "Srikanth");
Student s2 = new Student(1002, "Indumathi");
s1.display();
s2.display();
System.out.println("\nStatic Value Changed by One of the
Object \n");
s1.collegeName = "Jain college";
s1.display();
s2.display();
}
}

Output

8. Write a java program to create a student class with following


attributes; Enrollment_id: Name, Mark of sub1, Mark of sub2, Total
Marks. Total of the three marks must be calculated only when the
student passes in all three subjects. The pass mark for each subject is
50. If a candidate fails in any one of the subjects his total mark must
be declared as zero. Using this condition write a constructor for this
class. Write separate functions for accepting and displaying student
details. In the main method create an array 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("\n\nEnter student details");
System.out.print("Enrollment No : ");
Enrollment_id = sc.next();
System.out.print("Name : ");
Name = sc.next();
System.out.println("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("\n\n\tSTUDENT DETAILS");
System.out.println("Enrollment_No\tName\tTotal");
for(int i=0;i<3;i++)
s[i].displayInfo();
}
}

Output
9. In a college first year class are having the following attributes. Name
of the class (BCA, BCom, BSc), Name of the staff, No of the students
in the class, Array of students in the class. Define a class called first
year with above attributes and define a suitable constructor. Also write
a method called bestStudent() which process a first-year object and
return the student with the highest total mark. In the main method,
define a first-year object and find the best student of this class.

import java.util.*;

class FirstYear
{
String classteacher;
String classname;
int stdcount;
int stdmarks [] = new int [50];
String stdnames [] = new String[50];
Scanner sc = new Scanner(System.in);

public FirstYear()
{
getinfo();
}

public void getinfo()


{
System.out.print("Please Enter the Class Name: ");
classname = sc.nextLine();
System.out.print("Please Enter the Class Teacher Name: ");
classteacher = sc.nextLine();
System.out.print("Please Enter the Total Number of Students
of the Class: ");
stdcount = Integer.parseInt(sc.nextLine());
System.out.println("Please Enter the Names of all the
Students of the Class");
for (int i = 0; i < stdcount; i++)
stdnames[i] = sc.nextLine();

System.out.println("Please Enter the Marks of all the


Students of the Class");
for (int i = 0; i < stdcount; i++)
stdmarks[i] = sc.nextInt ();
}

public void bestStudent()


{
int best = 0, k = -1;
for (int i = 0; i < stdcount; i++)
{
if (stdmarks[i] > best)
{
best = stdmarks[i];
k = i;
}
}
System.out.println("The Best Student is "+ stdnames[k]);
}
}

public class Student


{
public static void main(String args[])
{
FirstYear fy = new FirstYear();
fy.bestStudent();
}
}

Output
10. Write a Java program to define a class called employee with the name
and date of appointment. Create ten employee objects as an array and
sort them as per their date of appointment i.e., print them as per their
seniority.

import java.util.Date;

class Employee
{
String name;
Date appdate;
public Employee (String nm, Date apdt)
{
name = nm;
appdate = apdt;
}
public void display()
{
System.out.println("employee name: " + name + "\t\t
appointment date: \t" + appdate.getDate() + "/"+
appdate.getMonth() + "/" + appdate.getYear());
}
}
public class EmpDate
{
public static void main(String as[])
{
Employee emp[] = new Employee [10];
emp[0] = new Employee ("Neeraja K ",new Date(1999, 05, 22));
emp[1] = new Employee ("Kuldeep M", new Date(2000, 01, 12));
emp[2] = new Employee ("Roja D ", new Date(2009, 04, 25));
emp[3] = new Employee ("Rana K ", new Date(2005, 02, 19));
emp[4] = new Employee ("Jyothi ", new Date(2010, 01, 01));
emp[5] = new Employee ("Srikanth ", new Date(1999, 01, 01));
emp[6] = new Employee ("Rajesh ", new Date(2020, 05, 19));
emp[7] = new Employee ("Asha ", new Date(2022, 04, 22));
emp[8] = new Employee ("Ammu ", new Date(2000, 01, 25));
emp[9]= new Employee ("Gourav ", new Date(2002, 9, 9));

System.out.println("List of Employees");
for (int i = 0; i < emp.length; i++)
emp[i].display();

for (int i = 0; i < emp.length; i++)


{
for (int j = i + 1; j < emp.length; j++)
{
if(emp[i].appdate.after (emp[j].appdate))
{
Employee t = emp[i];
emp[i] = emp[j];
emp [j] = t;
}
}
}
System.out.println("\nList of Employees Seniority wise");
for (int i = 0; i < emp.length; i++)
emp[i].display();
}
}
Output

11. Create a package’ studentBCA in our current working directory. Create a


default class student in the above package with the following attributes;
Name, age, Sex. Have methods for sorting as well as displaying.

🗁 BCA > studentbca > BCAStudent


package studentbca;
import java.util.Scanner;

public class BCAStudent


{
String name, sex;
int age;
Scanner sc = new Scanner(System.in);
public void getdata()
{
System.out.print("Student Name : ");
name = sc.nextLine();
System.out.print("Student Sex : ");
sex = sc.nextLine();
System.out.print("Student Age : ");
age = sc.nextInt();
}
public void display()
{
System.out.println();
System.out.println("Student details are ");
System.out.println("Student name : "+name);
System.out.println("Student sex : "+sex);
System.out.println("Student age : "+age);
}
}
🗁 BCA > PackageDemo

import studentbca.BCAStudent;
public class PackageDemo
{
public static void main(String args[])
{
BCAStudent std = new BCAStudent();
std.getdata();
std.display();
}
}

Output
12. Write a small program to catch Negative Array Size Exception. This
exception is caused when the array is initialized to negative values.

public class NegativeArraySizeExceptionDemo


{
public static void main(String[] args)
{
try
{
int[] array = new int[-10];
}
catch (NegativeArraySizeException obj)
{
obj.printStackTrace();
}
System.out.println("Exception Caught and Continuing
Execution...");
}
}

Output

13. Write a program to handle Null Pointer Exception and use the “finally”
method to display a message to the user.

public class NullPointerExecptionDemo


{
public static void main(String[] args)
{
String city= null;
try
{
if (city.equals("Bangalore"))
System.out.print("Equal");
else
System.out.print("Not Equal");
}
catch (NullPointerException e)
{
System.out.println("Null Pointer Exception Caught");
}
finally
{
System.out.println("This is Finally Block after Catching
NullPointerException");
}
}
}

Output

14. 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();
}
}

Output

15. Write a program to draw several shapes in the created window.

import java.awt.*;
public class Drawings extends Canvas
{
public void paint(Graphics g)
{
g.drawRect(50, 75, 100, 50);
g.fillRect(175, 75, 100, 50);
g.drawRoundRect(50, 150, 100, 50, 15, 15);
g.fillRoundRect(175, 150, 100, 50, 15, 15);
g.drawOval(50, 275, 100, 50);
g.fillOval(175, 275, 100, 50);
g.drawArc(20, 350, 100, 50, 25, 75);
g.fillArc(175, 350, 100, 50, 25, 75);
}
public static void main(String[] args)
{
Drawings m = new Drawings();
Frame f = new Frame();
f.add(m);
f.setSize(300, 450);
f.setVisible(true);
}
}

Output
16. Write a program create an applet and draw grid lines.

import java.awt.*;
import java.applet.*;
public class Grid extends Applet
{
public void paint (Graphics g)
{
int row, column, x, y=20;
// for every row
for (row = 1; row < 15; row++)
{
x = 20;
// for every column
for (column = 1; column < 15; column++)
{
g.drawRect(x, y, 50, 50);
x = x + 10;
}
y = y + 10;
}
}
}

<html>
<head>
<title>TO SHOW THE GRID LINES</title>
<body>
<applet code = "Grid" height = 500 width = 500>
</applet>
</body>
</head>
</html>
Output

17. Write a program which creates a frame with two buttons father and
mother. When we 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);
}
}

Output
18. 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(218, 78, 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(800, 400);
f.setLayout(null);
f.setVisible(true);
}
}

Output
19. Create a simple applet which reveals the personal information of yours

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class PersonalDetailsApplet extends Applet implements
ActionListener
{
String s1 = " ", s2 = " ", s3 = " " ,s4 = " ",s5 = " ";
public void init()
{
setLayout(null);
setSize(400, 300);
Button btn = new Button("CLICK HERE FOR MY PERSONAL
DETAILS");
add(btn);
btn.setBounds (20, 50, 300, 30);
btn.addActionListener(this);
}
public void actionPerformed (ActionEvent e)
{
s1 = "Full Name : Aishwarya Rao";
s2 = "Father Name : Ranjit Mother Name: Vijetha Age: 19";
s3 = "Roll No : BNU35628 College Name: Jain Degree College";
s4 = "Nationality Indian Contact No : 9999988888";
s5 = "Address : 7th Cross, Indira Nagar, Bangalore";
repaint();
}
public void paint (Graphics g)
{
g.setFont(new Font("Times Roman", Font.BOLD, 14));
g.drawString(s1, 20, 110);
g.drawString(s2, 20, 140);
g.drawString(s3, 20, 180);
g.drawString(s4, 20, 220);
g.drawString(s5, 20, 260);
}
}
<html>
<head>
<title> Personal Details </title>
<body>
<applet code="PersonalDetailsApplet.class" height=400
width=400>
</applet>
</body>
</head>
</html>

Output

20. Write a program to move different shapes according to the arrow key
pressed.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class ArrowKeys extends Applet implements KeyListener
{
int x1 = 100, y1 = 50, x2 = 250, y2 = 200;
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
showStatus("KeyDown");
int key = ke.getKeyCode();
switch (key)
{
case KeyEvent.VK_LEFT: x1 = x1 - 10;
x2 = x2 - 10;
break;
case KeyEvent.VK_RIGHT: x1 = x1 + 10;
x2 = x2 + 10;
break;
case KeyEvent.VK_UP : y1 = y1 - 10;
y2 = y2 - 10;
break;
case KeyEvent.VK_DOWN : y1 = y1 + 10;
y2 = y2 + 10;
break;
}
repaint();
}

public void keyReleased (KeyEvent ke)


{
}

public void keyTyped (KeyEvent ke)


{
repaint();
}

public void paint (Graphics g)


{
g.drawLine(x1, y1, x2, y2);
g.drawRect(x1, y1 + 160, 100, 50);
g.drawOval (x1, y1 + 235, 100, 50);
}
}

<html>
<head>
<title> Different shapes moving according to arrow key
pressed.</title>
<body>
<applet code="ArrowKeys" Width=400 height=400>
</applet>
</body>
</head>
</html>

Output
21. Write a java Program to create a window when we press M or m the
window displays Good Program 10 Morning, A or a the window displays
Good Afternoon E or e the window displays 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, 400);
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() == 'E' || e.getKeyChar() == 'e')
lbl.setText("GOOD EVENING");
else if (e.getKeyChar() == 'N' || e.getKeyChar() == 'n')
lbl.setText("GOOD NIGHT");
}

public void keyReleased (KeyEvent e)


{
}
public void keyTyped(KeyEvent e)
{
}

public static void main(String[] args)


{
new KeysDemo();
}
}

Output

Press M Press A

Press E Press N
22. Demonstrate the various mouse handling events using suitable example.

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MouseListenerExample implements MouseListener
{
Label lbl1, lbl2;
Frame fr;
String s;
MouseListenerExample()
{
fr=new Frame ("java mouse listener example");
lbl1=new Label ("demo for the mouse event", Label.CENTER);
lbl2= new Label ();
fr.setLayout(new FlowLayout());
fr.add (lbl1);
fr.add(lbl2);
fr.addMouseListener (this);
fr.setSize (250,250);
fr.setVisible (true);
}
public void mouseClicked(MouseEvent ev)
{
lbl2.setText("Mouse button Clicked");
fr.setVisible (true);
}
public void mouseEntered(MouseEvent ev)
{
lbl2.setText("mouse has entered the area of window");
fr.setVisible(true);
}
public void mouseExited( MouseEvent ev)
{
lbl2.setText("Mouse has left the area of window");
fr.setVisible(true);
}
public void mousePressed (MouseEvent ev)
{
lbl2.setText("Mouse button is being pressed");
fr.setVisible(true);
}
public void mouseReleased (MouseEvent ev)
{
lbl2.setText (" Mouse Released");
fr.setVisible(true);
}
public static void main(String args[])
{
MouseListenerExample ml= new MouseListenerExample();
}
}
Output
23. 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[])
{
MenuDemo md= new MenuDemo();
}
}
Output

inprotected.com

You might also like