0% found this document useful (0 votes)
2 views39 pages

TNB - Java - Practical Sem 3

The document is a practical file for Java programming at T.N.B. College, Bhagalpur, covering various topics such as multiple inheritance using interfaces, package creation, abstract classes, method overloading, object creation, multithreading, exception handling, and GUI development. Each section includes example code, explanations, and expected outputs. The practical file is intended for the academic year 2024-27 for the Department of Computer Application.

Uploaded by

baibhavaditya9
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)
2 views39 pages

TNB - Java - Practical Sem 3

The document is a practical file for Java programming at T.N.B. College, Bhagalpur, covering various topics such as multiple inheritance using interfaces, package creation, abstract classes, method overloading, object creation, multithreading, exception handling, and GUI development. Each section includes example code, explanations, and expected outputs. The practical file is intended for the academic year 2024-27 for the Department of Computer Application.

Uploaded by

baibhavaditya9
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

T.N.B.

COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

Java Programming
Practical File
Object Oriented Programming|15 Practicals

T.N.B. College, Bhagalpur

Department of Computer Application

Academic Year 2024-27


T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

Q1. Write a Java program using Interface for multiple inheritance

// Interface 1

interfaceFlyable{ void

fly();

// Interface 2

interfaceSwimmable{

void swim();

//Classimplementingbothinterfaces(multipleinheritance) class

Duck implements Flyable, Swimmable {

public void fly() {

[Link]("Duckisflying!");

public void swim() {

[Link]("Duckisswimming!");

public void quack() {

[Link]("Ducksays:Quack!");

public class MultipleInheritance {

publicstaticvoidmain(String[]args){
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

Duckd=newDuck();

[Link]();

[Link]();

[Link]();

// Interface reference

Flyable f = new Duck();

Swimmables=newDuck();

[Link]();

[Link]();

Output

Duck is flying!

Duckisswimming!

Ducksays:Quack!

Duck is flying!

Duck is swimming!
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

Q2. Create a Java program for Package Creation and Importing

//File:mypackage/[Link]

package mypackage;

public class Calculator {

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

publicintsubtract(inta,intb){returna-b;}

publicintmultiply(inta,intb){returna*b;} public

double divide(int a, int b){

if(b==0){[Link]("Divisionbyzero!");return0;} return

(double) a / b;

// File: [Link]

[Link];

public class PackageDemo {

public static void main(String[] args) {

Calculator calc = new Calculator();

[Link]("Add:"+[Link](10,5));

[Link]("Subtract: " + [Link](10, 5));


T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

[Link]("Multiply:"+[Link](10,5));

[Link]("Divide: " + [Link](10, 5));

Output

Add: 15

Subtract: 5

Multiply: 50

Divide: 2.0
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

Q3. Create a Java program using Abstract Class

abstractclassShape{

String color;

Shape(Stringcolor){

[Link] = color;

//Abstractmethods-mustbeimplementedbysubclasses abstract

double area();

abstract double perimeter();

//Concretemethod

void display() {

[Link]("Color: " + color);

[Link]("Area: " + area());

[Link]("Perimeter:"+perimeter());

classCircleextendsShape{

double radius;

Circle(Stringcolor,doubler){super(color);radius=r;} double

area() { return [Link] * radius * radius; }

double perimeter() { return 2 * [Link] * radius; }

}
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

classRectangleextendsShape{ double

length, breadth;

Rectangle(Stringcolor,doublel,doubleb){

super(color); length = l; breadth = b;

double area() { return length * breadth; }

double perimeter() { return 2 * (length + breadth); }

public class AbstractDemo {

publicstaticvoidmain(String[]args){ Shape

c = new Circle("Red", 5);

Shaper=newRectangle("Blue",4,6);

[Link]("--- Circle ---");

[Link]();
[Link]("---Rectangle---"); [Link]();

}}

Output

---Circle---

Color: Red

Area: 78.53981633974483

Perimeter: 31.41592653589793

---Rectangle---

Color: Blue

Area: 24.0

Perimeter: 20.0
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

Q4. Write a Java program for Method Overloading to calculate area of shapes

public class AreaCalculator {

// Area of circle

double area(double radius) {

[Link]*radius*radius;

// Area of rectangle

doublearea(doublelength,doublebreadth){ return

length * breadth;

// Area of triangle

doublearea(doublebase,doubleheight,chartype){ return 0.5

* base * height;

// Area of square

intarea(intside){

return side * side;

public static void main(String[] args) {

AreaCalculator ac = new AreaCalculator();

[Link]("AreaofCircle(r=7):"

+ [Link]("%.2f", [Link](7.0)));
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

[Link]("Area of Rectangle (4x6): "

+ [Link](4.0, 6.0));

[Link]("Area of Triangle (b=5, h=8): "

+ [Link](5.0, 8.0, 't'));

[Link]("Area of Square (side=5): "

+ [Link](5));

Output

Area of Circle (r=7): 153.94

AreaofRectangle(4x6):24.0

Area of Triangle (b=5, h=8): 20.0

Area of Square (side=5): 25


T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

[Link],assignvaluestoitsdata members,
and display the details using a method

class Student {

//Datamembers

String name;

int rollNo;

int age;

doublemarks;

//Methodtodisplaydetails

void displayDetails() {

[Link]("=======StudentDetails=======");

[Link]("Name: " + name);

[Link]("Roll No: " + rollNo);

[Link]("Age: " + age);

[Link]("Marks: " + marks);

[Link]("===============================");

}}

public class ObjectDemo {

public static void main(String[] args) {

// Declare object

Student s1 = new Student();

//Assignvaluestodatamembers

[Link] = "Ravi Kumar";

[Link] = 101;
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

[Link] = 20;

[Link] = 87.5;

//Displaydetailsusingmethod

[Link]();

// Second object

Students2=newStudent();

[Link] = "Priya Singh";

[Link] = 102;

[Link] = 19;
[Link] = 92.0;

[Link]();

}}

Output

=======StudentDetails=======

Name: Ravi Kumar

Roll No: 101

Age: 20

Marks: 87.5

===============================

=======StudentDetails=======

Name: Priya Singh

Roll No: 102

Age: 19

Marks: 92.0

===============================
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

[Link](with int and


float variants)

class Shapes {

// Circle with int radius

void calculateArea(int radius) {

double area = [Link] * radius * radius;

[Link]("AreaofCircle(intr="+radius

+ "): " + [Link]("%.2f", area));

// Circle with double radius

void calculateArea(double radius) {

doublearea=[Link]*radius*radius;

[Link]("Area of Circle (double r=" + radius

+ "): " + [Link]("%.2f", area));

// Rectangle: length and breadth

voidcalculateArea(doublelength,doublebreadth){

[Link]("Area of Rectangle (" + length

+ "x" + breadth + "): " + (length * breadth));

// Square: int side

void calculateArea(int side, boolean isSquare) {

[Link]("AreaofSquare(side="+side

+ "): " + (side * side));


T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

public class MethodOverloading {

publicstaticvoidmain(String[]args){

Shapes s = new Shapes();

[Link](5);

[Link](3.5);

[Link](4.0,6.0);

[Link](5, true);

Output

Area of Circle (int r=5): 78.54

AreaofCircle(doubler=3.5):38.48 Area

of Rectangle (4.0x6.0): 24.0 Area of

Square (side=5): 25
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

Q7. Create a Java program using this and super keyword

classAnimal{

String name;

String sound;

Animal(String name, String sound) {

[Link]=name;//'this'referstocurrentclassobject [Link] =

sound;

void makeSound() {

[Link](name + " says: " + sound);

void display() {

[Link]("Animal Name: " + [Link]);

classDogextendsAnimal{

String breed;

Dog(String name, String breed) {

super(name,"Woof");//'super'callsparentconstructor

[Link] = breed; // 'this' refers to Dog's own field

void display() {
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

[Link]();//'super'callsparentmethod

[Link]("Breed: " + [Link]);

void info() {

[Link]();//'this'callscurrentclassmethod

[Link]();

public class ThisSuperDemo {

publicstaticvoidmain(String[]args){ Dog

d = new Dog("Tommy", "Labrador");

[Link]();

Animal a = new Animal("Cat", "Meow");

[Link]();

[Link]();

Output

AnimalName:Tommy

Breed: Labrador

Tommy says: Woof

Animal Name: Cat

Cat says: Meow


T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

Q8. Create a Java program using Multithreading with two threads

classThread1extendsThread{ public

void run() {

for (int i = 1; i <= 5; i++) {

[Link]("Thread1-Count:"+i); try {

[Link](500); // pause 500ms

} catch (InterruptedException e) {

[Link]("Thread1interrupted");

[Link]("Thread 1 finished.");

classThread2implementsRunnable{ public

void run() {

for (int i = 1; i <= 5; i++) {

[Link]("Thread2-Count:"+i); try {

[Link](700);

} catch (InterruptedException e) {

[Link]("Thread2interrupted");

}}
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

[Link]("Thread 2 finished.");

}}

public class MultithreadingDemo {

publicstaticvoidmain(String[]args){ Thread1 t1

= new Thread1();

Thread t2 = new Thread(new Thread2());

[Link]();

[Link]();

[Link]("Both threads started!");

}}
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

Both threads started!

Thread 1 - Count: 1

Thread 2 - Count: 1

Thread 1 - Count: 2

Thread 1 - Count: 3

Thread 2 - Count: 2

Thread 1 - Count: 4

Thread 2 - Count: 3

Thread 1 - Count: 5

Thread 1 finished.

Thread 2 - Count: 4

Thread 2 - Count: 5

Thread 2 finished.
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

[Link],catch, throw,
throws, and finally blocks

public class ExceptionDemo {

//throwskeyword:declaresthatmethodmaythrowexception static

void checkAge(int age) throws Exception {

if (age < 18) {

// throw keyword: manually throw exception

throw new Exception("Age " + age + " is below 18. Not eligible!");

[Link]("Age " + age + ": Eligible.");

static int divide(int a, int b) {

return a / b; // may throw ArithmeticException

public static void main(String[] args) {

//try-catch-finally

try {

int result = divide(10, 0);

[Link]("Result:"+result);

} catch (ArithmeticException e) {

[Link]("Caught:"+[Link]());

} finally {

[Link]("Finally block always executes.");


T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

//Multiplecatchblocks try

[Link]("Arrayerror:"+[Link]());

//throwsexample

Output

Caught: / by zero

Finally block always executes.

Arrayerror:Index10outofboundsforlength5 Exception:

Age 15 is below 18. Not eligible!

Age 20: Eligible.


T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

[Link]()and sleep(),
and implement it in a class Dog

interface Animal {

//Abstractmethods(bydefaultpublicandabstract) void

sound();

void sleep();

//Defaultmethod(Java8+)

default void breathe() {

[Link]("Animal is breathing...");

classDogimplementsAnimal{ String

name;

Dog(Stringname){

[Link] = name;

//Implementingsound() public

void sound() {

[Link](name + " says: Woof! Woof!");

//Implementingsleep() public

void sleep() {

[Link](name + " is sleeping... Zzz");


T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

void fetch() {

[Link](name + " is fetching the ball!");

class Cat implements Animal {

public void sound() { [Link]("Cat says: Meow!"); }

publicvoidsleep(){[Link]("Catissleeping...");}

public class InterfaceDemo {

publicstaticvoidmain(String[]args){ Dog

d = new Dog("Tommy");

[Link]();

[Link]();

[Link]();

[Link]();

[Link]("---");

Animal cat = new Cat();

[Link]();
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

[Link]();

[Link]();

---

Catissleeping...
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

Q11. Write a Java program to make a calculator using layout manager

import [Link].*;

[Link].*;

import [Link].*;

publicclassCalculatorGUIextendsJFrameimplementsActionListener{ JTextField

display;

doublenum1,num2,result; char

operator;

CalculatorGUI() {

setTitle("Calculator");

setSize(350, 450);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setLayout(new BorderLayout(5, 5));

// Display field

display = new JTextField("0");

[Link](newFont("Arial",[Link],24));

[Link]([Link]);

[Link](false);

add(display, [Link]);

// Button panel using GridLayout

JPanelbtnPanel=newJPanel(newGridLayout(5,4,5,5));

String[] buttons = {

"7","8","9","/",
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

"4","5","6","*",

"1","2","3","-",

"0",".","=","+"

};

for (String b : buttons) {

JButtonbtn=newJButton(b);

[Link](newFont("Arial",[Link],18));

[Link](this);[Link](btn);

// Clear button row

JButton clear = new JButton("C");

[Link](newFont("Arial",[Link],18));

[Link]([Link]);

[Link]([Link]);

[Link](this);

[Link](clear);

add(btnPanel,[Link]);

setVisible(true);

publicvoidactionPerformed(ActionEvente){ String

cmd = [Link]();

if ([Link]("[0-9.]")) {
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

if([Link]().equals("0"))[Link](cmd); else

num1=[Link]([Link]());

num2=[Link]([Link]());

}elseif([Link]("C")){
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

publicstaticvoidmain(String[]args){ new

CalculatorGUI();

}
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

Q12. Write a Java program to transpose a matrix (3x3) using array

public class MatrixTranspose {

staticvoidtransposeMatrix(int[][]mat){ int

n = [Link];

[Link]("Original Matrix:");

for (int[] row : mat) {

for (int val : row)

[Link]("%4d",val);

[Link]();

[Link]("TransposedMatrix:");

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

for (int j = 0; j < n; j++)

[Link]("%4d",mat[j][i]);

[Link]();

publicstaticvoidmain(String[]args){

int[][] matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

};

transposeMatrix(matrix);

}
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

[Link] value

+[Link](num).toUpperCase());

+[Link](num));

[Link]("Binary: "

publicstaticvoidmain(String[]args){
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

convertNumber(16);

convertNumber(512);

Output

Number: 255

Hexadecimal:FF

Octal: 377

Binary: 11111111

Number: 100

Hexadecimal: 64

Octal: 144

Binary: 1100100

Number: 16

Hexadecimal: 10

Octal: 20

Binary: 10000

Number: 512

Hexadecimal: 200

Octal: 1000

Binary: 1000000000
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

Q14. Write a Java program to sort an array using Arrays class

import [Link];

public class ArraySorting {

public static void main(String[] args) {

// Integer array sorting

int[] numbers = {64, 25, 12, 92, 38, 7, 55};

[Link]("BeforeSorting:"+[Link](numbers));

[Link](numbers);

[Link]("After Sorting: " + [Link](numbers));

// String array sorting

String[] names = {"Ravi", "Alice", "Mohan", "Priya", "Bob"};

[Link]("\nBeforeSorting:"+[Link](names));

[Link](names);

[Link]("After Sorting: " + [Link](names));

// Partial sort (sort only index 1 to 4)

int[]partial={50,30,80,10,70,20};

[Link]("\nBeforePartialSort:"+
[Link](partial));

[Link](partial, 1, 4);

[Link]("After Partial Sort: " + [Link](partial));

// Binary search after sorting

int[] sorted = {10, 20, 30, 40, 50};


T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

int idx = [Link](sorted, 30);

[Link]("\nBinarySearchfor30:foundatindex"+idx);

Output

Before Sorting: [64, 25, 12, 92, 38, 7, 55]

After Sorting: [7, 12, 25, 38, 55, 64, 92]

BeforeSorting:[Ravi,Alice,Mohan,Priya,Bob] After

Sorting: [Alice, Bob, Mohan, Priya, Ravi]

Before Partial Sort: [50, 30, 80, 10, 70, 20]

After Partial Sort: [50, 10, 30, 80, 70, 20]

Binary Search for 30: found at index 2


T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

Q15. Write a Java program to create a Notepad and also implement all menu items

import [Link].*;

[Link].*;

import [Link].*;

import [Link].*;

publicclassNotepadextendsJFrameimplementsActionListener{ JTextArea

textArea;

JScrollPane scrollPane;

StringcurrentFile=null;

Notepad() {

setTitle("Notepad - Untitled");

setSize(800, 600);

setDefaultCloseOperation(EXIT_ON_CLOSE);

textArea = new JTextArea();

[Link](newFont("Monospaced",[Link],14));

scrollPane = new JScrollPane(textArea);

add(scrollPane, [Link]);

// Menu Bar

JMenuBar menuBar = new JMenuBar();

// File Menu

JMenu fileMenu = new JMenu("File");

addMenuItem(fileMenu,"New","new");
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

addMenuItem(fileMenu,"Open","open");

addMenuItem(fileMenu,"Save","save");

addMenuItem(fileMenu, "Exit", "exit");

// Edit Menu

JMenu editMenu = new JMenu("Edit");

addMenuItem(editMenu, "Cut", "cut");

addMenuItem(editMenu, "Copy", "copy");

addMenuItem(editMenu, "Paste", "paste");

addMenuItem(editMenu,"SelectAll","selectAll");

// Format Menu

JMenu formatMenu = new JMenu("Format");

addMenuItem(formatMenu, "Font Size +", "fontUp");

addMenuItem(formatMenu,"FontSize-","fontDown");

addMenuItem(formatMenu, "Word Wrap", "wordWrap");

// Help Menu

JMenu helpMenu = new JMenu("Help");

addMenuItem(helpMenu,"About","about");

[Link](fileMenu);

[Link](editMenu);

[Link](formatMenu);

[Link](helpMenu);

setJMenuBar(menuBar);

setVisible(true);
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

voidaddMenuItem(JMenumenu,Stringlabel,Stringcmd){

JMenuItem item = new JMenuItem(label);

[Link](cmd);[Link](this);

[Link](item);

publicvoidactionPerformed(ActionEvente){ String

cmd = [Link]();

switch(cmd){ case

"new":

[Link]("");

setTitle("Notepad-Untitled");

currentFile = null; break;

case "open":

JFileChooser fc = new JFileChooser();

if([Link](this)==JFileChooser.APPROVE_OPTION){ try {

currentFile=[Link]().getAbsolutePath();

BufferedReader br = new BufferedReader(

new FileReader(currentFile));

[Link](br, null); [Link]();

setTitle("Notepad-"+currentFile);

} catch (IOException ex) { [Link](); }


T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

} break;

case"save":

JFileChooser sfc = new JFileChooser();

if([Link](this)==JFileChooser.APPROVE_OPTION){ try

BufferedWriterbw=newBufferedWriter(

newFileWriter([Link]()));

[Link](bw); [Link]();

setTitle("Notepad - " + [Link]().getName());

} catch (IOException ex) { [Link](); }

} break;

case "exit": [Link](0); break;

case "cut": [Link](); break;

case "copy": [Link](); break;

case"paste":[Link]();break;

case "selectAll": [Link](); break;

case "fontUp":

[Link]([Link]().deriveFont(

[Link]().getSize() + 2f)); break;

case "fontDown":

[Link]([Link]().deriveFont(

[Link]().getSize() - 2f)); break;

case "wordWrap":

[Link](![Link]());break;

case "about":
T.N.B. COLLEGE, BHAGALPUR
Department of Computer Application
Java Programming Practical File

[Link](this,

"NotepadApplication\nCreatedinJavaSwing\[Link]", "About",

JOptionPane.INFORMATION_MESSAGE); break;

publicstaticvoidmain(String[]args){ new

Notepad();

Output

[GUINotepadWindowOpens]

Menu Bar contains:

File -> New | Open | Save | Exit

Edit -> Cut | Copy | Paste | Select All

Format->FontSize+|FontSize-|WordWrap Help ->

About

Text area is scrollable and editable.

Files can be opened and saved using dialogs.

You might also like