0% found this document useful (0 votes)
17 views27 pages

OOPS Java Practical File Guide

Uploaded by

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

OOPS Java Practical File Guide

Uploaded by

Himanshu Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

DEENBANDHU CHHOTU RAM

UNIVERSITY OF SCIENCE AND


TECHNOLOGY MURTHAL

Practical File
Of
OOPS Using Java
Department of Computer Science &
Engineering

Submitted To:
Submitted By:
Mrs. Priya
Nishant
Dept. Of CSE
Roll. No 250010001910
INDEX
Sr.N Experiments Page Sign
o No.
Write a java program to find
1 the Fibonacci series using 2-3
recursive and non recursive
functions
Write a java program to 4-5
2 multiply two given matrices.

Write a java program for 6-8


3 Method overloading and
Constructor overloading.
Write a java program to display 9-10
4 the employee details using
class.
Write a java program that 11-12
5 checks whether a given string
is palindrome or not
Write a java program to 13-14
6(a) represent Abstract class with
example.
Write a java program to 15-16
6(b) implement Interface using
extends keyword.
Write a java program to create 17-17
7(a) inner classes.

Write a java program to create 18-18


7(b) user defined package.

8 Write a java program for 19-20


creating multiple catch blocks.

9(a) Write a java program to display 21-21


File class properties

9(b) Write a java program to 22-23


represent ArrayList class.

9(c) Write a Java program1 loads 24-25


phone no, name from a text file
using hash table.
Program-1
Aim: Write a Java program to find the Fibonacci series using
recursive and non-recursive functions.
Source code:
class FibonacciExample {
// Recursive method to find nth Fibonacci number
public static int fibonacciRecursive(int n) {
if (n <= 1) {
return n; // Base case: F(0) = 0, F(1) = 1
}
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
}
// Non-recursive method to print Fibonacci series
public static void fibonacciNonRecursive(int terms) {
int first = 0, second = 1;
[Link](first + " " + second + " ");
for (int i = 2; i < terms; i++) {
int next = first + second;
[Link](next + " ");
first = second;
second = next;
}
[Link]();
}

public static void main(String[] args) {


int terms = 15; // Fixed value (change if needed)

// Non-recursive approach
[Link]("Fibonacci Series (Non-Recursive):");

2
fibonacciNonRecursive(terms);
// Recursive approach
[Link]("Fibonacci Series (Recursive):");
for (int i = 0; i < terms; i++) {
[Link](fibonacciRecursive(i) + " ");
}
[Link]();
}
}

Output:

3
Program-2
Aim: Write a Java program to multiply two given matrices.
Source code:
public class MatrixMultiplication {
public static void main(String[] args) {
// Define two matrices
int[][] A = {
{1, 4, 2},
{0, 3, -1}
};

int[][] B = {
{5, 1},
{2, 3},
{3, 4}
};
// Rows and columns
int rowsA = [Link]; // 2
int colsA = A[0].length; // 3
int rowsB = [Link]; // 3
int colsB = B[0].length; // 2
// Check if multiplication is possible
if (colsA != rowsB) {
[Link]("Matrix multiplication is not possible!");
return;
}
// Resultant matrix
int[][] result = new int[rowsA][colsB];

4
// Matrix multiplication logic
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
for (int k = 0; k < colsA; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}

// Print result
[Link]("Result of Matrix Multiplication:");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
[Link](result[i][j] + " ");
}
[Link]();
}
}
}

Output:

5
Program-3
Aim: Write a Java program for Method overloading and
Constructor overloading.
Source code:
class Student {
String name;
int age;
String course;

// -------- Constructor Overloading --------


// Constructor 1 - no arguments
Student() {
name = "Unknown";
age = 0;
course = "Not Assigned";
}

// Constructor 2 - with two arguments


Student(String n, int a) {
name = n;
age = a;
course = "Not Assigned";
}

// Constructor 3 - with three arguments


Student(String n, int a, String c) {
name = n;
age = a;
course = c;

6
}

// -------- Method Overloading --------


// Method 1 - display student details without parameters
void display() {
[Link]("Name: " + name + ", Age: " + age + ", Course: " +
course);
}

// Method 2 - display with course as parameter


void display(String newCourse) {
[Link]("Name: " + name + ", Age: " + age + ", Course: " +
newCourse);
}

// Method 3 - display with name and course


void display(String newName, String newCourse) {
[Link]("Name: " + newName + ", Age: " + age + ", Course: " +
newCourse);
}
}

public class OverloadingExample {


public static void main(String[] args) {
// Using constructor overloading
Student s1 = new Student(); // default constructor
Student s2 = new Student("Nishant", 18); // 2-argument constructor
Student s3 = new Student("Ram", 20, "Computer Science"); // 3-argument
constructor

// Display student details

7
[Link]();
[Link]();
[Link]();

// Using method overloading


[Link]("\n--- Method Overloading ---");
[Link]("Mathematics"); // calling method with one parameter
[Link]("daksh", "Physics"); // calling method with two parameters
}
}

Output:

8
Program-4
Aim: Write a Java program to display Employee details using
class.
Source code:
class Employee {
// Data members (instance variables)
int id;
String name;
String department;
double salary;

// Method to set employee details


void setDetails(int empId, String empName, String dept, double empSalary) {
id = empId;
name = empName;
department = dept;
salary = empSalary;
}

// Method to display employee details


void displayDetails() {
[Link]("Employee ID: " + id);
[Link]("Employee Name: " + name);
[Link]("Department: " + department);

9
[Link]("Salary: " + salary);
[Link]("-----------------------------");
}
}

// Main class
public class EmployeeDemo {
public static void main(String[] args) {
// Create objects of Employee
Employee e1 = new Employee();
Employee e2 = new Employee();

// Assign details to employees


[Link](101, "Nishant", "HR", 450000);
[Link](102, "Ram", "IT", 55000);

// Display employee details


[Link]();
[Link]();
}
}

Output:

10
Program-5
Aim: Write a Java program to check whether a given number is
Palindrome or not.
Source code:
import [Link];

public class PalindromeNumber {

// Method to check if a number is a palindrome


public static boolean isPalindrome(int number) {
int originalNumber = number; // Store the original number
int reversedNumber = 0;

// Reverse the number


while (number != 0) {
int digit = number % 10; // Extract the last digit
reversedNumber = reversedNumber * 10 + digit; // Build the reversed
number

11
number /= 10; // Remove the last digit
}

// Check if the original number is equal to the reversed number


return originalNumber == reversedNumber;
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Prompt the user for input


[Link]("Enter a number to check if it is a palindrome: ");
// Validate input
if (![Link]()) {
[Link]("Invalid input. Please enter an integer.");
[Link]();
return;
}

int number = [Link]();

// Check if the number is a palindrome


if (isPalindrome(number)) {
[Link](number + " is a palindrome.");
} else {
[Link](number + " is not a palindrome.");
}

[Link](); // Close the scanner


}

12
}

Output:

Program-6(a)
Aim: Write a Java program to represent Abstract class with
example.
Source code:
// Abstract class definition
abstract class Animal {
// Abstract method (no body, must be implemented by subclasses)
public abstract void makeSound();

// Non-abstract method (has a body)


public void eat() {
[Link]("This animal eats food.");
}
}

// Concrete subclass that extends the abstract class

13
class Dog extends Animal {
// Implementing the abstract method
@Override
public void makeSound() {
[Link]("The dog barks: Woof Woof!");
}
}

// Another concrete subclass


class Cat extends Animal {
// Implementing the abstract method
@Override
public void makeSound() {
[Link]("The cat meows: Meow Meow!");
}
}

// Main class to test the abstract class and its subclasses


public class AbstractClassExample {
public static void main(String[] args) {
// Create objects of the subclasses
Animal dog = new Dog();
Animal cat = new Cat();

// Call the methods


[Link]("Dog:");
[Link](); // Calls the overridden method in Dog
[Link](); // Calls the non-abstract method from Animal

[Link]("\nCat:");

14
[Link](); // Calls the overridden method in Cat
[Link](); // Calls the non-abstract method from Animal
}
}

Output:

Program-6(b)
Aim: Write a Java program to implement interface using
extends keyword.
Source code:
// Define a base interface
interface Animal {
void eat(); // Abstract method
}

// Extend the base interface


interface Dog extends Animal {
void bark(); // Additional abstract method
}

// Implement the extended interface in a class

15
class GermanShepherd implements Dog {
// Provide implementation for the eat() method from Animal interface
@Override
public void eat() {
[Link]("The German Shepherd is eating.");
}

// Provide implementation for the bark() method from Dog interface


@Override
public void bark() {
[Link]("The German Shepherd is barking.");
}
}

public class Main {


public static void main(String[] args) {
// Create an object of the GermanShepherd class
GermanShepherd gs = new GermanShepherd();
// Call the methods
[Link]();
[Link]();
}
}

Output:

16
Program-7(a)
Aim: Write a java program to create inner classes.
Source code:

public class OuterClass {

// Member variable of outer class


private String outerMessage = "Hello from Outer Class!";
// -------- Inner Class --------
class InnerClass {
void display() {
[Link]("This is the Inner Class.");
// Inner class can access private members of the outer class
[Link]("Accessing Outer Class variable: " + outerMessage);

17
}
}
public static void main(String[] args) {
// Create object of outer class
OuterClass outer = new OuterClass();
// Create object of inner class using outer class object
[Link] inner = [Link] InnerClass();
[Link]();
}
}

Output:

Program-7(b)
Aim: Write a java program to create user defined package.
Source code:
// Save this file inside a folder named "MyPackage"
// Folder structure: MyPackage/[Link]

package MyPackage; // user-defined package

public class Message {


public void displayMessage() {
[Link]("Hello! This message is from the user-defined package.");
}
}
// Save this file outside the MyPackage folder (in the main project folder)

18
import [Link]; // import the user-defined package

public class TestPackage {


public static void main(String[] args) {
Message msg = new Message(); // create object of class inside package
[Link]();
}
}

Output:

Program-8
Aim: Write a java program for creating multiple catch blocks.
Source code:

public class MultipleCatchExample {


public static void main(String[] args) {
try {
int[] numbers = {10, 20, 30};
int a = 10, b = 0;

// This line may throw ArithmeticException


int result = a / b;

19
// This line may throw ArrayIndexOutOfBoundsException
[Link](numbers[5]);

// This line may throw NullPointerException


String text = null;
[Link]([Link]());
}
// Catch block 1 - Arithmetic Exception
catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
}
// Catch block 2 - Array Index Exception
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Array index is out of range.");
}
// Catch block 3 - Null Pointer Exception
catch (NullPointerException e) {
[Link]("Error: Attempted to access a null object.");
}
// Generic catch block (optional)
catch (Exception e) {
[Link]("An unexpected error occurred: " + [Link]());
}

[Link]("Program continues after exception handling.");


}
}

Output:

20
Program-9(a)
Aim: Write a java program to display File class properties.
Source code:

import [Link];
public class FilePropertiesExample {
public static void main(String[] args) {
File file = new File("[Link]");
[Link]("File Name: " + [Link]());
[Link]("File Path: " + [Link]());
[Link]("Absolute Path: " + [Link]());
[Link]("Parent Directory: " + [Link]());

21
[Link]("Exists: " + [Link]());
[Link]("Readable: " + [Link]());
[Link]("Writable: " + [Link]());
[Link]("Executable: " + [Link]());
[Link]("Is Directory: " + [Link]());
[Link]("Is File: " + [Link]());
[Link]("File Size (in bytes): " + [Link]());
}
}

Output:

Program-9(b)
Aim: Write a java program to represent ArrayList class.
Source code:

import [Link];

public class ArrayListExample {


public static void main(String[] args) {
// Create an ArrayList of Strings
ArrayList<String> names = new ArrayList<>();

// Add elements to the ArrayList

22
[Link]("Nishant");
[Link]("Ram");
[Link]("Daksh");
[Link]("Shyam");

// Display all elements


[Link]("ArrayList Elements:");
[Link](names);

// Access elements using get() method


[Link]("\nElement at index 2: " + [Link](2));

// Update an element
[Link](1, "Punit");
[Link]("\nAfter updating index 1:");
[Link](names);

// Remove an element
[Link]("Daksh");
[Link]("\nAfter removing 'Daksh':");
[Link](names);

// Display size of the ArrayList


[Link]("\nSize of ArrayList: " + [Link]());

// Check if an element exists


[Link]("\nDoes list contain 'Nishant'? " +
[Link]("Nishant"));

// Iterate through ArrayList using for-each loop

23
[Link]("\nIterating through ArrayList:");
for (String name : names) {
[Link](name);
}
}
}

Output:

Program-9(c)
Aim: Write a Java program loads phone no, name from a text
file using hash table.
Source code:

import [Link].*;
import [Link];
import [Link];
import [Link];

24
public class PhoneDirectory {
public static void main(String[] args) {
// Create a Hashtable to store name and phone number pairs
Hashtable<String, String> phoneBook = new Hashtable<>();

try {
// Create a File object for the text file
File file = new File("[Link]");

// Create Scanner to read the file


Scanner sc = new Scanner(file);

// Read each line from file and store in Hashtable


while ([Link]()) {
String line = [Link]();

// Split line into name and phone number (format: Name,Number)


String[] parts = [Link](",");
if ([Link] == 2) {
String name = parts[0].trim();
String number = parts[1].trim();
[Link](name, number);
}
}
[Link]();
// Display all contacts
[Link]("---- Phone Directory ----");
Enumeration<String> names = [Link]();
while ([Link]()) {
String name = [Link]();

25
[Link]("Name: " + name + " | Phone: " +
[Link](name));
}
} catch (FileNotFoundException e) {
[Link]("Error: [Link] file not found.");
}
}
}

File 2: [Link] :
Nishant,9876543210
Ram,9812345678
Daksh,9898989898
Shyam,9123456780
Output:

26

You might also like