Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Java Lab Cycles

2nd sem java lab cycle.

Uploaded by

maths7252
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Java Lab Cycles

2nd sem java lab cycle.

Uploaded by

maths7252
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Java Programming Lab

Lab 1: Write a simple java application, to print the message,


“Welcome to java”

Program:
class Lab1{

public static void main(String args[])

System.out.println("Welcome to java");

Output:

Welcome to java

Lab 2: Write a program to display the month of a year. Months of the year
should be held in an array.

Program:

import java.util.Calendar;

class Lab2{

public static void main(String args[]){

Calendar calendar=Calendar.getInstance();
String
mon[]={"Jan","Feb","March","April","May","June","July","Aug","Sept","Oct","Nov
","Dec"};

System.out.println(calendar.get(Calendar.MONTH));

System.out.println("Current Month="+mon[calendar.get(Calendar.MONTH)]);

Output:
5

Current Month=June

Lab 3: Write a program to demonstrate a division by zero exception

Program:
class Lab3{

public static void main (String args[]) {

int num1 = 15, num2 = 0, result = 0;

try{

result = num1/num2;

System.out.println("The result is" +result);

catch (ArithmeticException e) {

System.out.println ("Can't be divided by Zero: "+ e);


}

Output:
Can't be divided by Zero: java.lang.ArithmeticException: / by zero

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

Program:
import java.util.*;

class PayoutOfBoundsException extends Exception{

PayoutOfBoundsException(String msg){

System.out.println("Pay out of bound exception:"+msg);

public class Lab4{

public static void main(String args[]) throws PayoutOfBoundsException{

System.out.println("Enter the emp salary");

Scanner sc=new Scanner(System.in);

int pay=sc.nextInt();
if(pay<10000 || pay>50000){

throw new PayoutOfBoundsException("salary not in valid range");

}else

System.out.println("Emp is eiligible for 30% hike");

Output 1:
Enter the emp salary

60000

Pay out of bound exception:salary not in valid range

Exception in thread "main" PayoutOfBoundsException

at Lab4.main(Lab4.java:16)

Output 2:
Enter the emp salary

30000

Emp is eiligible for 30% hike

Lab 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.
Program:
class Lab5{

static int add(int a, int b){

return a+b;

static float add(float x, float y){

return x+y;

static int add(){

return (50+50);

public static void main(String args[]){

int int_sum=add(10,13);

float flt_sum=add(12.2f,10.0f);

System.out.println("add of int is:"+int_sum);

System.out.println("Add of float is:"+flt_sum);

System.out.println("Calling Default addition");

int deft=add();

System.out.println("Default add:"+deft);
}

Output:
add of int is:23

Add of float is:22.2

Calling Default addition

Default add:100

Lab 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.

Program:
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);

}
class Lab6{

public static void main(String args[]){

MulDiv md=new MulDiv(20,10);

System.out.println("Sum of (20,10)is:"+md.add());

System.out.println("Substraction of (20,10)is:"+md.sub());

System.out.println("Multiplication of (20,10)is:"+md.mul());

System.out.println("Division of (20,10)is:"+md.div());

Output:
Sum of (20,10)is:30

Substraction of (20,10)is:10

Multiplication of (20,10)is:200

Division of (20,10)is:2

Lab 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 object’s member variable values.

Program:
class Student{

static String collegeName="KLE";

int rno;

String sname;

public Student(int no, String nm){

rno=no;

sname=nm;

void display(){

System.out.println(collegeName+" "+rno+" "+sname);

public class Lab7{

public static void main(String args[]){

System.out.println("Objects sharing the static variable collegename");

Student s1=new Student(1,"Sri");

Student s2=new Student(2,"Ram");

s1.display();

s2.display();
System.out.println("Static value is changed by one of the object");

s1.collegeName="KLESNC";

s1.display();

s2.display();

Output:

Objects sharing the static variable collegename

KLE 1 Sri

KLE 2 Ram

Static value is changed by one of the object

KLESNC 1 Sri

KLESNC 2 Ram

Lab 8: 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 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 declaredas 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.

Program:

import java.util.*;

class Student{

Scanner sc=new Scanner(System.in);

String Eid;

String name;

int sub1, sub2,sub3, total;

Student(){

getInfo();

public void getInfo(){

System.out.println("**Student details**");

System.out.println("Enter Enrollment ID");

Eid=sc.next();

System.out.println("Enter Name");
name=sc.next();

System.out.println("Enter marks");

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 display(){

System.out.println(Eid+"\t\t"+name+"\t\t"+total);

class Lab8{

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("***Student Details***");

System.out.println("Eid"+"\t\t"+"name"+"\t\t"+"total");

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

s[i].display();

Output:
Enter Enrollment ID

s1

Enter Name

sri

Enter marks

66

67

68

**Student details**

Enter Enrollment ID
s2

Enter Name

ram

Enter marks

78

87

67

**Student details**

Enter Enrollment ID

s3

Enter Name

hari

Enter marks

98

78

65

***Student Details***

Eid name total

s1 sri 201

s2 ram 232

s3 hari 241
Lab 9: In a college first year class are having the following
attributesName of the class (BCA, BCom, BSc), Name of the staff , No
of the students in the class, Array of students in the class

Program:

import java.util.*;

class FirstYear{

String classname;

String classteacher;

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.println("Please Enter the class Name:");


classname = sc.nextLine();

System.out.println("Please Enter the class Teacher Name:");

classteacher = sc.nextLine();

System.out.println("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 Lab9{

public static void main(String args[]){

FirstYear fy = new FirstYear();

fy.bestStudent();

Output:
Harshada

Please Enter the Total number of students of the class:

Please Enter the Names of all the students of the class:

Please Enter the marks of all the students of the class:

78

87
88

The Best Student is C

Lab 10: Define a class called first year with above attributes and define
a suitable constructor. Also write a method called best Student ()
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

Program:

Lab 11:
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. ie, print them as per their
seniority.

Program:
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 appointment


date:\t"+appdate.getDate()+"/"+ appdate.getMonth()+"/"+appdate.getYear());

public class Lab11{

public static void main(String args[]){

Employee emp[]=new Employee[10];

emp[0]=new Employee("Neeraja k", new Date(1999,05,22));

emp[1]=new Employee("roja D",new Date(2009,04,25));

emp[2]=new Employee("rana k",new Date (2005,02,19));

emp[3]=new Employee("jothika", new Date(2009,01,01));

emp[4]=new Employee("srikanth",new Date(1999,01,01));

emp[5]=new Employee("rajesh",new Date(2020,05,19));

emp[6]=new Employee("asha",new Date(2000,01,25));

emp[7]=new Employee("ammu",new Date(2022,04,22));

emp[8]=new Employee("gourav",new Date(2002,9,9));

emp[9]=new Employee("kuldeep",new Date(2000,01,19));

System.out.println("list of employees Before sorting");

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:
list of employees Before sorting

employee name:Neeraja k appointment date: 22/5/1999

employee name:roja D appointment date: 25/4/2009

employee name:rana k appointment date: 19/2/2005

employee name:jothika appointment date: 1/1/2009

employee name:srikanth appointment date: 1/1/1999


employee name:rajesh appointment date: 19/5/2020

employee name:asha appointment date: 25/1/2000

employee name:ammu appointment date: 22/4/2022

employee name:gourav appointment date: 9/9/2002

employee name:kuldeep appointment date: 19/1/2000

List of employees seniority wise

employee name:srikanth appointment date: 1/1/1999

employee name:Neeraja k appointment date: 22/5/1999

employee name:kuldeep appointment date: 19/1/2000

employee name:asha appointment date: 25/1/2000

employee name:gourav appointment date: 9/9/2002

employee name:rana k appointment date: 19/2/2005

employee name:jothika appointment date: 1/1/2009

employee name:roja D appointment date: 25/4/2009

employee name:rajesh appointment date: 19/5/2020

employee name:ammu appointment date: 22/4/2022

Lab 12:
Create a package‘ student.Fulltime.BCA‘ in your current working directory
a. Create a default class student in the above package with the following
attributes: Name, age, sex. b. Have methods for storing as well as displaying

Program:
package student.fulltime.bca;
import java.util.Scanner;

public class BCAStudent{

String name, sex;

int age;

Scanner sc=new Scanner(System.in);

public void getdata(){

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

name=sc.nextLine();

System.out.println("Student Sex:");

sex=sc.nextLine();

System.out.println("Student Age:");

age=sc.nextInt();

public void display(){

System.out.println("Student details are:");

System.out.println("Student Name:"+name);

System.out.println("Student Sex:"+sex);

System.out.println("Student Age:"+age);

}
/* NOTE: Save this file by name BCAStudent.java

Compile this file by using command:

javac -d . BCAStudent.java

folder hierarchy Student\fulltime\bca will be created and BCAStudent is been placed in bca
folder

*/

//save this file as packageDemo.java outside of student folder and execute this file

import student.fulltime.bca.BCAStudent;

public class packageDemo{

public static void main(String args[]){

BCAStudent std=new BCAStudent();

std.getdata();

std.display();

Output:
Student Name:

sri

Student Sex:

male

Student Age:

23
Student details are:

Student Name:sri

Student Sex:male

Student Age:23

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

Program:

import java.util.*;

class Lab13

public static void main(String args[])

Scanner sc=new Scanner(System.in);

System.out.println("Enter the size of an array: ");

int size=sc.nextInt();

try

String[] s=new String[size];

System.out.println("Array is created successfully");

catch(NegativeArraySizeException e)
{

System.out.println("Array underflow");

System.out.println(e.toString());

Output:

Enter the size of an array:

-2

Array underflow

java.lang.NegativeArraySizeException

Lab 14:

Write a program to handle Null Pointer Exception and use the


“finally” method to display a message to the user.

Program:

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

String city=null;
try{
if(city.equals("Bangalore"))
System.out.println("Equals");
else
System.out.println("not Equals");
}catch(NullPointerException e){
System.out.println("Null Pointer Exception Caught");
}
finally{
System.out.println(" this is finally block after try_catch blk");
}
}
}

Output:

Null Pointer Exception Caught

this is finally block after try catch blk

Lab 15:

Write a program which create and displays a message on the


window

Program:

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:
Lab 16:

Write a program to draw several shapes in the created window

Program:

import java.awt.*;

public class Drawings extends Canvas


{
public void paint(Graphics g)
{
g.drawRect(50,75,100,50);
g.fillRect(200,75,50,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("Shapes");
f.add(m);
f.setSize(400,450);
f.setVisible(true);
}
}

Output:

Lab 17:

Write a program to create an applet and draw grid lines


Program:

import java.awt.*;
import java.applet.*;
/*<applet code=Lab17 width=200 height=200>
</applet>*/

public class Lab17 extends Applet{


public void paint(Graphics g){
int row, column,x,y=20;
for(row=1;row<5;row++){
x=20;
for(column=1;column<5;column++){
g.drawRect(x,y,40,40);
x=x+20;
}
y=y+20;
}
}
}

Output:
Lab Cycle: 18
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 Lab18


{
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));
final Label n1 = new Label();
final Label d1 = new Label();
final Label a1 = new Label();
l.setBounds(20,20,500,50);
n1.setBounds(20,110,500,30);
d1.setBounds(20,150,500,30);
a1.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)
{
n1.setText("Name: "+"Aishwarya");
a1.setText("Age: "+"42");
d1.setText("Designation: "+"Professor");
}
});

Button fb = new Button("Father");


fb.setBounds(80,70,50,30);

fb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
n1.setText("Name: "+"Ram");
a1.setText("Age: "+"45");
d1.setText("Designation: "+"Manager");
}
});

f.add(mb);
f.add(fb);
f.add(l);
f.add(n1);
f.add(d1);
f.add(a1);
f.setLayout(null);
f.setSize(250,250);
f.setVisible(true);
}
}

Output:
Lab 19: Create a frame which displays your personal details with respect to a
button click .

import java.awt.*;
import java.awt.event.*;

class personalDetails
{
public static void main(String args[])
{
Frame f= new Frame("Button example");
Label lb=new Label("Welcome to my page");
lb.setFont(new Font("Calibri", Font.BOLD,14));

final Label fnl=new Label();


final Label mnl=new Label();
final Label lnl=new Label();
final Label rl=new Label();
final Label al=new Label();
lb.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 info");
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:Ranjith Mother name: vijaya");
lnl.setText("Roll no: BNU85765 College name: KLE");
rl.setText("Nationality: Indian Contact no: 11111111");
al.setText("Address: Rajajinagar, Bangalore");
}
});

f.add(mb);
f.add(lb);
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);
}

Output:
/*Lab 20: Create a simple applet which reveals the personal information of
yours.
*/

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class Lab20 extends Applet implements ActionListener{


String s1="";
String s2="";
String s3="";
String s4="";
String 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: Ranjith Mother Name: Vijaya Age:19";
s3= "Roll No: BNU234324 College name: KLE";
s4="Nationality: Indian Contact No:123456789";
s5="Address: Rajajinagar, Bangalore";

repaint();
}

public void paint(Graphics g){


g.setFont(new Font("TimesRoman",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);
}
}

/* <applet code="Lab20.class" height=400 width=400></applet>


*/

Output:

Lab 22: Write a java Program to create a window when we press M or m the
window displays Good Morning, A or a the window displays Good After Noon
E or e the window displays Good Evening, N or n the window displays Good
Night

Program:

import java.awt.*;

import java.awt.event.*;
public class Lab22 extends Frame implements KeyListener{

Label lbl;

Label l;

Lab22(){

l = new Label("Press the key [ M, A, E, N ] to Display Greetings", Label.CENTER);

l.setBounds(50, 50, 300, 50);

add(l);

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 Lab22();

OUTPUT:
Lab 23: Demonstrate the various mouse handling events using suitable
example.

Program:
import java.awt.*;

import java.awt.event.*;

public class Lab23 extends Frame implements MouseListener{

Label l;

Lab23(){

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 Lab23();

OUTPUT:
Lab 24: Write a program to create menu bar and pull-down menus

Program:
import java.awt.*;

class Lab24

{
Lab24(){

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

MenuBar mb=new MenuBar();

Menu fileMenu=new Menu("File");

Menu submenu=new Menu("Save AS");

MenuItem i1=new MenuItem("New");

MenuItem i2=new MenuItem("Open");

MenuItem i3=new MenuItem("Save");

MenuItem i4=new MenuItem("pdf");

MenuItem i5=new MenuItem("doc");

fileMenu.add(i1);

fileMenu.add(i2);

fileMenu.add(i3);

submenu.add(i4);

submenu.add(i5);

fileMenu.add(submenu);

mb.add(fileMenu);

f.setMenuBar(mb);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

public static void main(String args[])

new Lab24();
}

OUTPUT:

You might also like