0% found this document useful (0 votes)
22 views74 pages

JAVAPROGRAMS Practicalkhushi

The document contains a Java programming assignment for a B.Tech (CSE) student, detailing various programs demonstrating fundamental concepts such as printing output, command line arguments, constructor and method overloading, method overriding, inheritance, abstract classes, interfaces, and exception handling. Each program includes source code and expected results, showcasing the student's understanding of Java programming principles. The assignment is part of the academic session 2023-24 at Dronacharya Group of Institutions.

Uploaded by

devbhargav100
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)
22 views74 pages

JAVAPROGRAMS Practicalkhushi

The document contains a Java programming assignment for a B.Tech (CSE) student, detailing various programs demonstrating fundamental concepts such as printing output, command line arguments, constructor and method overloading, method overriding, inheritance, abstract classes, interfaces, and exception handling. Each program includes source code and expected results, showcasing the student's understanding of Java programming principles. The assignment is part of the academic session 2023-24 at Dronacharya Group of Institutions.

Uploaded by

devbhargav100
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

JAVA PROGRAMING

SUBJECT CODE: BCS 452


B.TECH.(CSE) SEMESTER -IV

Academic Session: 2023-24, Even Semester


Student Name: Khushi Chaudary
Roll. No.: 2202300100091
Branch/Section: CSE/G1A

Dronacharya Group of Institutions


Plot No. 27, Knowledge Park-3, Greater Noida, Uttar Pradesh 201308
Affiliated to

Dr. A P J Abdul Kalam Technical University


Lucknow, Uttar Pradesh 22603
JAVA PROGRAMING

Program no-1
WAP in java to print Hello word.

public class practice {


public static void main(String[] args) {
System.out.println("Hello World ");
}
}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

1
JAVA PROGRAMING

Program no-2
WAP in java to find the sum of two numbers using
Command Line Arguments.

public class AddNumbers {


public static void main(String[] args) {
// Check if two arguments are provided
if (args.length != 2) {
System.out.println("Please provide two numbers as command
line arguments.");
return;
}

try {
// Parse the command line arguments to integers
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);

// Calculate the sum


int sum = num1 + num2;

// Print the result


System.out.println("The sum of " + num1 + " and " + num2 +
" is: " + sum);

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

2
JAVA PROGRAMING

} catch (NumberFormatException e) {
System.out.println("Invalid input. Please provide two valid
numbers.");
}
}
}

Result :

Program no-3

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

3
JAVA PROGRAMING

WAP in java to implement Constructor Overloading.

public class Rectangle {


int length;
int width;

// Default constructor
public Rectangle() {
this.length = 0;
this.width = 0;
}

// Constructor with one parameter


public Rectangle(int side) {
this.length = side;
this.width = side;
}

// Constructor with two parameters


public Rectangle(int length, int width) {
this.length = length;
this.width = width;
}

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

4
JAVA PROGRAMING

// Method to calculate the area of the rectangle


public int getArea() {
return length * width;
}

// Method to display the dimensions of the rectangle


public void display() {
System.out.println("Length: " + length + ", Width: " + width + ",
Area: " + getArea());
}

public static void main(String[] args) {


// Using the default constructor
Rectangle rect1 = new Rectangle();
rect1.display();
Result:

Program no-4
WAP in java to implement Method Overloading.

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

5
JAVA PROGRAMING

public class Calculator {

// Method to add two integers


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

// Method to add three integers


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

// Method to add two double numbers


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

// Method to add three double numbers


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

// Main method to test the overloaded methods


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

// Testing the add method with different parameters


System.out.println("Sum of 10 and 20: " + calc.add(10, 20)); //
Calls add(int, int)
System.out.println("Sum of 10, 20, and 30: " + calc.add(10, 20,
30)); // Calls add(int, int, int)
System.out.println("Sum of 10.5 and 20.5: " + calc.add(10.5,
20.5)); // Calls add(double, double)
System.out.println("Sum of 10.5, 20.5, and 30.5: " +
calc.add(10.5, 20.5, 30.5)); // Calls add(double, double, double)
}

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

6
JAVA PROGRAMING

}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

7
JAVA PROGRAMING

Program no-5
WAP in java to implement Method Overriding.
// Superclass
class Animal {
// Method to be overridden
public void makeSound() {
System.out.println("The animal makes a sound");
}
}

// Subclass
class Dog extends Animal {
// Overriding the makeSound method
@Override
public void makeSound() {
System.out.println("The dog barks");
}
}

// Another Subclass
class Cat extends Animal {
// Overriding the makeSound method
@Override

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

8
JAVA PROGRAMING

public void makeSound() {


System.out.println("The cat meows");
}
}

public class MethodOverridingDemo {


public static void main(String[] args) {
// Creating instances of Animal, Dog, and Cat
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();

// Calling the makeSound method on different objects


myAnimal.makeSound(); // Calls makeSound() of Animal
myDog.makeSound(); // Calls makeSound() of Dog
myCat.makeSound(); // Calls makeSound() of Cat
}
}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

9
JAVA PROGRAMING

Program no-6
WAP in java to implement Static method, static class
and static Variables.

public class StaticDemo {

// Static variable
static int count = 0;

// Static method
static void displayCount() {
System.out.println("Count: " + count);
}

// Static nested class


static class NestedStaticClass {
void show() {
System.out.println("Inside static nested class.");
}
}

// Non-static method to increment count


void increment() {
count++;
}

public static void main(String[] args) {


// Accessing static variable and method without creating an
instance
StaticDemo.displayCount(); // Count: 0

// Creating an instance of StaticDemo and using non-static


method

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

10
JAVA PROGRAMING

StaticDemo demo = new StaticDemo();


demo.increment();
demo.increment();

// Accessing static variable and method after incrementing


StaticDemo.displayCount(); // Count: 2

// Creating an instance of static nested class


StaticDemo.NestedStaticClass nested = new
StaticDemo.NestedStaticClass();
nested.show(); // Inside static nested class.
}
}
Result:

Program no-7

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

11
JAVA PROGRAMING

WAP in java to implement static and instance block.


public class BlockDemo {

// Static variable
static int staticCount;

// Instance variable
int instanceCount;

// Static block
static {
staticCount = 10;
System.out.println("Static block executed. Static count: " +
staticCount);
}

// Instance block
{
instanceCount = 5;
System.out.println("Instance block executed. Instance count: " +
instanceCount);
}

// Constructor

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

12
JAVA PROGRAMING

public BlockDemo() {
System.out.println("Constructor executed.");
}

public static void main(String[] args) {


System.out.println("Main method started.");

// Creating the first instance of BlockDemo


BlockDemo demo1 = new BlockDemo();

// Creating the second instance of BlockDemo


BlockDemo demo2 = new BlockDemo();

System.out.println("Main method ended.");


}
}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

13
JAVA PROGRAMING

Program no-8
WAP in Java to implement Single Inheritance.
// Superclass
class Animal {
// Method of the superclass
void eat() {
System.out.println("This animal eats food.");

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

14
JAVA PROGRAMING

}
}

// Subclass
class Dog extends Animal {
// Method of the subclass
void bark() {
System.out.println("The dog barks.");
}
}

public class SingleInheritanceDemo {


public static void main(String[] args) {
// Creating an instance of the subclass
Dog myDog = new Dog();

// Calling methods of the superclass and subclass


myDog.eat(); // Method inherited from Animal
myDog.bark(); // Method of Dog
}
}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

15
JAVA PROGRAMING

Program no-9
WAP in Java to implement Multilevel Inheritance.
// Base class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

16
JAVA PROGRAMING

// Derived class
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}

// Further derived class


class Puppy extends Dog {
void weep() {
System.out.println("The puppy weeps.");
}
}

public class MultilevelInheritanceDemo {


public static void main(String[] args) {
// Creating an instance of the further derived class
Puppy myPuppy = new Puppy();

// Calling methods from the base class, derived class, and further
derived class
myPuppy.eat(); // Method inherited from Animal
myPuppy.bark(); // Method inherited from Dog
myPuppy.weep(); // Method of Puppy
}
}

Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

17
JAVA PROGRAMING

Program no-10
WAP in Java to implement Hierarchical Inheritance.
// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

18
JAVA PROGRAMING

}
}

// Subclass 1
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}

// Subclass 2
class Cat extends Animal {
void meow() {
System.out.println("The cat meows.");
}
}

public class HierarchicalInheritanceDemo {


public static void main(String[] args) {
// Creating instances of the subclasses
Dog myDog = new Dog();
Cat myCat = new Cat();

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

19
JAVA PROGRAMING

// Calling methods from the superclass and the respective


subclasses
myDog.eat(); // Method inherited from Animal
myDog.bark(); // Method of Dog

myCat.eat(); // Method inherited from Animal


myCat.meow(); // Method of Cat
}
}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

20
JAVA PROGRAMING

Program no-11
WAP in java to show the use of Abstract Class.
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
abstract void makeSound();

// Concrete method
void eat() {
System.out.println("This animal eats food.");
}
}

// Subclass 1
class Dog extends Animal {
// Implementation of the abstract method
void makeSound() {
System.out.println("The dog barks.");
}
}

// Subclass 2
class Cat extends Animal {

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

21
JAVA PROGRAMING

// Implementation of the abstract method


void makeSound() {
System.out.println("The cat meows.");
}
}

public class AbstractClassDemo {


public static void main(String[] args) {
// Creating instances of the subclasses
Dog myDog = new Dog();
Cat myCat = new Cat();

// Calling methods from the superclass and the respective


subclasses
myDog.eat(); // Method inherited from Animal
myDog.makeSound(); // Method of Dog

myCat.eat(); // Method inherited from Animal


myCat.makeSound(); // Method of Cat
}
}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

22
JAVA PROGRAMING

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

23
JAVA PROGRAMING

Program no-12
WAP in java to show the use of interface.
// Interface
interface Animal {
// Abstract method (does not have a body)
void makeSound();

// Default method
default void eat() {
System.out.println("This animal eats food.");
}
}

// Class implementing the interface


class Dog implements Animal {
// Implementation of the abstract method
public void makeSound() {
System.out.println("The dog barks.");
}
}

// Another class implementing the interface


class Cat implements Animal {

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

24
JAVA PROGRAMING

// Implementation of the abstract method


public void makeSound() {
System.out.println("The cat meows.");
}
}

public class InterfaceDemo {


public static void main(String[] args) {
// Creating instances of the implementing classes
Dog myDog = new Dog();
Cat myCat = new Cat();

// Calling methods defined in the interface and implemented by


the classes
myDog.eat(); // Default method from the interface
myDog.makeSound(); // Method implemented in Dog

myCat.eat(); // Default method from the interface


myCat.makeSound(); // Method implemented in Cat
}
}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

25
JAVA PROGRAMING

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

26
JAVA PROGRAMING

Program no-13
WAP in java to show the use of try catch and finally.

public class TryCatchFinallyDemo {


public static void main(String[] args) {
// Example of try, catch, and finally
try {
// Code that may throw an exception
int[] numbers = {1, 2, 3};
System.out.println("Element at index 3: " + numbers[3]);
} catch (ArrayIndexOutOfBoundsException e) {
// Code to handle the exception
System.out.println("Exception caught: Array index is out of
bounds.");
} finally {
// Code that will always execute
System.out.println("The 'try catch' block has finished
executing.");
}

// Another example
try {
int result = 10 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero.");
} finally {
System.out.println("The 'try catch' block has finished
executing.");
}
}
} public class TryCatchFinallyDemo {
public static void main(String[] args) {
// Example of try, catch, and finally

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

27
JAVA PROGRAMING

try {
// Code that may throw an exception
int[] numbers = {1, 2, 3};
System.out.println("Element at index 3: " + numbers[3]);
} catch (ArrayIndexOutOfBoundsException e) {
// Code to handle the exception
System.out.println("Exception caught: Array index is out of
bounds.");
} finally {
// Code that will always execute
System.out.println("The 'try catch' block has finished
executing.");
}

// Another example
try {
int result = 10 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero.");
} finally {
System.out.println("The 'try catch' block has finished
executing.");
}
}
}
Result:

Program no-14

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

28
JAVA PROGRAMING

WAP in java to show the use of try with multiple catch.


public class MultipleCatchDemo {
public static void main(String[] args) {
// Example of try with multiple catch blocks
try {
// Code that may throw multiple types of exceptions
int[] numbers = {1, 2, 3};
int result = numbers[1] / 0; // This will throw
ArithmeticException
System.out.println("Result: " + result);

System.out.println("Element at index 5: " + numbers[5]); //


This will throw ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
// Handle arithmetic exception (division by zero)
System.out.println("ArithmeticException caught: Division by
zero.");
} catch (ArrayIndexOutOfBoundsException e) {
// Handle array index out-of-bounds exception
System.out.println("ArrayIndexOutOfBoundsException
caught: Array index is out of bounds.");
} catch (Exception e) {
// Handle any other exceptions
System.out.println("Exception caught: " + e);
} finally {

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

29
JAVA PROGRAMING

// Code that will always execute


System.out.println("The 'try catch' block has finished
executing.");
}
}
}
Result:

Or

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

30
JAVA PROGRAMING

Program no-15
WAP in java to show the use of nested try and catch.
public class NestedTryCatchDemo {
public static void main(String[] args) {
// Outer try block
try {
// Code that may throw exceptions
int[] numbers = {1, 2, 3};
System.out.println("Element at index 1: " + numbers[1]);

// Inner try block


try {
int result = numbers[1] / 0; // This will throw
ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Inner catch: ArithmeticException
caught - Division by zero.");
}

// Accessing an invalid index


System.out.println("Element at index 5: " + numbers[5]); //
This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

31
JAVA PROGRAMING

System.out.println("Outer catch:
ArrayIndexOutOfBoundsException caught - Array index is out of
bounds.");
} catch (Exception e) {
System.out.println("Outer catch: Exception caught - " + e);
} finally {
System.out.println("The outer 'try catch' block has finished
executing.");
}
}
}
Result:

Or

Program no-16

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

32
JAVA PROGRAMING

WAP in java to implement custom exception


(AgeException) using throw and throws.

public class AgeException extends Exception {


public AgeException(String message) {
super(message);
}
}
public class CustomExceptionDemo {
// Method that checks age and throws AgeException
public static void checkAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age is less than 18. Access
denied.");
} else {
System.out.println("Age is " + age + ". Access granted.");
}
}

public static void main(String[] args) {


try {
checkAge(16); // This will throw AgeException
} catch (AgeException e) {
System.out.println("Exception caught: " + e.getMessage());
}

try {
checkAge(20); // This will not throw AgeException
} catch (AgeException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}

Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

33
JAVA PROGRAMING

Program no-17
WAP in java Create multithreading using Thread Class
and show the use of important Methods of Thread class.

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

34
JAVA PROGRAMING

(getName(),setName(), getPriority(),
setPriority(),getID(), join()).
class MyThread extends Thread {
public MyThread(String name) {
super(name); // Set the thread name
}

@Override
public void run() {
try {
for (int i = 1; i <= 5; i++) {
System.out.println(getName() + " - Count: " + i);
Thread.sleep(500); // Sleep for 500 milliseconds
}
} catch (InterruptedException e) {
System.out.println(getName() + " interrupted.");
}
}
}
public class MultithreadingDemo {
public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread-1");
MyThread thread2 = new MyThread("Thread-2");

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

35
JAVA PROGRAMING

// Set thread priority


thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);

System.out.println(thread1.getName() + " ID: " +


thread1.getId());
System.out.println(thread2.getName() + " ID: " +
thread2.getId());

thread1.start();
thread2.start();

try {
// Main thread waits for thread1 and thread2 to finish
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}

System.out.println("Thread-1 Priority: " + thread1.getPriority());


System.out.println("Thread-2 Priority: " + thread2.getPriority());

thread1.setName("Renamed-Thread-1");

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

36
JAVA PROGRAMING

System.out.println("Renamed Thread-1: " + thread1.getName());

System.out.println("Main thread execution completed.");


}
}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

37
JAVA PROGRAMING

Program no-18
WAP in java to create thread using Runnable interface
and show the use of printStacktrace(), toString(), and
getMessage() methods.
// Define a class that implements Runnable interface
class MyRunnable implements Runnable {
public void run() {
try {
// Simulate some work that might throw an exception
int result = 10 / 0; // This will cause ArithmeticException
} catch (ArithmeticException e) {
// Print stack trace using printStackTrace() method
e.printStackTrace();

// Get and print exception message using getMessage() method


System.out.println("Exception Message: " + e.getMessage());
}
}
}

public class Main {


public static void main(String[] args) {
// Create a new thread with MyRunnable as the target

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

38
JAVA PROGRAMING

Thread thread = new Thread(new MyRunnable());

// Start the thread


thread.start();

// Demonstrate toString() method of exception


try {
throw new NullPointerException("Explicitly thrown
exception");
} catch (NullPointerException e) {
// Print using toString() method
System.out.println("Exception toString(): " + e.toString());
}
}
}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

39
JAVA PROGRAMING

Program no-19
Write a program in java to create a String ans show the
use of equals() and ==.
public class StringComparisonExample {
public static void main(String[] args) {
// Creating two String objects
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");

// Using == operator to compare references


System.out.println("Using == operator:");
System.out.println("s1 == s2: " + (s1 == s2)); // true (references
are the same)
System.out.println("s1 == s3: " + (s1 == s3)); // false (references
are different)

// Using equals() method to compare contents


System.out.println("\nUsing equals() method:");
System.out.println("s1.equals(s2): " + s1.equals(s2)); // true
(contents are the same)
System.out.println("s1.equals(s3): " + s1.equals(s3)); // true
(contents are the same)

// Modify s1 to demonstrate immutability of Strings

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

40
JAVA PROGRAMING

s1 = s1 + " World";
// Check again
System.out.println("\nAfter modification:");
System.out.println("s1: " + s1);
System.out.println("s2: " + s2);
System.out.println("s3: " + s3);
System.out.println("s1 == s2: " + (s1 == s2)); // false (references
are different after modification)
System.out.println("s1.equals(s2): " + s1.equals(s2)); // false
(contents are different after modification)
}
}
Result:

Program no-20

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

41
JAVA PROGRAMING

Write a program in java to remove all extra spaces from


a paragraph.
public class RemoveExtraSpaces {
public static void main(String[] args) {
String paragraph = " This is a paragraph with extra
spaces. ";

// Remove extra spaces using regular expression


String cleanedParagraph = paragraph.trim().replaceAll("\\s+", "
");

// Display original and cleaned paragraph


System.out.println("Original Paragraph:");
System.out.println(paragraph);
System.out.println("\nParagraph after removing extra spaces:");
System.out.println(cleanedParagraph);
}
}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

42
JAVA PROGRAMING

Program no-21
Write a program in java to show the use of default and static methods.
// Define an interface with default and static methods
interface MyInterface {
// Abstract method (public and abstract by default)
void abstractMethod();

// Default method (with default implementation)


default void defaultMethod() {
System.out.println("This is a default method in MyInterface");
}

// Static method (with static implementation)


static void staticMethod() {
System.out.println("This is a static method in MyInterface");
}
}

// Implementing class that implements MyInterface


class MyClass implements MyInterface {
// Implementing the abstract method
@Override
public void abstractMethod() {

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

43
JAVA PROGRAMING

System.out.println("Abstract method implementation in


MyClass");
}
}

public class Main {


public static void main(String[] args) {
// Create an object of MyClass
MyClass obj = new MyClass();

// Call abstract method implemented in MyClass


obj.abstractMethod();

// Call default method from interface


obj.defaultMethod();
// Call static method from interface
MyInterface.staticMethod();
}
}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

44
JAVA PROGRAMING

Program no-22
Write a program in java to show the use of Lambda of
single argument, no argument and two arguments.
// Functional interface with single abstract method (SAM)
interface SingleArgument {
void printMessage(String message);
}

// Functional interface with no abstract method (to demonstrate no-


argument lambda)
interface NoArgument {
void display();
}

// Functional interface with two abstract methods (to demonstrate two-


argument lambda)
interface TwoArguments {
int multiply(int a, int b);
}

public class LambdaExamples {


public static void main(String[] args) {
// Lambda expression with single argument

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

45
JAVA PROGRAMING

SingleArgument singleArgument = message ->


System.out.println("Message: " + message);
singleArgument.printMessage("Lambda with single argument");

// Lambda expression with no arguments


NoArgument noArgument = () -> System.out.println("Lambda
with no arguments");
noArgument.display();

// Lambda expression with two arguments


TwoArguments twoArguments = (a, b) -> a * b;
int result = twoArguments.multiply(5, 10);
System.out.println("Result of multiplication: " + result);
}
}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

46
JAVA PROGRAMING

Program no-23
Write a program in java to show the use of method
reference.
import java.util.ArrayList;
import java.util.List;

// A functional interface with a method that takes a String argument


and returns void
interface StringProcessor {
void process(String s);
}

public class MethodReferenceExample {

// Static method to print a string


static void print(String s) {
System.out.println("Printing: " + s);
}

public static void main(String[] args) {


List<String> strings = new ArrayList<>();
strings.add("Java");
strings.add("is");
strings.add("awesome");

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

47
JAVA PROGRAMING

// Using lambda expression to call static method 'print'


strings.forEach(s -> MethodReferenceExample.print(s));

// Method reference to static method 'print'


strings.forEach(MethodReferenceExample::print);

// Using method reference with an instance method


StringProcessor processor = System.out::println;
strings.forEach(processor::process);
}
}
Result:

Program no-24

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

48
JAVA PROGRAMING

Write a program in java to create a Stream of Integers


and find the sum of all Even Integers.
import java.util.Arrays;
public class SumOfEvenIntegers {
public static void main(String[] args) {
// Create an array of integers
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Create a stream of integers from the array
int sumOfEvens = Arrays.stream(numbers)
// Filter even numbers
.filter(n -> n % 2 == 0)
// Sum the filtered numbers
.sum();

// Print the sum of even integers


System.out.println("Sum of even integers: " + sumOfEvens);
}
}
Result:

Program no-25

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

49
JAVA PROGRAMING

Write a program in java to create a LinkedList and copy


all the value to ArrayList.
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.List;

public class LinkedListToArrayList {


public static void main(String[] args) {
// Create a LinkedList
LinkedList<String> linkedList = new LinkedList<>();

// Add elements to the LinkedList


linkedList.add("Apple");
linkedList.add("Banana");
linkedList.add("Cherry");
linkedList.add("Date");

// Create an ArrayList
List<String> arrayList = new ArrayList<>(linkedList); //
Copying LinkedList to ArrayList

// Print the original LinkedList


System.out.println("Original LinkedList:");
System.out.println(linkedList);

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

50
JAVA PROGRAMING

// Print the ArrayList


System.out.println("\nCopied ArrayList:");
System.out.println(arrayList);
}
}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

51
JAVA PROGRAMING

Program no-26
Write a program in java to input a paragraph and find
the occurrence of each unique words.
import java.util.*;

public class WordOccurrence {


public static void main(String[] args) {
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);

// Prompt user to enter a paragraph


System.out.println("Enter a paragraph:");
String paragraph = scanner.nextLine();

// Close the scanner after input


scanner.close();

// Remove punctuation and convert to lowercase


paragraph = paragraph.replaceAll("[^a-zA-Z ]",
"").toLowerCase();

// Split paragraph into words


String[] words = paragraph.split("\\s+");

// Create a HashMap to store word counts


Map<String, Integer> wordCountMap = new HashMap<>();

// Iterate through each word and update the count in the


HashMap
for (String word : words) {
if (word.length() > 0) { // Check if the word is not empty
if (wordCountMap.containsKey(word)) {
wordCountMap.put(word, wordCountMap.get(word) +
1);

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

52
JAVA PROGRAMING

} else {
wordCountMap.put(word, 1);
}
}
}

// Print the occurrences of each unique word


System.out.println("\nOccurrences of each word:");
for (Map.Entry<String, Integer> entry :
wordCountMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

53
JAVA PROGRAMING

Program no-27
Write a program in java to create a Employee class and
sort the object of this class using Comparable.
// Employee class implementing Comparable interface
class Employee implements Comparable<Employee> {
private int id;
private String name;
private int age;
private double salary;

// Constructor
public Employee(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}

// Getter methods
public int getId() {
return id;
}

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

54
JAVA PROGRAMING

public String getName() {


return name;
}

public int getAge() {


return age;
}

public double getSalary() {


return salary;
}

// Implementing compareTo method for natural ordering


@Override
public int compareTo(Employee other) {
// Compare employees based on their ids
return Integer.compare(this.id, other.id);
}

// toString method to print Employee details


@Override
public String toString() {
return "Employee{" +
"id=" + id +

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

55
JAVA PROGRAMING

", name='" + name + '\'' +


", age=" + age +
", salary=" + salary +
'}';
}
}

public class EmployeeSortingExample {


public static void main(String[] args) {
// Create an ArrayList of Employee objects
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(101, "John Doe", 30, 55000.0));
employees.add(new Employee(102, "Jane Smith", 28, 50000.0));
employees.add(new Employee(103, "Michael Johnson", 35,
60000.0));
employees.add(new Employee(104, "Emily Davis", 27,
52000.0));

// Print the list before sorting


System.out.println("Employees before sorting:");
for (Employee emp : employees) {
System.out.println(emp);
}

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

56
JAVA PROGRAMING

// Sort the employees using Collections.sort() which uses


compareTo method
Collections.sort(employees);

// Print the list after sorting


System.out.println("\nEmployees after sorting by id:");
for (Employee emp : employees) {
System.out.println(emp);
}
}
}
Result:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

57
JAVA PROGRAMING

Program no-28
Write a program in java to create a Employee class and
sort the object of this class using Comparator of many
field.
public class Employee {
private String name;
private int id;
private double salary;

// Constructor
public Employee(String name, int id, double salary) {
this.name = name;
this.id = id;
this.salary = salary;
}

// Getters
public String getName() {
return name;
}

public int getId() {


return id;

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

58
JAVA PROGRAMING

public double getSalary() {


return salary;
}

// Override the toString method for easy printing


@Override
public String toString() {
return "Employee{name='" + name + "', id=" + id + ", salary=" +
salary + '}';
}
}
import java.util.Comparator;

public class EmployeeComparators {

// Comparator to sort by salary, then by name, and then by ID


public static final Comparator<Employee>
BY_SALARY_NAME_ID = (e1, e2) -> {
int salaryCompare = Double.compare(e1.getSalary(),
e2.getSalary());
if (salaryCompare != 0) {
return salaryCompare;
}

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

59
JAVA PROGRAMING

int nameCompare = e1.getName().compareTo(e2.getName());


if (nameCompare != 0) {
return nameCompare;
}
return Integer.compare(e1.getId(), e2.getId());
};
// You can define more comparators if needed
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Create a list of Employee objects
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("Alice", 1, 50000));
employees.add(new Employee("Bob", 2, 75000));
employees.add(new Employee("Charlie", 3, 50000));
employees.add(new Employee("Alice", 4, 50000));
employees.add(new Employee("Charlie", 5, 60000));
// Print unsorted list
System.out.println("Unsorted list:");
for (Employee emp : employees) {
System.out.println(emp);

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

60
JAVA PROGRAMING

}
// Sort the list using the comparator
Collections.sort(employees,
EmployeeComparators.BY_SALARY_NAME_ID);
// Print sorted list
System.out.println("\nSorted list (by salary, then name, then
ID):");
for (Employee emp : employees) {
System.out.println(emp);
}
}
}
Result:

Program no-29
Write a program in java to implement Set interface.

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

61
JAVA PROGRAMING

Using hashset
import java.util.HashSet;
import java.util.Set;

public class HashSetExample {


public static void main(String[] args) {
// Create a HashSet
Set<String> hashSet = new HashSet<>();

// Add elements to the HashSet


hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
hashSet.add("Apple"); // Duplicate element, will not be added

// Print the HashSet


System.out.println("HashSet: " + hashSet);

// Check if an element exists


System.out.println("Contains 'Banana': " +
hashSet.contains("Banana"));

// Remove an element
hashSet.remove("Banana");

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

62
JAVA PROGRAMING

System.out.println("HashSet after removing 'Banana': " +


hashSet);

// Iterate through the HashSet


System.out.println("Iterating over HashSet:");
for (String fruit : hashSet) {
System.out.println(fruit);
}
}
}
Result:

Using linked hashset:


import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetExample {


public static void main(String[] args) {
// Create a LinkedHashSet
Set<String> linkedHashSet = new LinkedHashSet<>();

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

63
JAVA PROGRAMING

// Add elements to the LinkedHashSet


linkedHashSet.add("Apple");
linkedHashSet.add("Banana");
linkedHashSet.add("Orange");
linkedHashSet.add("Apple"); // Duplicate element, will not be
added

// Print the LinkedHashSet


System.out.println("LinkedHashSet: " + linkedHashSet);

// Check if an element exists


System.out.println("Contains 'Banana': " +
linkedHashSet.contains("Banana"));

// Remove an element
linkedHashSet.remove("Banana");
System.out.println("LinkedHashSet after removing 'Banana': " +
linkedHashSet);

// Iterate through the LinkedHashSet


System.out.println("Iterating over LinkedHashSet:");
for (String fruit : linkedHashSet) {
System.out.println(fruit);
}

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

64
JAVA PROGRAMING

}
}
Result:

Using treeset:
import java.util.Set;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
// Create a TreeSet
Set<String> treeSet = new TreeSet<>();
// Add elements to the TreeSet
treeSet.add("Apple");
treeSet.add("Banana");
treeSet.add("Orange");
treeSet.add("Apple"); // Duplicate element, will not be added
// Print the TreeSet
System.out.println("TreeSet: " + treeSet);
// Check if an element exists

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

65
JAVA PROGRAMING

System.out.println("Contains 'Banana': " +


treeSet.contains("Banana"));
// Remove an element
treeSet.remove("Banana");
System.out.println("TreeSet after removing 'Banana': " +
treeSet);
// Iterate through the TreeSet
System.out.println("Iterating over TreeSet:");
for (String fruit : treeSet) {
System.out.println(fruit);
}
}
}
Result:

Program no-30
Write a program in java to implement HashMap and
TreeMap.
import java.util.HashMap;
import java.util.Map;

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

66
JAVA PROGRAMING

import java.util.TreeMap;

public class MapExample {


public static void main(String[] args) {
// Using HashMap
Map<String, Integer> hashMap = new HashMap<>();

// Adding elements to HashMap


hashMap.put("Apple", 3);
hashMap.put("Banana", 2);
hashMap.put("Orange", 4);
hashMap.put("Grapes", 5);

// Printing the HashMap


System.out.println("HashMap:");
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

// Accessing an element
System.out.println("\nValue for 'Banana': " +
hashMap.get("Banana"));

// Removing an element

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

67
JAVA PROGRAMING

hashMap.remove("Orange");
System.out.println("\nHashMap after removing 'Orange':");
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

// Using TreeMap
Map<String, Integer> treeMap = new TreeMap<>();

// Adding elements to TreeMap


treeMap.put("Apple", 3);
treeMap.put("Banana", 2);
treeMap.put("Orange", 4);
treeMap.put("Grapes", 5);

// Printing the TreeMap


System.out.println("\nTreeMap:");
for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

// Accessing an element
System.out.println("\nValue for 'Banana': " +
treeMap.get("Banana"));

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

68
JAVA PROGRAMING

// Removing an element
treeMap.remove("Orange");
System.out.println("\nTreeMap after removing 'Orange':");
for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Result for hashmap:

Result for treemap:

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

69
JAVA PROGRAMING

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

70
JAVA PROGRAMING

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

71
JAVA PROGRAMING

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

72
JAVA PROGRAMING

Computer Science & Engineering Department


Khushi chaudary (2202300100091)

73

You might also like