FACULTY OF ENGINEERING AND TECHNOLOGY BACHELOR OF TECHNOLOGY

 

 

Object Oriented Programming (303105206)

 

 

SEMESTER III

Information Technology

 

 


 

 



 

CERTIFICATE

This is to certify that

 

 

 

Mr.SATHYAJIT HALDAR with Enrollment No 2303031087078

successfully completed his/her laboratory Oriented Programming(303105206) from has

experiments Object the department of Information Technology during the academic year 2023-2024.


 

 

 

 

 

 

 

 

 

 


 

 

 

Date of Submission ….……………                        Staff In charge …..……………

 

 

 

Head of Department………….……


 


 

 

INDEX


Faculty of Engineering & Technology Subject Name: OOPS

B.Tech.      IT   Year    2      Semester 3_


 

SR.NO

Experment Title

Page No

Dateof Performanc

e

Date of Submissi o

n

Marks

Sign

From

To

1

Write Program to print hello world

 

 

 

 

 

 

2

Write a program that prints the numbers from 1

to

100 and for multiples of ‘3’ print “Fizz” instead

of the number and for the multiples of ‘5’ print “Buzz”.

 

 

 

 

 

 

3

write a program to tell whether a number is even

or odd.

 

 

 

 

 

 

4

Write a program on Age calculator.

 

 

 

 

 

 

5

Write a program on temperature Conversion

 

 

 

 

 

 

6.

Write a program to calculate a weight on mars.

 

 

 

 

 

 

7.

Write a program calculates the distance between two

cities based on their latitude and longitude coordinates. All you need to do is ask the user for the latitude and longitude of two cities and then

print out the distance between them.

 

 

 

 

 

 

8.

Write a program calculates the amount of interest

earned on an investment over a period of time and is among simpler programs of Java for a starting Java developer. All you need to do is ask the user for the initial investment amount, the interest rate, and the number of years. Then print out the total amount of interest earned. Use

Java exponentiation to calculate the compounding interest.

 

 

 

 

 

 

9.

Write a program should print a diamond shape to the console. The user should specify the height of the diamond, which will always be an odd number. For example, if the user specifies a

height of 5.

 

 

 

 

 

 

10.

Write a program for a given array of 0s 1s and

2s segregate them

 

 

 

 

 

 

11.

Write a program to find the sum of all elements in

the array

 

 

 

 

 

 

12.

Write a program to Java Program to Create the

Object

and the use of it

 

 

 

 

 

 

13.

Write a program should generate a random number

between 1 and 100, and then ask the user to guess the number. If the user’s guess is too high or too low, the program should give them a hint and let them try again. The program should keep track of

how many guesses the user has made, and end when the user has guessed the number correctly.

 

 

 

 

 

 


 

Faculty of Engineering & Technology Subject Name: OOPS

B.Tech.      IT   Year    2      Semester 3_

INDEX

 

14.

(A)     Write a java program to show the importance of Encapsulation.

(B) Write a program to show the importance of

Inheritance.

(C) Write a program to show the Importance of Polymorphism.

(D)   Write a program to use super class with variables

 

 

 

 

 

 

15.

Write a program to use super class with methods

 

 

 

 

 

 

16.

Write a program to find the Importance and

working Inner class

 

 

 

 

 

 

17.

Write a program on Implementing Interfaces.

 

 

 

 

 

 

18.

Write a java program on Creating Packages

 

 

 

 

 

 

19.

(A)  Write a program on String Buffer and its

methods

(B)        Write a program on String Builder and String Buffer methods

(C)  Write a program on String Manipulation

 

 

 

 

 

 

20.

Write Java Program on Exceptional Handling

 

 

 

 

 

 

21.

(A)        Write a program on Multi-Threading

extending the thread class

(B)    Thread Creation by Runnable Interface

 

 

 

 

 

 

22.

Write a java program Implementing Array

 

 

 

 

 

 

23.

Write a java program Implementing Array List 2

 

 

 

 

 

 

24.

Write a java program on Vectors

 

 

 

 

 

 

25.

Program on Frame works -1

 

 

 

 

 

 

26.

Write Program on J Frame Work -2

 

 

 

 

 

 

 


 

 

 

 


PRACTICAL: 01

    - Write a program to print Hello World.

Source Code

class hello

{

public static void main(String[] args)

{

System.out.print("hello world!!");

}

}

OUTPUT:



 

 


 


PRACTICAL: 02


- Write a program that prints the numbers from1 to 100 and for multiples of ‘3’ print “Fizz” instead of the number and for the multiples of‘5’ print “Buzz”.

Source code:

public class Main{

public static void main(String args[]) { for (int i=1; i<=100; i++){

if (i%3==0){

System.out.print("Fizz"+" ");

}

else if (i%5==0) { System.out.print("Buzz"+" ");

 

}

else { System.out.print(i+" ");

 

}

}

}

}

OUTPUT:


 


PRACTICAL: 03

     - write a program to tell whether a number is even or odd.

Source code:

import java.util.Scanner; public class EvenOdd {

public static void main(String[] args) {

Scanner reader = new Scanner(System.in); System.out.print("Enter a number: ");

int num = reader.nextInt();

 if(num% 2 == 0) System.out.println(num+ " is even");

 else

System.out.println(num+ " is odd");

}

}

 


OUTPUT:


 


PRACTICAL: 04

Write a program on Age calculator.

Source code:

import java.util.Scanner;

import java.util.Calendar;

 

public class AgeCalculator {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

       

        System.out.print("Enter your birth year: ");

        int birthYear = scanner.nextInt();

       

        // Get the current year from the system

        int currentYear = Calendar.getInstance().get(Calendar.YEAR);

       

        // Calculate the age

        int age = currentYear - birthYear;

       

        System.out.println("Your age is: " + age + " years");

       

        scanner.close();

    }

}



 

 

 

 

 


       OUTPUT:


 


          PRACTICAL: 05

Write a program on temperature Conversion.

 

Source Code:

 

import java.util.Scanner;

 

public class Temp {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Temperature in Celsius: ");

        double celsius = scanner.nextDouble();

       

        double fahrenheit = (celsius * 9 / 5) + 32;

        System.out.println("Temperature in Fahrenheit: " + fahrenheit);

       

        double kelvin = celsius + 273.15;

        System.out.println("Temperature in Kelvin: " + kelvin);

       

        scanner.close();

    }

}


OUTPUT:


 

 

 


PRACTICAL:06

     –Write a program to calculate a weight on mars.

Source code:

 

import java.util.Scanner;

 

public class WeightOnMars {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your weight on Earth (in kilograms): ");

        double weightOnEarth = scanner.nextDouble();

        double accelerationOnMars = 3.72076;

 

        double weightOnMars = (weightOnEarth / 9.81) * accelerationOnMars;

 

        System.out.println("Your weight on Mars would be approximately: " +

weightOnMars + " kilograms");

 

        scanner.close();

    }

}


 

 

 


OUTPUT:


 

 

 

 

 

 

 

 


 

 


PRACTICAL:07

– Write a program calculates the distance between two cities based on their latitude and longitude coordinates. All you need to do is ask the user for the latitude and longitude of two cities and then print out the distance between them.

Source Code:

 

import java.util.Scanner;

 

public class Distance{

    public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {

        double radius = 6371.0;

 

        lat1 = Math.toRadians(lat1);

        lon1 = Math.toRadians(lon1);

        lat2 = Math.toRadians(lat2);

        lon2 = Math.toRadians(lon2);

 

        double dlon = lon2 - lon1;

        double dlat = lat2 - lat1;

 

        double a = Math.sin(dlat / 2) * Math.sin(dlat / 2) +

                Math.cos(lat1) * Math.cos(lat2) * Math.sin(dlon / 2) * Math.sin(dlon / 2);

 

        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        double distance = radius * c;

 

        return distance;

    }

 

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the latitude of the first city: ");

        double lat1 = scanner.nextDouble();

 

        System.out.print("Enter the longitude of the first city: ");

        double lon1 = scanner.nextDouble();

 

        System.out.print("Enter the latitude of the second city: ");

        double lat2 = scanner.nextDouble();

 

        System.out.print("Enter the longitude of the second city: ");

        double lon2 = scanner.nextDouble();

 

        double distance = calculateDistance(lat1, lon1, lat2, lon2);

        System.out.println("The distance between the two cities is " + distance + " kilometers.");

 

        scanner.close();

    }

}

 

 


OUTPUT:


 

 

 

 


PRACTICAL:08

– Write a program calculates the amount of interest earned on an investment over a period of                          time and is among simpler programs of Java for a starting Java developer. All you need to do is ask the user for the initial investment amount, the interest rate, and the number of years. Then print out the total amount of interest earned. Use Java exponentiation to calculate the compounding interest.

Source code:

 

import java.util.Scanner;

 

public class Intrest {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

 

        System.out.print("Enter the initial investment amount: ");

        double principal = scanner.nextDouble();

 

        System.out.print("Enter the annual interest rate (in percentage): ");

        double annualInterestRate = scanner.nextDouble();

 

        System.out.print("Enter the number of years: ");

        int years = scanner.nextInt();

 

        double interestRate = annualInterestRate / 100.0;

        double totalAmount = principal * Math.pow(1 + interestRate, years);

        double interestEarned = totalAmount - principal;

        System.out.println("The total amount of interest earned is: " + interestEarned);

 

        scanner.close();

    }

}

 


OUTPUT:


 

 


PRACTICAL:09

– Write a program should print a diamond shape to the console. The user should specify the height of the diamond, which will always be an odd number. For example, if the user specifies a height of 5.

Source code:

import java.util.Scanner;

public class Diamond {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int height;

        do {

            System.out.print("Enter the height of the diamond (odd number): ");

            height = scanner.nextInt();

        } while (height % 2 == 0);

 

        int spaces = height / 2;

        for (int i = 1; i <= height; i += 2) {

            // Print leading spaces

            for (int j = 0; j < spaces; j++) {

                System.out.print(" ");

            }

 

            // Print stars

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

                System.out.print("*");

            }

 

            System.out.println();

            spaces--;

        }

 

        spaces = 1;

        for (int i = height - 2; i >= 1; i -= 2) {

            // Print leading spaces

            for (int j = 0; j < spaces; j++) {

                System.out.print(" ");

            }

 

            // Print stars

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

                System.out.print("*");

            }

 

            System.out.println();

            spaces++;

        }

 

        scanner.close();

    }

}


 

 

 

 

 

 

 


              OUTPUT:

 

 


 

 


 

PRACTICAL:10

Write a program for a given array of 0s 1s and 2s segregate them

Source code:

public class Segregate {

public static void segregate(int[] arr) { int low = 0; int high = arr.length - 1; int mid = 0;

int temp;

 

while(mid <= high) { switch (arr[mid]) { case 0:

temp = arr[low]; arr[low] = arr[mid]; arr[mid] = temp; low++;

mid++; break;

 

case 1:

mid++; break;

case 2:

temp = arr[mid]; arr[mid] = arr[high]; arr[high] = temp; high--; break;

}

}

}


 

 

 

 


public static void printArray(int[] arr) { for (int num: arr) {

System.out.print(num+ " ");

}

System.out.println();

}

public static void main(String[] args) { int[] arr =

{ 0, 1, 2, 0, 1, 2, 1, 0 };

System.out.println("Original array:"); printArray(arr);

 

 

segregate(arr);

 

 

System.out.println("Array after segregation:"); printArray(arr);

}

}


 

 

 


OUTPUT:

 


 

 

 

 

 

 

 

 

 

 

 


 

 

 


PRACTICAL:11

Write a program to find the sum of all elements in the array

Source code:

 

        import java.util.Scanner;

 

public class ArraysumCalculator {

    public static void main(String[] args) {

        try (Scanner scanner = new Scanner(System.in)) {

            System.out.println("Enter the number of elements in the array");

            int n = scanner.nextInt();

 

            // Consume the newline character

            scanner.nextLine();

 

            int[] arr = new int[n];

            System.out.println("Enter the elements of the array");

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

                arr[i] = scanner.nextInt();

            }

            int sum = 0;

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

                sum += arr[i];

            }

            System.out.println("Sum of the elements in the array: " + sum);

        }

    }

}

         


 

 

 

 

 


OUTPUT:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


PRACTICAL:12

Write a program to Java Program to Create the Object and the use of it

Source code:

 

public class Person {

    String name;

    int age;

    //constructor to initialize the object

       public Person(String name,int age){

        this.name = name;

        this.age = age;

        System.out.println("");

    }

    //method to display information about the person

    public void displayInfo(){

        System.out.println("name:"+name);

        System.out.println("age:"+age);

    }

    public static void main(String[]args){

        //creating an object of the person class for ram

        Person ram = new Person("ram",30);

       

        //using the object to call method and access fields

        System.out.println("person 1:");

        ram.displayInfo();

       

        //creating another object of the person class for dsita

        Person sita = new Person("sita",25);

       

        //using the second object

        System.out.println("\nperson 2:");

        sita.displayInfo();

    }

}

 

 

 

 

 

 


OUTPUT:

 


 

 


PRACTICAL:13

Write a program should generate a random number between 1 and 100, and then ask the user to guess the number. If the user’s guess is too high or too low, the program should give them a hint and let them try again. The program should keep track of how many guesses the user has made, and end when the user has guessed the number correctly.

Source code:

import java.util.Random;

import java.util.Scanner;

 

public class NumberGuessingGame{

    public static void main(String[]args){

        Scanner sc = new Scanner(System.in);

        Random rm = new Random();

       

        int lowerBound = 1;

        int upperBound = 100;

        int randomNumber = rm.nextInt(upperBound - lowerBound + 1)+lowerBound;

        int numberofGuesses = 0;

        int userGuess;

       

       System.out.println("welcome to the Number guessing game");

       System.out.println("I have selected a random number between 1 and 100");

      

       while(true){

        System.out.println("Guess the number: ");

        userGuess = sc.nextInt();

        numberofGuesses++;

       

     

 

  if(userGuess == randomNumber){

        System.out.println("Congrats you gussed the right number"+randomNumber+"in"+numberofGuesses+"guesses");

        break;

        }else if(userGuess < lowerBound || userGuess > upperBound){

            System.out.println("Please guess a number between 1 and 100");

        }else if(userGuess< randomNumber){

            System.out.println("too low try again");

        }else{

            System.out.println("too high try again");

        }

       

       }

       sc.close();

    }

   

}

 


 

 


           

 

              OUTPUT:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


PRACTICAL:14(A)

 Write a program to show the importance of Encapsulation

Source code:

class Student {

    private String name;

    private int age;

 

    public Student(String name, int age) {

        this.name = name;

        this.age = age;

    }

 

    public String getName() {

        return name;

    }

 

    public int getAge() {

        return age;

    }

 

    public void displayInfo() {

        System.out.println("Student name: " + name);

        System.out.println("Student age: " + age);

    }

}

 

 


public class EncapsulationDemo {

    public static void main(String[] args) {

        Student stud = new Student("Sai", 23);

        System.out.println("Name: " + stud.getName());

        System.out.println("Age: " + stud.getAge());

        stud.displayInfo();

    }

}

OUTPUT:

 

 

 

 

 

 

 

 

 

 

 

 


PRACTICAL:14(B)

Write a program to show the importance of Inheritance

Source code:

class Animal {

    void sound() {

        System.out.println("Animal makes a sound");

    }

}

 

class Dog extends Animal {

    @Override

    void sound() {

        System.out.println("Dog barks");

    }

}

 

public class InheritanceDemo {

    public static void main(String[] args) {

        Animal animal = new Animal();

        Dog dog = new Dog();

        animal.sound();

        dog.sound();

    }

}

 

 

 

 


OUTPUT:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


PRACTICAL:14(C)

Write a program to show the Importance of Polymorphism

Source code:

class Shape {

    void draw() {

        System.out.println("Drawing the Shape");

    }

}

 

class Circle extends Shape {

    void draw() {

        System.out.println("Drawing the Circle");

    }

}

 

public class Poly {

    public static void main(String[] args) {

        Shape shape = new Circle();

        shape.draw(); // corrected the method invocation

    }

}

OUTPUT:

 

 


PRACTICAL:14(D)

Write a program to use super with variables

Source code:

class Parent {

    String message = "Hello from parent ";

}

 

class Child extends Parent {

    String message = "Hello from child";

 

    void displayMessage() {

        System.out.println("Parent message: " + super.message);

        System.out.println("Child message: " + this.message);

    }

}

 

public class SuperDemo {

    public static void main(String[] args) {

        Child child = new Child();

        child.displayMessage(); // corrected the method invocation and variable name

    }

}

 

 

 

 

 


OUTPUT:

 

 

 

 

 

 

 

 

 

 

 


PRACTICAL:15

Write a program to use super with methods

Source code:

class Parent {

    void display() {

        System.out.println("This is the parent class.");

    }

}

 

class Child extends Parent {

    @Override

    void display() {

        super.display();

        System.out.println("This is the child class.");

    }

}

 

public class SuperWithMethods {

    public static void main(String[] args) {

        Child child = new Child(); // corrected the instantiation

        child.display(); // corrected the method invocation

    }

}

 

 

 

 


OUTPUT:

 

 

 

 

 

 

 

 

 

 

 


PRACTICAL:16

Write a program to find the Importance and working of Inner class

Source code:

class OuterClass {

    private int outerData = 10;

 

    class InnerClass {

        void display() {

            System.out.println("InnerClass: Accessing outerData from InnerClass: " + outerData);

        }

    }

 

    void useInnerClass() {

        InnerClass inner = new InnerClass();

        inner.display();

    }

}

public class InnerClassDemo {

    public static void main(String[] args) {

        OuterClass outer = new OuterClass();

        OuterClass.InnerClass innerDirect = outer.new InnerClass(); // corrected the instantiation

        outer.useInnerClass();

        innerDirect.display();

    }

}

 


OUTPUT:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

PRACTICAL:17

Write a program on Implementing Interfaces

Source code:

interface Shape

{

                double calculateArea();

}

//implements the interface in a class

           class Circle implements Shape

 {  

 private double radius;

 public Circle(double radius){  

 this.radius = radius;

}

  public double calculateArea(){  

 return Math.PI*radius*radius;

}

}

public class Interface{

    public static void main(String[] args){

        Circle c = new Circle(5.0);

        double area = c.calculateArea();

       System.out.println("Area os the circle:"+ area); 

  }      

 }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

OUTPUT:

 

 

 

 

 

 

                                                                    

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


PRACTICAL:18

: Write a program on Creating Packages

Source code:

To create the package:

1.  1st create a folder for the package and the package_name is MyPack.

2.  In that MyPack folder, create a file_name on Circle.java

3.  Then write the code for the “Circle class” by using (package Mypack;).

package mypack;

public class Circle {

int r=10;     

public void area(){  

     System.out.println("Area ofthe circle is : " + (3.14*r*r));     

}

}

Implement the package:

4.     After that create a file for main class for importing it in a circle class by using (import MyPack.circle;)

import mypack.Circle;

public class Main{

  public static void main(String args[]){ 

  Circle c = new Circle();

    c.area(); 

}

}

 


                  OUTPUT:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

                                           

 

 

 

 

 

 

 

 


PRACTICAL:19

: a) Write a program on String Buffer and its methods

Source code:

public class StringBuffer {

    public static void main(String[] args) {

    StringBuffer buffer = new StringBuffer("Hello, ");

    buffer.insert(6,"java").append("World!").delete(0,6).reverse();

    System.out.println(buffer.toString());       

}

}  

 

Output:

 

 


PRACTICAL:19

: b) Write a program on String Builder and String Buffer methods

Source code:

 

public class StringBuilderAndStringBufferExample {

    public static void main(String[] args) {

        StringBuilder a = new StringBuilder("Hello, ");

        StringBuffer b = new StringBuffer("World!");

        a.append("java");

        b.append("Programming");

        System.out.println("Stringbuilder" + a.toString());

        System.out.println("StringBuffer" + b.toString());

    }

}

OUTPUT:

 

 

 

 

 

 


PRACTICAL:19

: c) Write a program on String Manipulation

Source code:

public class StringManipulationExample{

public static void main(String[]args){

  String text ="  HELLO, WORLD!  ";

  String trimmedText = text.trim();

  String lowercaseText = trimmedText.toLowerCase();

  boolean startsWithHello = lowercaseText.startsWith("hello");

  boolean containsWorld = lowercaseText.contains("world");

  String replacedText = trimmedText.replace("world", "java");

  System.out.println("Original text: " + text);

  System.out.println("Trimmed text: " + trimmedText);

  System.out.println("lowercase text: " + lowercaseText);

  System.out.println("Starts with 'hello': " + startsWithHello);

  System.out.println("Contains world: " + containsWorld);

  System.out.println("Replaced text: " + replacedText);

 

}

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


OUTPUT:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


PRACTICAL:20

: Program on Exceptional Handling

Source code:

import java.util.Scanner;

 

public class ExceptionHandlingExample {

  public static void main(String[] args) {

    Scanner scanner =new Scanner(System.in);

 

    try

      {

        System.out.println("Enter the number:");

        int divisor =scanner.nextInt();

        int result=10/divisor;

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

      } catch (ArithmeticException e){

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

      }catch(java.util.InputMismatchException e){

        System.out.println("input mismatch error: please enter a valid number");

      }finally{

        System.out.println("finally block executed");

        scanner.close();

      }

    System.out.println("program");

  }

}

 

 

 

 

 

 

 

 

 

 

 


OUTPUT:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

                                 

 

 

 


PRACTICAL:21(A)

: Write a program on Multi-Threading extending the thread class

Source code:

public class Main extends Thread {

    // Declare a String variable to represent the task.

    String task;

 

    Main(String task) {

        this.task = task; // refers to the current object in a method or constructor

    }

 

    public void run() {

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

            System.out.println(task + " : " + i);

            try {

                // Pause the thread execution for 1000 milliseconds.

                Thread.sleep(1000);

            } catch (InterruptedException ie) {

                System.out.println(ie.getMessage());

            }

        }

    }

 

    public static void main(String[] args) {

    

 

   // Create two objects to represent two tasks.

        Main th1 = new Main("Cut the ticket"); // Passing task as an argument to its constructor.

        Main th2 = new Main("Show your seat number");

 

        // Create two objects of Thread class and pass two objects as parameters to the constructor of Thread class.

        Thread t1 = new Thread(th1);

        Thread t2 = new Thread(th2);

 

        t1.start();

        t2.start();

    }

}

 

OUTPUT

 

 


PRACTICAL:21(B)

: Thread Creation by Runnable

Source code:

 

class MyRunnable implements Runnable {

public void run() {

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

System.out.println("Thread " + Thread.currentThread().getId() + ": Count " + i);

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

System.out.println(e);

}

}

}

}

public class RunnableThreadDemo {

public static void main(String[] args) {

Thread thread1 = new Thread(new MyRunnable());

Thread thread2 = new Thread(new MyRunnable());

thread1.start();

thread2.start();

}

}

 

OUTPUT:

 

 

 


PRACTICAL:22

: Write a program Implementing Array List -1

Source code:

import java.util.ArrayList;

public class ArrayListDemo {

public static void main(String[] args) {

// Create an ArrayList for String data

ArrayList<String> stringList = new ArrayList<>();

stringList.add("jai");

stringList.add("shri");

stringList.add("krishna");

System.out.println("String Data in the List:");

System.out.println(stringList);

// Create an ArrayList for Integer data

ArrayList<Integer> intList = new ArrayList<>();

intList.add(100);

intList.add(200);

intList.add(300);

System.out.println("\nInteger Data in the List:");

System.out.println(intList);

}

}

OUTPUT:

 


PRACTICAL:23

: Write a program Implementing Array List -2

Source code:

import java.util.ArrayList;

class Product {

String name;

double price;

public Product(String name, double price) {

this.name = name;

this.price = price;

}

public String toString() {

return "Product{name='" + name + "', price=" + price + '}';

}

}

public class InventorySystems {

public static void main(String[] args) {

ArrayList<Product> products = new ArrayList<>();

products.add(new Product("Laptop", 1499.99));

products.add(new Product("Smartphone", 499.99));

System.out.println("Products in the shop:");

for (Product product : products) {

System.out.println(product);

 


}

products.add(new Product("Headphones", 199.99));

System.out.println("\nProducts after adding new item:");

for (Product product : products) {

System.out.println(product);

}

}

}

OUTPUT:

 

 

 

 

 

 

 

 


PRACTICAL:24

: Write a program on Vectors

Source code:

import java.util.Iterator;

import java.util.Vector;

 

public class Main {

    public static void main(String[] a) {

        // Create a Vector to store strings

        Vector<String> vct = new Vector<String>();

        // Add elements to the Vector

        vct.add("First");

        vct.add("Second");

        vct.add("Third");

        vct.add("Random");

        // Create an Iterator to traverse the Vector

        Iterator<String> itr = vct.iterator();

        // Iterate over the Vector using the Iterator

        while (itr.hasNext()) {

            // Retrieve and print each element

            System.out.println(itr.next());

        }

    }

}

 

 

 


OUTPUT:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


PRACTICAL:25

: Program on Frameworks -1

 

Source code:

import java.util.LinkedList;

 

class LinkedListDemo {

    public static void main(String[] args) {

        LinkedList<String> languages = new LinkedList<>();

 

        // Add elements to the linked list

        languages.add("Python");

        languages.add("Java");

        languages.add("JavaScript");

 

        System.out.println("LinkedList: " + languages);

 

        // Add element with the index parameter

        languages.add(1, "C");

        System.out.println("Inserted LinkedList: " + languages);

 

        // Get the element from the linked list

        String str = languages.get(1);

        System.out.println("Element at index 1: " + str);

 

        // Update element at index 3

        languages.set(3, "HTML");

        System.out.println("Updated LinkedList: " + languages);

    }

}

 

 

 

 

 

 

 

 


OUTPUT:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


PRACTICAL:26

: Program on Frameworks -2

Source code:

 

import java.util.HashMap;

import java.util.Map;

 

public class HashMapDemo {

    public static void main(String[] args) {

        // Create a HashMap object called capitalCities

        Map<String, String> capitalCities = new HashMap<>();

       

        // Add keys and values (Country, City)

        capitalCities.put("India", "Delhi");

        capitalCities.put("Germany", "Berlin");

        capitalCities.put("Norway", "Oslo");

        capitalCities.put("USA", "Washington DC");

 

        System.out.println(capitalCities);

    }

}

OUTPUT:

 

Comments