0% found this document useful (0 votes)
11 views15 pages

Java Lab Exercises for CSE Students

The document outlines a lab file for Java programming focusing on Object-Oriented Programming concepts such as inheritance, polymorphism, exception handling, and lambda expressions. It includes practical exercises with sample code for creating Java programs, implementing error handling, and using Java I/O, along with examples of function overloading and overriding. The lab is part of the curriculum for the 2nd semester of the B.Tech (AI) program at Mangalmay Institute of Engineering & Technology for the academic session 2024-25.
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)
11 views15 pages

Java Lab Exercises for CSE Students

The document outlines a lab file for Java programming focusing on Object-Oriented Programming concepts such as inheritance, polymorphism, exception handling, and lambda expressions. It includes practical exercises with sample code for creating Java programs, implementing error handling, and using Java I/O, along with examples of function overloading and overriding. The lab is part of the curriculum for the 2nd semester of the B.Tech (AI) program at Mangalmay Institute of Engineering & Technology for the academic session 2024-25.
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

Mangalmay Institute of Engineering & Technology

Oops with Java Lab File

Department of Computer Science & Engineering ,AI ,DS Session:


2024 - 25
Year: 2nd Sem:4th

Submitted To : Submitted By:


Tapash Kumar Saha Roll No: 2307861520022
Assistant Professor Name: Dhruv Tiwari
CSE, MIET Greater Noida Branch: [Link] (AI)
Index
[Link]. Experiment Title Page Date Sign
No.

1. Create Java programs using types of inheritance and


polymorphism.
2. Implement error-handling techniques using exception
handling and multithreading
3. Write a java program to find the Fibonacci series using
recursive and non recursive functions.
4. Write a java program to represent ArrayList class.
5. Construct java program using Java I/O package.
6. Implement Function Overloading and Function
Overiding using suitable example.
7. Using Lamda Expression Calculate :---

1) Factorial of a given number


2) Check a number is Prime or not.
3) Check a number is Even or Odd or not.
4) Find longest and shortest string.

8. Write a suitable Example of Lambda Expression with


zero,single and multiple parameters .
9. Write a suitable Example of SortedSet Interface,
HashMap Class and Hashtable Class .
10 Write a suitable Example of for each loop(enhanced
for loop) and forEach Method .
PRACTICAL-1

Create Java programs using types of inheritance and polymorphism.


1. Single Inheritance
// Parent class
class Animal {
void eat() {
[Link]("This animal eats food.");
}
}

// Child class
class Dog extends Animal {
void bark() {
[Link]("The dog barks.");
}
}

// Main class
public class SingleInheritanceExample {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Inherited from Animal
[Link](); // Own method
}
}
2 Multilevel Inheritance
// Base class
class Animal {
void eat() {
[Link]("Animal eats.");
}
}
// Derived class
class Dog extends Animal {
void bark() {
[Link]("Dog barks.");
}
}

// Further derived class


class Puppy extends Dog {
void weep() {
[Link]("Puppy weeps.");
}
}

// Main class
public class MultilevelInheritanceExample {
public static void main(String[] args) {
Puppy p = new Puppy();
[Link](); // From Animal
[Link](); // From Dog
[Link](); // Own method
}
}

3 Hierarchical Inheritance
// Superclass
class Animal {
void eat() {
[Link]("Animal eats food.");
}
}

// Subclass 1
class Dog extends Animal {
void bark() {
[Link]("Dog barks.");
}
}

// Subclass 2
class Cat extends Animal {
void meow() {
[Link]("Cat meows.");
}
}

// Main class
public class HierarchicalInheritanceExample {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();

Cat c = new Cat();


[Link]();
[Link]();
}
}
4 Polymorphism (Method Overriding)
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
[Link]("Dog barks");
}
}

class Cat extends Animal {


@Override
void sound() {
[Link]("Cat meows");
}
}

public class PolymorphismExample {


public static void main(String[] args) {
Animal a;

a = new Dog(); // Upcasting


[Link](); // Dog barks

a = new Cat(); // Upcasting


[Link](); // Cat meows
}
}

5. Polymorphism (Method Overloading)


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

double add(double a, double b) {


return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}

public class MethodOverloadingExample {


public static void main(String[] args) {
Adder ad = new Adder();
[Link]([Link](10, 20));
[Link]([Link](3.5, 2.5));
[Link]([Link](1, 2, 3));
}
}
PRACTICAL-2
Implement error-handling techniques using exception handling and multithreading
// Thread class with exception handling
class TaskThread extends Thread {
private int number;

public TaskThread(int number) {


[Link] = number;
}

public void run() {


try {
[Link]("Thread " + getName() + " started.");

// Simulate work
if (number == 0) {
throw new ArithmeticException("Division by zero in thread " + getName());
}

int result = 100 / number;


[Link]("Result in " + getName() + ": 100 / " + number + " = " + result);

} catch (ArithmeticException e) {
[Link]("Exception caught in thread " + getName() + ": " + [Link]());
} finally {
[Link]("Thread " + getName() + " finished.\n");
}
}
}

// Main class
public class ExceptionHandlingWithMultithreading {
public static void main(String[] args) {
// Creating threads with different numbers
TaskThread t1 = new TaskThread(25);
TaskThread t2 = new TaskThread(0); // Will cause ArithmeticException
TaskThread t3 = new TaskThread(5);

// Naming threads
[Link]("Worker-1");
[Link]("Worker-2");
[Link]("Worker-3");

// Starting threads
[Link]();
[Link]();
[Link]();
}
}

Output (Sample)
Thread Worker-1 started.
Result in Worker-1: 100 / 25 = 4
Thread Worker-1 finished.

Thread Worker-2 started.


Exception caught in thread Worker-2: Division by zero in thread Worker-2
Thread Worker-2 finished.

Thread Worker-3 started.


Result in Worker-3: 100 / 5 = 20
Thread Worker-3 finished.
PRACTICAL-3
Write a java program to find the Fibonacci series using recursive and non recursive
functions.
import [Link];
public class FibonacciSeries {
// Recursive method
public static int fibonacciRecursive(int n) {
if (n <= 1)
return n;
else
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
}
// Non-recursive (iterative) method
public static void fibonacciIterative(int count) {
int a = 0, b = 1;
[Link]("Fibonacci Series (Iterative): ");
for (int i = 0; i < count; i++) {
[Link](a + " ");
int next = a + b;
a = b;
b = next;
}
[Link]();
}
// Main method
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of terms: ");
int n = [Link]();
// Iterative approach
fibonacciIterative(n);
// Recursive approach
[Link]("Fibonacci Series (Recursive): ");
for (int i = 0; i < n; i++) {
[Link](fibonacciRecursive(i) + " ");
}
[Link]();

[Link]();
}
}

Sample Output:
Enter the number of terms: 7
Fibonacci Series (Iterative): 0 1 1 2 3 5 8
Fibonacci Series (Recursive): 0 1 1 2 3 5 8
PRACTICAL-4
Write a java program to represent ArrayList class.
import [Link];

public class ArrayListExample {


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

// Adding elements
[Link]("Apple");
[Link]("Banana");
[Link]("Mango");
[Link]("Orange");

// Displaying the ArrayList


[Link]("Initial ArrayList: " + fruits);

// Accessing elements
[Link]("Element at index 2: " + [Link](2));

// Updating elements
[Link](1, "Blueberry");
[Link]("After updating index 1: " + fruits);

// Removing an element
[Link]("Mango");
[Link]("After removing 'Mango': " + fruits);

// Size of the ArrayList


[Link]("Size of ArrayList: " + [Link]());

// Iterating through the ArrayList


[Link]("Fruits in the list:");
for (String fruit : fruits) {
[Link]("- " + fruit);
}

// Checking if list contains an element


if ([Link]("Apple")) {
[Link]("Apple is in the list.");
} else {
[Link]("Apple is not in the list.");
}

// Clearing the list


[Link]();
[Link]("After clearing: " + fruits);
}
}

Sample Output:
Initial ArrayList: [Apple, Banana, Mango, Orange]
Element at index 2: Mango
After updating index 1: [Apple, Blueberry, Mango, Orange]
After removing 'Mango': [Apple, Blueberry, Orange]
Size of ArrayList: 3
Fruits in the list:
- Apple
- Blueberry
- Orange
Apple is in the list.
After clearing: []
PRACTICAL-5

Construct java program using Java I/O package.


import [Link].*;

public class FileIOExample {


public static void main(String[] args) {
String fileName = "[Link]";

// Content to write
String content = "Hello, this is a Java I/O example!\nIt demonstrates file writing and reading.";

// Writing to file
try (FileWriter writer = new FileWriter(fileName)) {
[Link](content);
[Link]("File written successfully.");
} catch (IOException e) {
[Link]("Error writing to file: " + [Link]());
}

// Reading from file


[Link]("\nReading content from the file:");
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;

while ((line = [Link]()) != null) {


[Link](line);
}

} catch (FileNotFoundException e) {
[Link]("The file was not found.");
} catch (IOException e) {
[Link]("Error reading the file: " + [Link]());
}
}
}

Sample Output:
File written successfully.

Reading content from the file:


Hello, this is a Java I/O example!
It demonstrates file writing and reading.
PRACTICAL-6
Implement Function Overloading and Function Overiding using suitable example.
1. Function Overloading (Compile-Time Polymorphism)
class Calculator {
// Overloaded add method with two integers
int add(int a, int b) {
return a + b;
}

// Overloaded add method with three integers


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

// Overloaded add method with two doubles


double add(double a, double b) {
return a + b;
}
}

public class FunctionOverloadingExample {


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

[Link]("add(2, 3) = " + [Link](2, 3));


[Link]("add(2, 3, 4) = " + [Link](2, 3, 4));
[Link]("add(2.5, 3.5) = " + [Link](2.5, 3.5));
}
}
2. Function Overriding (Run-Time Polymorphism)
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
[Link]("Dog barks");
}
}

class Cat extends Animal {


@Override
void sound() {
[Link]("Cat meows");
}
}

public class FunctionOverridingExample {


public static void main(String[] args) {
Animal a;

a = new Dog(); // upcasting


[Link](); // Dog barks

a = new Cat(); // upcasting


[Link](); // Cat meows
}
}
PRACTICAL-7

Using Lamda Expression Calculate :---

1) Factorial of a given number


2) Check a number is Prime or not.
3) Check a number is Even or Odd or not.
4) Find longes and shortest string.
import [Link].*;

import [Link].*;

public class LambdaTasks {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

// 1) Factorial using Lambda

Function<Integer, Integer> factorial = n -> {

int fact = 1;

for (int i = 1; i <= n; i++) fact *= i;

return fact;

};

[Link]("Enter a number for factorial: ");

int num = [Link]();

[Link]("Factorial of " + num + " is: " + [Link](num));

// 2) Prime check using Lambda

Predicate<Integer> isPrime = n -> {

if (n <= 1) return false;

for (int i = 2; i <= [Link](n); i++) {

if (n % i == 0) return false;

return true;

};

[Link]("Enter a number to check prime: ");

int primeNum = [Link]();


[Link](primeNum + " is " + ([Link](primeNum) ? "Prime" : "Not Prime"));

// 3) Even/Odd check using Lambda

Consumer<Integer> checkEvenOdd = n -> {

if (n % 2 == 0)

[Link](n + " is Even");

else

[Link](n + " is Odd");

};

[Link]("Enter a number to check even/odd: ");

int evenOddNum = [Link]();

[Link](evenOddNum);

// 4) Find longest and shortest strings using Lambda

List<String> strings = [Link]("apple", "banana", "kiwi", "grapefruit", "fig", "mango");

Comparator<String> lengthComparator = [Link](String::length);

String shortest = [Link]().min(lengthComparator).orElse("No strings");

String longest = [Link]().max(lengthComparator).orElse("No strings");

[Link]("\nStrings List: " + strings);

[Link]("Shortest String: " + shortest);

[Link]("Longest String: " + longest);

[Link]();

Sample Output:
Enter a number for factorial: 5
Factorial of 5 is: 120
Enter a number to check prime: 7
7 is Prime
Enter a number to check even/odd: 4
4 is Even

Strings List: [apple, banana, kiwi, grapefruit, fig, mango]


Shortest String: fig
Longest String: grapefruit
PRACTICAL-8
Write a suitable Example of Lambda Expression with zero , single and multiple
parameters.
@FunctionalInterface
interface ZeroParam {
void sayHello();
}

@FunctionalInterface
interface OneParam {
int square(int x);
}

@FunctionalInterface
interface TwoParams {
int add(int a, int b);
}

public class LambdaExamples {


public static void main(String[] args) {

// Zero Parameter Lambda


ZeroParam greeting = () -> [Link]("Hello from Lambda with zero parameters!");
[Link]();

// Single Parameter Lambda


OneParam square = x -> x * x;
[Link]("Square of 5 is: " + [Link](5));

// Multiple Parameters Lambda


TwoParams add = (a, b) -> a + b;
[Link]("Sum of 10 and 20 is: " + [Link](10, 20));
}
}

Output:
Hello from Lambda with zero parameters!
Square of 5 is: 25
Sum of 10 and 20 is: 30
PRACTICAL 9
Write a suitable Example of SortedSet Interface, HashMap Class and Hashtable
Class .
1. SortedSet Interface Example
import [Link];
import [Link];
public class SortedSetExample {
public static void main(String[] args) {
SortedSet<String> fruits = new TreeSet<>();
[Link]("Banana");
[Link]("Apple");
[Link]("Mango");
[Link]("Orange");
[Link]("SortedSet (Alphabetical Order):");
for (String fruit : fruits) {
[Link](fruit);
}
[Link]("First Element: " + [Link]());
[Link]("Last Element: " + [Link]());
}
}

2. HashMap Class Example


import [Link];
public class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> studentMap = new HashMap<>();
[Link](101, "Alice");
[Link](102, "Bob");
[Link](103, "Charlie");
[Link]("HashMap Elements:");
for (Integer id : [Link]()) {
[Link]("ID: " + id + ", Name: " + [Link](id));
}
[Link]("Contains key 102? " + [Link](102));
}
}

3. Hashtable Class Example


import [Link];
public class HashtableExample {
public static void main(String[] args) {
Hashtable<String, String> countryCapital = new Hashtable<>();

[Link]("India", "New Delhi");


[Link]("USA", "Washington D.C.");
[Link]("Japan", "Tokyo");

[Link]("Hashtable Elements:");
for (String country : [Link]()) {
[Link]("Country: " + country + ", Capital: " + [Link](country));
}
[Link]("Capital of USA: " + [Link]("USA"));
}
}
PRACTICAL-10
Write a suitable Example of for each loop(enhanced for loop) and forEach Method.
import [Link];
import [Link];

public class ForEachExample {


public static void main(String[] args) {
List<String> fruits = [Link]("Apple", "Banana", "Cherry", "Date");

// 1 Enhanced for loop


[Link]("Using enhanced for loop:");
for (String fruit : fruits) {
[Link](fruit);
}

// 2 forEach method with lambda expression


[Link]("\nUsing forEach() method:");
[Link](fruit -> [Link](fruit));

// 3 forEach method with method reference (even shorter)


[Link]("\nUsing forEach() with method reference:");
[Link]([Link]::println);
}
}

Output:
Using enhanced for loop:
Apple
Banana
Cherry
Date

Using forEach() method:


Apple
Banana
Cherry
Date

Using forEach() with method reference:


Apple
Banana
Cherry
Date

You might also like