0% found this document useful (0 votes)
3 views

java record

This document is a practical laboratory record for the Object Oriented Lab (Java Lab) submitted by Dony Biji as part of the Master of Computer Applications program at Kristu Jyoti College. It includes a certificate of authenticity, a declaration of originality, acknowledgments, and a detailed content list of Java programs demonstrating various object-oriented programming concepts. The document serves as a comprehensive report of practical works completed under the guidance of Mr. Roji Thomas.

Uploaded by

noyalaugusthy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

java record

This document is a practical laboratory record for the Object Oriented Lab (Java Lab) submitted by Dony Biji as part of the Master of Computer Applications program at Kristu Jyoti College. It includes a certificate of authenticity, a declaration of originality, acknowledgments, and a detailed content list of Java programs demonstrating various object-oriented programming concepts. The document serves as a comprehensive report of practical works completed under the guidance of Mr. Roji Thomas.

Uploaded by

noyalaugusthy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

OBJECT ORIENTED LAB (JAVA LAB)

(Course Code: MCACP205)

Submitted in partial fulfilment of the requirement for the award of the degree of

MASTER OF COMPUTER APPLICATION

SEMESTER II [2024-2026]

Submitted by

DONY BIJI

RegisterNo:243242210888

Under the guidance of

Mr ROJI THOMAS

DEPARTMENT OF COMPUTER APPLICATION,

KRISTU JYOTI COLLEGE OF MANAGEMENT AND TECHNOLOGY,

CHANGANASSERY

JUNE-2025
KRISTU JYOTI COLLEGE OF MANAGEMENT AND TECHNOLOGY

CHANGANASSERY

DEPARTMENT OF COMPUTER APPLICATION

CERTIFICATE

Certify that the practical laboratory record of OBJECT ORIENTED LAB(JAVA LAB)
is a bona-fide report of the practical works done by DONY BIJI (Reg
No.243242210888)under our guidance and supervision is submitted in partial fulfilment
of the Master of Computer Applications, awarded by Mahatma Gandhi University,
Kerala.

Mr. Roji Thomas……………….………..………………………

(Teacher-in-Charge)

Mr. Roji Thomas…………………………………………..........

(H.O.D)

Rev.Fr. Joshy Cheeramkuzhy CMI……………………………

(Principal)

Submitted for practical examination and viva held on…………………….

Department Seal

Examiner(s)

1.

2.
DECLARATION

I hereby declare that the project work entitled “OBJECT ORIENTED LAB(JAVA LAB)”
submitted to Mahatma Gandhi University in partial fulfillment of requirement for the award of
post-graduation of Master of Computer Application from Kristu Jyoti College of management
and technology, Changanacherry is a record of bona-fide work done under the guidance of Mr
Roji Thomas, Department of Computer Application. This project work has not been submitted
in partial or fulfilment of any other post-graduation or similar of this University or any other
university.

DONY BIJI

Regno:243242210888
ACKNOWLEDGEMENT

I would like to express my thankfulness towards a number of people who have been instrument
in making of this project. First of all, we thank the college management who has been with us
with most helpful facilities throughout the completion of the project. I am greatly indebted to
Rev. Fr. Joshy Cheeramkuzhy CMI, Principal of Kristu Jyoti College who whole heartedly give
us the permission and whose advice was a real encouragement. I record my sincere thanks and
gratitude to Mr. Roji Thomas, HOD, Computer Application, for the valuable suggestions
provided. I am deeply indebted to Mr. Roji Thomas HOD Department of Computer Application,
for the valuable discussion and helpful counselling. Last, not the least I wish to express my
gratitude and heartfelt thanks to our friends, family and whom with their valuable advice,
encouragement and support for the successful completion of the project. Above all thanking the
GOD the almighty.

DONY BIJI
CONTENT

serial no Description Page no

PART -I
1 Program to implement ‘this’ keyword 2
2 Demonstrate overloading method 3
3 Demonstrate object as parameter 4-5
4 Demonstrate member access in 5-6
inheritance
5 Program to demonstrate package 7
6 Demonstrate exception handling and 8
display the description
7 Demonstrate final keyword to prevent 9
overriding
8 String class functions 10-11
9 Demonstrating mouse events in java 12-14
10 Demonstrate Label, Button and TextField 14-15
11 Demonstrate all methods in the class 16-17
CheckBox and implement the
Itemlistener
12 Demonstrate all methods in the class 18-19
Choice and implement the Itemlistener
13 Display the content of a table on screen 19-20
14 Display the records of table based on the 21-22
partial rollno entered through keyboard
15 Create java program with the 3 22-24
textboxes,display the result in third box
based on option selected
16 Create a java applet with textfield and 25-28
button, should be displayed in the reverse
order
17 Applet to display a word on the screen. 29-30
The size of the word should be altered
based on adjustment in the scrollbar
PART-II
32
1 program to demonstrate inheritance
32-33
2 program to method overriding
program to create a package 33
3
program to implement exception handling
4 33-34
program to display roll number,marks of 2
5 34-35
subjects,sports weightage mark and total
score of a student using interfaces

6 Package program to implement


36
mathematical operations.
program to check whether a number is
7
prime. Import the package to check 37-38
whether a number is prime and if the
number is prime, check the digits are also
prime
Program to implement all string handling 38-39
8
functions
9 Familiarize the use of applets by drawing
39
different shapes
Familiarize the use of parametrized applets 40
10
Create a GUI which accepts details of a
11 40-43
student and to store them in a database
43-44
12 Create an interface to display the details
stored in a database in a GUI.
13 Create a menu based application program
44-47
which accepts details of an employee,does
some operation and to display details from
the database in GUI
14 Program to draw Olympic rings 47-48
15
Program to handle mouse events 49-50
Kristu Jyoti College of Management and Technology

PART -I

1
Kristu Jyoti College of Management and Technology

1. Write a java program to implement ‘this’ keyword


Program

class student{
int rollno, age;
String name;

student (int rollno, String name,int age){


this.rollno=rollno;
this.name=name;
this.age=age;
}

void display(){
System.out.println(rollno+" "+name+" "+age);
}
}

class Test{
public static void main(String args[]){
student s1=new student(1 ,"Rahul", 23);
student s2=new student(2 ,"Aarohi", 22);
s1.display();
s2.display();
}
}

Output

1 Rahul 23
2 Aarohi 22

2
Kristu Jyoti College of Management and Technology

2. Write a program to demonstrate overloading method.

Program

class Sum {
int add(int a, int b) {
return(a+b);
}
int add(int a, int b, int c) {
return (a+b+c);
}
double add(double a, double b) {
return (a+b);
}
}

class Overload {
public static void main(String args[]) {
Sum a=new Sum();
System.out.println("sum of two integers = "+a.add(10, 20));
System.out.println("sum of three integers = "+a.add(10, 20, 30));
System.out.println("sum of two double values = "+a.add(2.5, 4.5));
}
}

Output

sum of two integers = 30


sum of three integers = 60
sum of two double values = 7.0

3
Kristu Jyoti College of Management and Technology

3. Write a java program to demonstrate object as a parameter

Program

class Movie {
String title;
String actor, actress;

Movie(String title, String actor, String actress ) {


this.title = title;
this.actor = actor;
this.actress = actress;
}
}

class MovieInfo {
void display(Movie m) {
System.out.println("Title: " + m.title);
System.out.println("Actor: " + m.actor);
System.out.println("Actress: " + m.actress);
}
}

public class Cinema {


public static void main(String[] args) {
Movie m1 = new Movie("Raaz", "Dino Morea", "Bipasha Basu");

4
Kristu Jyoti College of Management and Technology

MovieInfo x = new MovieInfo();


x.display(m1);
}
}

Output

Title: Raaz
Actor: Dino Morea
Actress: Bipasha Basu

4. Write a java program to demonstrate member access in Inheritance

Program

class Person {
String name;
int age;

void setDetails(String name, int age) {


this.name = name;
this.age = age;
}

void showDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}

5
Kristu Jyoti College of Management and Technology

class Student extends Person {


String course;

void setCourse(String course) {


this.course = course;
}

void showStudentDetails() {
showDetails();
System.out.println("Course: " + course);
}
}

public class Inheritance {


public static void main(String[] args) {
Student s1 = new Student();

s1.setDetails("Sanjana", 22);
s1.setCourse("MCA");
s1.showStudentDetails();
}
}

Output

Name: Sanjana
Age: 22
Course: MCA

6
Kristu Jyoti College of Management and Technology

5. Write a simple java program to demonstrate package

Program

myinfo/Info.java:

package myinfo;

public class Info {


public void showMessage() {
System.out.println("Hello from the myinfo package!");
}
}

Main.java
import myinfo.Info;

public class Main {


public static void main(String[] args) {
Info obj = new Info();
obj.showMessage();
}
}

Output

Hello from the myinfo package!

7
Kristu Jyoti College of Management and Technology

6. Write a java program to demonstrate exception handling and display the


description of the exception. Use try catch clause

Program

public class ExceptionDemo {


public static void main(String[] args) {
try {
int a = 10;
int b = 0;

int result = a / b;

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

} catch (ArithmeticException e) {
System.out.println("Exception caught!");
System.out.println("Description : " + e.getMessage());
System.out.println("Full Exception : " + e.toString());
}

System.out.println("Program continues after exception handling.");


}
}

Output

Exception caught!
Description : / by zero
Full Exception : java.lang.ArithmeticException: / by zero
Program continues after exception handling.

8
Kristu Jyoti College of Management and Technology

7. Write a program to demonstrate “final” keyword to prevent overriding

Program

class FinalDemo {
public final void display() {
System.out.println("This is a final method.");
}
}

class Main extends FinalDemo {


public final void display() {
System.out.println("The final method is overridden.");
}

public static void main(String[] args) {


Main obj = new Main();

obj.display();
}
}

Output

error: display() in Main cannot override display() in FinalDemo


overridden method is final

9
Kristu Jyoti College of Management and Technology

8. Design a java program for demonstrate the String class functions equals(),
length(), charAt(), getChars() and trim().

Program

public class StringFunctionsDemo {


public static void main(String[] args) {
String str1 = " Hello Java ";
String str2 = "Hello Java";

System.out.println("1. equals():");
boolean isEqual = str1.trim().equals(str2);
System.out.println("str1 equals str2? " + isEqual);

System.out.println("\n2. length():");
System.out.println("Length of str1: " + str1.length());

System.out.println("\n3. charAt():");
System.out.println("Character at index 2 of str2: " + str2.charAt(2));

System.out.println("\n4. getChars():");
char[] charArray = new char[5];
str2.getChars(0, 5, charArray, 0);

10
Kristu Jyoti College of Management and Technology

System.out.print("First 5 characters of str2: ");


for (char ch : charArray) {
System.out.print(ch);
}
System.out.println();

System.out.println("\n5. trim():");
System.out.println("Original str1: \"" + str1 + "\"");
System.out.println("Trimmed str1: \"" + str1.trim() + "\"");
}
}

Output

1. equals():
str1 equals str2? true

2. length():
Length of str1: 13

3. charAt():
Character at index 2 of str2: l

4. getChars():
First 5 characters of str2: Hello

5. trim():
Original str1: " Hello Java "
Trimmed str1: "Hello Java"

11
Kristu Jyoti College of Management and Technology

9. Write a java applet for demonstrating mouse events in java

Program

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

public class MouseDemo extends Applet implements MouseListener,


MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0;
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me) {


mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
public void mouseEntered(MouseEvent me) {
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
public void mouseExited(MouseEvent me) {

12
Kristu Jyoti College of Management and Technology

mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
public void mousePressed(MouseEvent me) {
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
public void mouseReleased(MouseEvent me) {
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
public void mouseMoved(MouseEvent me) {
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
13
Kristu Jyoti College of Management and Technology

//<applet code="MouseDemo.class" width=300 height=100></applet>

Output

10. Display a java applet form for demonstrate Label, Button and Text field.

Program

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

public class abc extends Applet implements ActionListener {


Label l;
TextField t;
Button b;
String msg;

public void init() {


l = new Label("Enter your name:");
t = new TextField(20);
b = new Button("Greet");

14
Kristu Jyoti College of Management and Technology

add(l);
add(t);
add(b);

b.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {


msg = "Hello, " + t.getText() + "!";
repaint();
}
public void paint(Graphics g){
g.drawString(msg,130,70);
}
}

//<applet code="abc.class" width=400 height=200></applet>

Output

15
Kristu Jyoti College of Management and Technology

11. Display a java applet, which contains the demonstration of all methods available
in the class “CheckBox” and implement the interface “ItemListener”.

Program

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

public class CheckboxDemo extends Applet implements ItemListener {

Checkbox cb1 = null;


Checkbox cb2 = null;
Checkbox cb3 = null;

public void init() {

cb1 = new Checkbox("C++");


cb2 = new Checkbox("Java");
cb3 = new Checkbox("Python");

add(cb1);
add(cb2);
add(cb3);

cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
}

public void paint(Graphics g) {


g.drawString("C++:" +cb1.getState(),10,80);
g.drawString("Java:" +cb2.getState(),10,100);
16
Kristu Jyoti College of Management and Technology

g.drawString("Python:" +cb3.getState(),10,120);
}

public void itemStateChanged(ItemEvent e) {


repaint();
}
}
//<applet code="CheckboxDemo.class" width=400 height=200></applet>

Output

17
Kristu Jyoti College of Management and Technology

12. Display a java applet, which contains the demonstration of all methods available
in the class “Choice” and implement the interface “ItemListener”.

Program

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

public class ChoiceDemo extends Applet implements ItemListener {

Choice language;
String msg = "";

public void init() {


language = new Choice();

language.add("C++");
language.add("Java");
language.add("VB");
language.add("Perl");

add(language);
language.addItemListener(this);
}

public void itemStateChanged(ItemEvent e) {


msg = "Selected: " + language.getSelectedItem();
repaint();
}

18
Kristu Jyoti College of Management and Technology

public void paint(Graphics g) {


g.drawString(msg, 100, 110);
}
}
//<applet code="ChoiceDemo.class" width=300 height=200></applet>

Output

13. Write a program to display the content of a table on to the screen.

Program

import java.sql.*;

class Table {
public static void main(String args[]) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c = DriverManager.getConnection("jdbc:odbc:DSN_NAME");
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM " + args[0]);
19
Kristu Jyoti College of Management and Technology

while (rs.next()) {
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
}
rs.close();
s.close();
c.close();
} catch (Exception e) {

System.out.println("Error: " + e);


}
}
}

Output

Id name email

1 rahul [email protected]

2 anjali [email protected]

3 tina [email protected]

20
Kristu Jyoti College of Management and Technology

14. Write a program to display the records of a table based on the partial rollno
entered through the keyboard.
( Use proper exception and like operator with sql query).

Program

import java.sql.*;
public class student
public static void main(String args[]){

Connection DB(connection=new Connection DB());


Connection con=null;
prepared Statement P=null;
Result set rs=null;
con=Connection.connect DB();

try{
String sql=”Select*from login where id=”+ Integer.parseInt(textfield.getText());
P.con=prepare statement(sql);
rs=p.execute .Query();
System.out.println(“rollno\t name\t Age”);

if(rs.next()){
int id=rs.getInt(“rollno”);
String name=rs.getString(“name”);
String age=rs.getInt(“age”);
System.out.println(“rollno+”\t\t”+ name+”\t\t “+Age”+\t);
}
}catch(SQL Exception e){
System.out.println(e);
}
21
Kristu Jyoti College of Management and Technology

Output

Rollno Name Age

1 Tusshar 23

15. Create a Applet Application with three textboxes. The inputs should be provided
into the first two textboxes and based on the selection made through the Combo
box the result should be displayed in the third textbox.
• The third textbox should not be editable.
• The combo box should have options ADD, SUBSTRACT, MULTIPLY,
DIVIDE and CLOSE.

Program

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

public class Calc extends Applet implements ItemListener {


TextField t1, t2, t3;
Choice c;

public void init() {


t1 = new TextField(10);
t2 = new TextField(10);
t3 = new TextField(10);
22
Kristu Jyoti College of Management and Technology

t3.setEditable(false);

c = new Choice();
c.add("ADD");
c.add("SUBTRACT");
c.add("MULTIPLY");
c.add("DIVIDE");
c.add("CLOSE");

add(t1);
add(t2);
add(t3);
add(c);

c.addItemListener(this);

public void itemStateChanged(ItemEvent e) {


int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
String op = c.getSelectedItem();

if (op.equals("ADD")) {
t3.setText(String.valueOf(num1 + num2));
} else if (op.equals("SUBTRACT")) {
t3.setText(String.valueOf(num1 - num2));
} else if (op.equals("MULTIPLY")) {
t3.setText(String.valueOf(num1 * num2));
} else if (op.equals("DIVIDE")) {
if (num2 != 0) {
t3.setText(String.valueOf(num1 / num2));

23
Kristu Jyoti College of Management and Technology

} else {
t3.setText("Cannot divide by zero");
}
} else if (op.equals("CLOSE")) {
t1.setText("");
t2.setText("");
t3.setText("");
}
}
}
//<applet code="Calc.class" width=400 height=200></applet>

Output

24
Kristu Jyoti College of Management and Technology

16. Develop an applet window having a textfield and button. The text entered in the
textfield should be displayed in the reverse order on to the applet screen when
the button in pressed.
Nb:
• The font size of the text displayed on the applet screen should be
regulated by selecting values using a combo box ( values should range
from 8 to 75 ).
• The font color should be determined by entering values into three
textboxes and the color should be set only when the right button of the
button is pressed.
• Use the null layout to place the controls to the required positions.

Program

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

public class ReverseApplet extends Applet implements ActionListener, ItemListener {

Choice c;

Color fcolor;
TextField t1, t2, t3, t4;
Button b1;
String str = "";
String rev = "";
Font f;
String s;
int k = 20, r = 0, g = 0, b = 0;

25
Kristu Jyoti College of Management and Technology

public void init() {


setLayout(null);

t1 = new TextField(10);
t1.setBounds(50, 30, 100, 25);
add(t1);

t2 = new TextField(3);
t2.setBounds(50, 70, 40, 25);
add(t2);

t3 = new TextField(3);
t3.setBounds(100, 70, 40, 25);
add(t3);

t4 = new TextField(3);
t4.setBounds(150, 70, 40, 25);
add(t4);

b1 = new Button("Click");

b1.setBounds(220, 30, 60, 30);


add(b1);
b1.addActionListener(this);

c = new Choice();
for (int i = 8; i <= 75; i++) {
c.addItem(String.valueOf(i));
26
Kristu Jyoti College of Management and Technology

c.setBounds(220, 70, 60, 25);


add(c);
c.addItemListener(this);
}

public void actionPerformed(ActionEvent e) {


int i;
r = Integer.parseInt(t2.getText());
g = Integer.parseInt(t3.getText());
b = Integer.parseInt(t4.getText());
fcolor = new Color(r, g, b);

str = t1.getText();
rev = "";

for ( i = str.length() - 1; i >= 0; i--) {


rev += str.charAt(i);
}

s = c.getSelectedItem();
k = Integer.parseInt(s);

repaint();
}

public void itemStateChanged(ItemEvent e) {


s = c.getSelectedItem();
k = Integer.parseInt(s);
repaint();
}
27
Kristu Jyoti College of Management and Technology

public void paint(Graphics g) {


f = new Font("Arial", Font.BOLD, k);
g.setFont(f);
g.setColor(fcolor);
g.drawString(rev, 80, 200);
}
}
//<applet code="ReverseApplet.class" width=400 height=200></applet>

Output

28
Kristu Jyoti College of Management and Technology

17. Develop an applet to display a word on the screen. The size of the word should be
altered based on adjustment in the scrollbar.

Program

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

public class FontSizeApplet extends Applet implements AdjustmentListener {


Scrollbar s;
int fsize = 20; // default font size
String word = "Hello, Java!";

public void init() {


s = new Scrollbar(Scrollbar.HORIZONTAL, fsize, 1, 10, 100);
add(s);
s.addAdjustmentListener(this);
}

public void adjustmentValueChanged(AdjustmentEvent e) {


fsize = s.getValue();
repaint();
}

public void paint(Graphics g) {


g.setFont(new Font("Arial", Font.BOLD, fsize));
g.drawString(word, 100, 150);
}
}
//<applet code="FontSizeApplet.class" width=400 height=300></applet>
29
Kristu Jyoti College of Management and Technology

Output

30
Kristu Jyoti College of Management and Technology

PART-II

31
Kristu Jyoti College of Management and Technology

1.Write a program to demonstrate inheritance.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def display_info(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")

class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id

super().display_info()
print(f"Student ID: {self.student_id}")
student = Student("Alice", 20, "S12345")

student.display_info()

Output
Name: Alice
Age: 20
Student ID: S12345

2.Write a program to method overriding.

class Animal:
def sound(self):
print("Animals make sound")

class Dog(Animal):
def sound(self):
print("Dog barks")

class Cat(Animal):
def sound(self):
print("Cat meows")

animal = Animal()
dog = Dog()
cat = Cat()

animal.sound()
dog.sound()
cat.sound()
32
Kristu Jyoti College of Management and Technology

Output

Animals make sound


Dog barks
Cat meows

3.Write a program to create a package .

package mypackage;

public class Calculator {


public int add(int a, int b) {
return a + b;
}

public int subtract(int a, int b) {


return a - b;
}
}

package main;

import mypackage.Calculator;

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();

System.out.println("Addition: " + calc.add(10, 5));


System.out.println("Subtraction: " + calc.subtract(10, 5));
}
}

Output:

makefile
Copy code
Addition: 15
Subtraction: 5

4.Write a program to implement exception handling.

public class ExceptionExample {


public static void main(String[] args) {
33
Kristu Jyoti College of Management and Technology

int[] numbers = {10, 20, 30};


int divisor = 0;

try {
int result = numbers[1] / divisor;
System.out.println("Result: " + result);

System.out.println("Number: " + numbers[5]);

} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");

} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index out of bounds.");

} catch (Exception e) {
System.out.println("General Exception: " + e.getMessage());

} finally {
System.out.println("This block always executes.");
}

System.out.println("Program continues...");
}
}

Output

Error: Division by zero is not allowed.


This block always executes.
Program continues...

5. Write a program to display roll number,marks of 2 subjects,sports weightage mark and


total score of a student using interfaces.

interface Exam {
void getMarks(int m1, int m2);
}

interface Sports {
void getSportsMark(int sm);
}

34
Kristu Jyoti College of Management and Technology

class Student implements Exam, Sports {


int rollNo;
int mark1, mark2;
int sportsMark;
int total;

public Student(int rollNo) {


this.rollNo = rollNo;
}

public void getMarks(int m1, int m2) {


mark1 = m1;
mark2 = m2;
}

public void getSportsMark(int sm) {


sportsMark = sm;
}

public void display() {


total = mark1 + mark2 + sportsMark;
System.out.println("Roll Number: " + rollNo);
System.out.println("Subject 1 Marks: " + mark1);
System.out.println("Subject 2 Marks: " + mark2);
System.out.println("Sports Weightage Mark: " + sportsMark);
System.out.println("Total Score: " + total);
}
}

public class InterfaceExample {


public static void main(String[] args) {
Student s = new Student(101);
s.getMarks(85, 90);
s.getSportsMark(10);
s.display();
}
}

Output
Roll Number: 101
Subject 1 Marks: 85
Subject 2 Marks: 90
Sports Weightage Mark: 10
Total Score: 185

35
Kristu Jyoti College of Management and Technology

6. Write a Package program to implement mathematical operations.

package mathoperations;

public class MathOperations {

public int add(int a, int b) {


return a + b;
}

public int subtract(int a, int b) {


return a - b;
}

public int multiply(int a, int b) {


return a * b;
}

public double divide(int a, int b) {


if (b == 0) {
throw new ArithmeticException("Cannot divide by zero.");
}
return (double) a / b;
}
}
import mathoperations.MathOperations;

public class Main {


public static void main(String[] args) {
MathOperations math = new MathOperations();

int x = 20;
int y = 5;

System.out.println("Addition: " + math.add(x, y));


System.out.println("Subtraction: " + math.subtract(x, y));
System.out.println("Multiplication: " + math.multiply(x, y));
System.out.println("Division: " + math.divide(x, y));
}
}

Output
Addition: 25
Subtraction: 15
Multiplication: 100
Division: 4.0

36
Kristu Jyoti College of Management and Technology

7. Write a package program to check whether a number is prime. Import the package
to check whether a number is prime and if the number is prime, check the digits are also
prime.

package primecheck;

public class PrimeChecker {

public boolean isPrime(int n) {


if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}

public boolean areDigitsPrime(int n) {


String numStr = String.valueOf(n);
for (char c : numStr.toCharArray()) {
int digit = c - '0';
if (!isPrime(digit)) {
return false;
}
}
return true;
}
}
import primecheck.PrimeChecker;
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
PrimeChecker checker = new PrimeChecker();
Scanner sc = new Scanner(System.in);

System.out.print("Enter a number to check: ");


int num = sc.nextInt();

if (checker.isPrime(num)) {
System.out.println(num + " is a prime number.");

if (checker.areDigitsPrime(num)) {
System.out.println("All digits of " + num + " are prime digits.");
} else {
System.out.println("Not all digits of " + num + " are prime digits.");
}
} else {
37
Kristu Jyoti College of Management and Technology

System.out.println(num + " is not a prime number.");


}

sc.close();
}
}

Output
Enter a number to check: 233
233 is a prime number.
All digits of 233 are prime digits.

8. Write a Program to implement all string handling functions.(length, concatenation,


character extraction, string comparison, string index, substring, replace, lower and
uppercase, trim)

public class StringFunctionsExample {


public static void main(String[] args) {
String str1 = " Hello ";
String str2 = "World";
System.out.println("Length of str1: " + str1.length());

String concatenated = str1 + str2;


System.out.println("Concatenated string: " + concatenated);

System.out.println("Character at index 2 of str1: " + str1.charAt(2));

System.out.println("str1 equals str2? " + str1.equals(str2));


System.out.println("str1 equals \" Hello \"? " + str1.equals(" Hello "));
System.out.println("Index of 'l' in str1: " + str1.indexOf('l'));
System.out.println("Substring of str1 (2 to 5): " + str1.substring(2, 5));

String replaced = str1.replace('l', 'p');


System.out.println("Replace 'l' with 'p' in str1: " + replaced);

System.out.println("str2 to lowercase: " + str2.toLowerCase());

System.out.println("str2 to uppercase: " + str2.toUpperCase());

System.out.println("Trimmed str1: '" + str1.trim() + "'");


}
}

Output
Length of str1: 7
Concatenated string: Hello World
Character at index 2 of str1: H
38
Kristu Jyoti College of Management and Technology

str1 equals str2? false


str1 equals " Hello "? true
Index of 'l' in str1: 3
Substring of str1 (2 to 5): llo
Replace 'l' with 'p' in str1: Heppo
str2 to lowercase: world
str2 to uppercase: WORLD
Trimmed str1: 'Hello'

9.Familiarize the use of applets by drawing different shapes.


import java.applet.Applet;

import java.awt.Graphics;
import java.awt.Color;

public class ShapeApplet extends Applet {

@Override
public void paint(Graphics g) {
setBackground(Color.WHITE);

g.setColor(Color.RED);
g.fillRect(50, 50, 100, 100);
g.setColor(Color.BLUE);
g.fillOval(200, 50, 80, 80);
g.setColor(Color.GREEN);
int[] xPoints = {350, 380, 410};
int[] yPoints = {50, 100, 50};
g.fillPolygon(xPoints, yPoints, 3);
}
}
Output

39
Kristu Jyoti College of Management and Technology

10. Familiarize the use of parametrized applets.

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

public class ParamApplet extends Applet {

String message;

public void init() {


message = getParameter("message"); // Get the parameter value

if (message == null) {
message = "Hello, World!"; // Default message
}
}

public void paint(Graphics g) {


g.drawString(message, 20, 30); // Display the message
}
}

Output

11. Create a GUI which accepts details of a student and to store them in a database.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class StudentGUI extends JFrame implements ActionListener {

private JTextField nameField, rollNoField, ageField, addressField;


private JButton submitButton;
40
Kristu Jyoti College of Management and Technology

private JLabel statusLabel;


private Connection dbConnection;

public StudentGUI() {
super("Student Details");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

JLabel nameLabel = new JLabel("Name:");


JLabel rollNoLabel = new JLabel("Roll No:");
JLabel ageLabel = new JLabel("Age:");
JLabel addressLabel = new JLabel("Address:");
statusLabel = new JLabel("");

nameField = new JTextField(20);


rollNoField = new JTextField(10);
ageField = new JTextField(5);
addressField = new JTextField(30);

submitButton = new JButton("Submit");


submitButton.addActionListener(this);

add(nameLabel);
add(nameField);
add(rollNoLabel);
add(rollNoField);
add(ageLabel);
add(ageField);
add(addressLabel);
add(addressField);
add(submitButton);
add(statusLabel);

setSize(400, 300);
setVisible(true);
setLocationRelativeTo(null);
try {

dbConnection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/student_db", "username",
"password");
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Error connecting to the database", "Database
Error", JOptionPane.ERROR_MESSAGE);
}
41
Kristu Jyoti College of Management and Technology

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == submitButton) {
try {
String name = nameField.getText();
String rollNo = rollNoField.getText();
int age = Integer.parseInt(ageField.getText());
String address = addressField.getText();

String sql = "INSERT INTO students (name, roll_no, age, address) VALUES (?, ?, ?,
?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(sql);
preparedStatement.setString(1, name);
preparedStatement.setString(2, rollNo);
preparedStatement.setInt(3, age);
preparedStatement.setString(4, address);
int rowsAffected = preparedStatement.executeUpdate();

if (rowsAffected > 0) {
statusLabel.setText("Student details saved successfully!");

nameField.setText("");
rollNoField.setText("");
ageField.setText("");
addressField.setText("");
} else {
statusLabel.setText("Failed to save student details.");
}
} catch (SQLException | NumberFormatException ex) {
ex.printStackTrace();
statusLabel.setText("Error processing student details.");
}
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new StudentGUI();
}
});
}
}

42
Kristu Jyoti College of Management and Technology

Output

• GUI Form with:


o Student ID
o Name
o Age
o Submit button
• On click of Submit, data is saved to students table.
• Shows success or error messages using JOptionPane.

12 .Create an interface to display the details stored in a database in a GUI.

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class StudentDisplayGUI extends JFrame {

JTable table;
DefaultTableModel model;

Connection con;
Statement stmt;
ResultSet rs;

public StudentDisplayGUI() {
setTitle("Student Records");
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new BorderLayout());

model = new DefaultTableModel();


table = new JTable(model);
JScrollPane scroll = new JScrollPane(table);
add(scroll, BorderLayout.CENTER);

model.addColumn("Roll No");
model.addColumn("Name");
model.addColumn("Marks");

connectAndLoadData();

setVisible(true);
43
Kristu Jyoti College of Management and Technology

void connectAndLoadData() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb", "root",
"your_password");

stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM students");

while (rs.next()) {
int roll = rs.getInt("roll_no");
String name = rs.getString("name");
int marks = rs.getInt("marks");
model.addRow(new Object[]{roll, name, marks});
}

} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Database Error: " + e.getMessage());
}
}

public static void main(String[] args) {


new StudentDisplayGUI();
}
}

Output
Roll No Name Marks
101 John 85
102 Alice 90
103 Bob 78

13. Create a menu based application program which accepts details of an employee,does
some operation and to display details from the database in GUI.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class EmployeeApp extends JFrame implements ActionListener {


JMenuBar menuBar;
JMenu menu;
44
Kristu Jyoti College of Management and Technology

JMenuItem addItem, viewItem, exitItem;

Connection con;
PreparedStatement pst;
Statement stmt;
ResultSet rs;

public EmployeeApp() {
setTitle("Employee Management");
setSize(600, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

menuBar = new JMenuBar();


menu = new JMenu("Options");
addItem = new JMenuItem("Add Employee");
viewItem = new JMenuItem("View Employees");
exitItem = new JMenuItem("Exit");

addItem.addActionListener(this);
viewItem.addActionListener(this);
exitItem.addActionListener(this);

menu.add(addItem);
menu.add(viewItem);
menu.add(exitItem);
menuBar.add(menu);
setJMenuBar(menuBar);

connectDB();
setVisible(true);
}

void connectDB() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/companydb", "root", "your_password"
);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "DB Connection Failed: " + e.getMessage());
}
}

void addEmployee() {
JTextField idField = new JTextField();
JTextField nameField = new JTextField();
45
Kristu Jyoti College of Management and Technology

JTextField salaryField = new JTextField();

Object[] fields = {
"Employee ID:", idField,
"Name:", nameField,
"Salary:", salaryField
};

int option = JOptionPane.showConfirmDialog(this, fields, "Add Employee",


JOptionPane.OK_CANCEL_OPTION);

if (option == JOptionPane.OK_OPTION) {
try {
int id = Integer.parseInt(idField.getText());
String name = nameField.getText();
double salary = Double.parseDouble(salaryField.getText());

pst = con.prepareStatement("INSERT INTO employees VALUES (?, ?, ?)");


pst.setInt(1, id);
pst.setString(2, name);
pst.setDouble(3, salary);

int inserted = pst.executeUpdate();


if (inserted > 0)
JOptionPane.showMessageDialog(this, "Employee added successfully.");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
}
}
}

void viewEmployees() {
try {
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM employees");

String[] columns = { "Emp ID", "Name", "Salary" };


DefaultTableModel model = new DefaultTableModel(columns, 0);

while (rs.next()) {
Object[] row = {
rs.getInt("emp_id"),
rs.getString("name"),
rs.getDouble("salary")
};
model.addRow(row);
}
46
Kristu Jyoti College of Management and Technology

JTable table = new JTable(model);


JScrollPane scrollPane = new JScrollPane(table);

JFrame viewFrame = new JFrame("Employee Records");


viewFrame.add(scrollPane);
viewFrame.setSize(400, 300);
viewFrame.setLocationRelativeTo(null);
viewFrame.setVisible(true);

} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error: " + e.getMessage());
}
}

public void actionPerformed(ActionEvent e) {


if (e.getSource() == addItem) {
addEmployee();
} else if (e.getSource() == viewItem) {
viewEmployees();
} else if (e.getSource() == exitItem) {
System.exit(0);
}
}

public static void main(String[] args) {


new EmployeeApp();
}
}

Output
To Compile & Run -

1. Replace "your_password" with your MySQL password.


2. Ensure the MySQL JDBC Driver is in your classpath.
3. Compile & Run

javac -cp .:mysql-connector-java-8.0.xx.jar EmployeeApp.java


java -cp .:mysql-connector-java-8.0.xx.jar EmployeeApp

14. .Program to draw Olympic rings,.

import java.applet.Applet;
import java.awt.*;

47
Kristu Jyoti College of Management and Technology

public class OlympicRings extends Applet {


public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(5));

g.setColor(Color.BLUE);
g.drawOval(50, 50, 100, 100);

g.setColor(Color.BLACK);
g.drawOval(170, 50, 100, 100);

g.setColor(Color.RED);
g.drawOval(290, 50, 100, 100);
g.setColor(Color.YELLOW);
g.drawOval(110, 110, 100, 100);

g.setColor(Color.GREEN);
g.drawOval(230, 110, 100, 100);
}
}

Output

48
Kristu Jyoti College of Management and Technology

15.Program to handle mouse events

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MouseEventExample extends JFrame implements MouseListener {

JLabel label;

public MouseEventExample() {
setTitle("Mouse Event Demo");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

label = new JLabel("Interact with the window using your mouse.");


add(label);

addMouseListener(this);

setVisible(true);
}

public void mouseClicked(MouseEvent e) {


label.setText("Mouse Clicked at X: " + e.getX() + ", Y: " + e.getY());
}

public void mouseEntered(MouseEvent e) {


label.setText("Mouse Entered the Frame");
}

public void mouseExited(MouseEvent e) {


label.setText("Mouse Exited the Frame");
}

public void mousePressed(MouseEvent e) {


label.setText("Mouse Button Pressed");
}

public void mouseReleased(MouseEvent e) {


label.setText("Mouse Button Released");
}

public static void main(String[] args) {


new MouseEventExample();
49
Kristu Jyoti College of Management and Technology

}
}

Output
1.Save the code as MouseEventExample.java.
2.Complie:
javac MouseEventExample.java
3.Run
java MouseEventExample

50

You might also like