0% found this document useful (0 votes)
30 views28 pages

Java Lab-1

Uploaded by

Sizz Rizz
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)
30 views28 pages

Java Lab-1

Uploaded by

Sizz Rizz
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
You are on page 1/ 28

JAVA LAB

INDEX
Sl. Java Program Page no.
No.
1. Write a program implementing Has-A relationship
(composition). Create necessary classes and driver
class.
2. Write a program and implement data hiding
principle. Create necessary classes and driver
class.
3. Write a program for storing subjects marks of
each individuals implementing List (ArrayList,
Linked List) also Create necessary classes and
driver class.
4. Write a program to demonstrate inheritance
(similar to ZooApp).
5. Write a program to show the difference between
static binding and dynamic binding.
6. Demonstrate different type of constructor in java.
7. Write a program and run through java and javac
(cmd).
8. Write a program using wrapper class and use
method which takes an object as a parameter.
9. Demonstrate constructor overloading in java.
10. Write a program of method overloading and
method overriding.
11. Write a program that contains interface and
abstract class.
12. Write a program in java to demonstrate the
concept of multiple inheritance through
interface

2024-501-032 Suzan Rizvi


JAVA LAB

13. Create a class Point (2-Dimensional) and


extend it to a 3-Dimensional point with class
name Point3D. Create two instances in a
separate TestPoint class (one for 2D point and
other for 3D point). Populate the values and
print the same
14. Create a class point and also create a class Line
which is composed of 2 Points StartPoint and
EndPoint. Then create a class Triangle which is
composed of three lines. Populate the values
and print the same
15. Write a program in Java to demonstrate the
concept of Exception Handling through
NullPointerException
16. Write a program in Java to demonstrate the
concept of Exception Handling through
StringIndexOutOfBoundsException.

17. Write a program in Java to demonstrate the


Concept of Exception Handling through
ArrayIndexOutOfBoundsException

18. Write a program concept in Java to demonstrate


the of Exception Handling through
FileNotFoundException

2024-501-032 Suzan Rizvi


JAVA LAB

Q1. Write a program implementing Has-A relationship (composition).


Create necessary classes and driver class.
Code:
// Class representing a Car
class Car {
private String model;

public Car(String model) {


this.model = model;
}

public String getModel() {


return model;
}
}

// Class representing a Person


class Person {
private String name;
private Car car;

public Person(String name, Car car) {


this.name = name;
this.car = car;
}

public String getName() {


return name;
}

public Car getCar() {


return car;
}
}

2024-501-032 Suzan Rizvi


JAVA LAB

// Driver class to test the Has-A relationship


public class Main {
public static void main(String[] args) {
Car car = new Car("Toyota");
Person person = new Person("Alice", car);

System.out.println(person.getName() + " owns a " +


person.getCar().getModel());
}
}
Output:

Q2. Write a program and implement data hiding principle. Create


necessary classes and driver class.
Code:
// Class representing a Bank Account
class BankAccount {
private double balance;

public BankAccount(double initialBalance) {


this.balance = initialBalance;
}

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
} else {
System.out.println("Invalid deposit amount");
}
2024-501-032 Suzan Rizvi
JAVA LAB

public void withdraw(double amount) {


if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Invalid withdrawal amount");
}
}

public double getBalance() {


return balance;
}
}

// Driver class to test data hiding principle


public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000.0);

// Trying to access balance directly (which is private) will result


in a compilation error
// System.out.println(account.balance);

// Depositing and withdrawing money using public methods


account.deposit(500.0);
account.withdraw(200.0);

// Getting the balance using a public method


System.out.println("Current Balance: " + account.getBalance());
}
}
Output:

2024-501-032 Suzan Rizvi


JAVA LAB

Q3. Write a program for storing subjects marks of each individuals


implementing List (ArrayList, Linked List) also Create necessary classes
and driver class.
Code:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

class Student {
private String name;
private List<Integer> marks;

public Student(String name) {


this.name = name;
this.marks = new ArrayList<>();
}

public String getName() {


return name;
}

public void addMark(int mark) {


marks.add(mark);
}

public List<Integer> getMarks() {


return marks;
2024-501-032 Suzan Rizvi
JAVA LAB

}
}

public class Main {


public static void main(String[] args) {
List<Student> studentsArrayList = new ArrayList<>();
List<Student> studentsLinkedList = new LinkedList<>();

Student student1 = new Student("Alice");


student1.addMark(85);
student1.addMark(90);

Student student2 = new Student("Bob");


student2.addMark(75);
student2.addMark(80);

studentsArrayList.add(student1);
studentsArrayList.add(student2);

studentsLinkedList.add(student1);
studentsLinkedList.add(student2);

System.out.println("Using ArrayList:");
for (Student student : studentsArrayList) {
System.out.println("Student: " + student.getName());
System.out.println("Marks: " + student.getMarks());
}

System.out.println("\nUsing LinkedList:");
for (Student student : studentsLinkedList) {
System.out.println("Student: " + student.getName());
System.out.println("Marks: " + student.getMarks());
}
}
}
2024-501-032 Suzan Rizvi
JAVA LAB

Output:

Q4. Write a program to demonstrate inheritance (similar to ZooApp).


Code:
// Animal class (Parent class)
class Animal {
private String name;

public Animal(String name) {


this.name = name;
}

public void eat() {


System.out.println(name + " is eating.");
}

public void sleep() {


System.out.println(name + " is sleeping.");
}
}
2024-501-032 Suzan Rizvi
JAVA LAB

// Dog class (Child class inheriting from Animal)


class Dog extends Animal {
public Dog(String name) {
super(name);
}

public void bark() {


System.out.println("Woof! Woof!");
}
}

// Cat class (Child class inheriting from Animal)


class Cat extends Animal {
public Cat(String name) {
super(name);
}

public void meow() {


System.out.println("Meow! Meow!");
}
}

public class ZooApp {


public static void main(String[] args) {
Dog dog = new Dog("Buddy");
Cat cat = new Cat("Whiskers");

dog.eat();
dog.sleep();
dog.bark();

System.out.println();

cat.eat();
2024-501-032 Suzan Rizvi
JAVA LAB

cat.sleep();
cat.meow();
}
}
Output:

Q5. Write a program to show the difference between static binding and
dynamic binding.
Code:
// Parent class
class Parent {
void display() {
System.out.println("Inside Parent class");
}
}

// Child class
class Child extends Parent {
void display() {
System.out.println("Inside Child class");
}
}

public class BindingExample {


2024-501-032 Suzan Rizvi
JAVA LAB

public static void main(String[] args) {


Parent parent = new Parent();
Child child = new Child();

// Static binding - Method call is resolved at compile time


parent.display(); // Output: Inside Parent class
child.display(); // Output: Inside Child class

// Dynamic binding - Method call is resolved at runtime


Parent dynamicParent = new Child();
dynamicParent.display(); // Output: Inside Child class
}
}
Output:

Q6. Demonstrate different type of constructor in java.


Code:
// Class with different types of constructors
class ConstructorExample {
private String name;
private int age;

// Default constructor
public ConstructorExample() {
this.name = "Sahil khan";
this.age = 20;
}

2024-501-032 Suzan Rizvi


JAVA LAB

// Parameterized constructor
public ConstructorExample(String name, int age) {
this.name = name;
this.age = age;
}

// Copy constructor
public ConstructorExample(ConstructorExample other) {
this.name = other.name;
this.age = other.age;
}

// Method to display object details


public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

public class ConstructorDemo {


public static void main(String[] args) {
// Using default constructor
ConstructorExample defaultConstructor = new
ConstructorExample();
System.out.print("Default Constructor: ");
defaultConstructor.display();

// Using parameterized constructor


ConstructorExample parameterizedConstructor = new
ConstructorExample("Aadil raza khan", 15);
System.out.print("Parameterized Constructor: ");
parameterizedConstructor.display();

// Using copy constructor


ConstructorExample original = new ConstructorExample("aahil
raza khan", 10);
2024-501-032 Suzan Rizvi
JAVA LAB

ConstructorExample copyConstructor = new


ConstructorExample(original);
System.out.print("Copy Constructor: ");
copyConstructor.display();
}
}
Output:

Q7. Write a program and run through java and javac (cmd).
Screenshot:

Q8. Write a program using wrapper class and use method which takes an
object as a parameter.
Code:
// WrapperClassExample class
public class WrapperClassExample {
public static void displayObject(Object obj) {
System.out.println("Object: " + obj);
}

public static void main(String[] args) {


2024-501-032 Suzan Rizvi
JAVA LAB

Integer number = 10; // Wrapper class Integer

displayObject(number); // Passing Integer object to the method


}
}
Output:

Q9. Demonstrate constructor overloading in java.


Code:
// Class with constructor overloading
class ConstructorOverloadingExample {
private String name;
private int age;

// Default constructor
public ConstructorOverloadingExample() {
this.name = "Aadil raza khan";
this.age = 15;
}

// Parameterized constructor with name and age


public ConstructorOverloadingExample(String name, int age) {
this.name = name;
this.age = age;
}

// Constructor with only name


public ConstructorOverloadingExample(String name) {
this.name = name;
2024-501-032 Suzan Rizvi
JAVA LAB

this.age = 0; // Default age


}

// Method to display object details


public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

public class ConstructorOverloadingDemo {


public static void main(String[] args) {
// Using default constructor
ConstructorOverloadingExample defaultConstructor = new
ConstructorOverloadingExample();
System.out.print("Default Constructor: ");
defaultConstructor.display();

// Using parameterized constructor with name and age


ConstructorOverloadingExample parameterizedConstructor =
new ConstructorOverloadingExample("Sahil khan", 20);
System.out.print("Parameterized Constructor with name and
age: ");
parameterizedConstructor.display();

// Using constructor with only name


ConstructorOverloadingExample nameConstructor = new
ConstructorOverloadingExample("Aahil raza khan");
System.out.print("Constructor with only name: ");
nameConstructor.display();
}
}
Output:

2024-501-032 Suzan Rizvi


JAVA LAB

Q10. Write a program of method overloading and method overriding.


Code:
// Parent class with method overriding
class Parent {
public void display() {
System.out.println("Inside Parent class");
}

public void greet() {


System.out.println("Hello from Parent");
}
}

// Child class with method overriding


class Child extends Parent {
@Override
public void display() {
System.out.println("Inside Child class");
}

// Method overloading in Child class


public void greet(String name) {
System.out.println("Hello, " + name + " from Child");
}
}

public class MethodExample {


2024-501-032 Suzan Rizvi
JAVA LAB

public static void main(String[] args) {


Parent parent = new Parent();
Child child = new Child();

// Method overriding
parent.display(); // Output: Inside Parent class
child.display(); // Output: Inside Child class

// Method overloading
parent.greet(); // Output: Hello from Parent
child.greet(); // Output: Hello, null from Child
child.greet("Sahil khan"); // Output: Hello, Sahil khan from child
}
}
Output:

Q11. Write a program that contains interface and abstract class.


Code:
// Interface
interface Shape {
double calculateArea();
double calculatePerimeter();
}

// Abstract class
2024-501-032 Suzan Rizvi
JAVA LAB

abstract class Quadrilateral implements Shape {


protected double side1;
protected double side2;
protected double side3;
protected double side4;

public Quadrilateral(double side1, double side2, double side3,


double side4) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
this.side4 = side4;
}

@Override
public double calculatePerimeter() {
return side1 + side2 + side3 + side4;
}
}

// Rectangle class implementing the Quadrilateral abstract class


class Rectangle extends Quadrilateral {
public Rectangle(double length, double width) {
super(length, width, length, width);
}

@Override
public double calculateArea() {
return side1 * side2;
}
}

public class ShapeExample {


public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 10);
2024-501-032 Suzan Rizvi
JAVA LAB

System.out.println("Rectangle Area: " +


rectangle.calculateArea());
System.out.println("Rectangle Perimeter: " +
rectangle.calculatePerimeter());
}
}
Output:

Q12. Write a program in java to demonstrate the concept of multiple


inheritance through interface
Code:
// Interface for Animal behaviors
interface Animal {
void eat();
void sleep();
}

// Interface for Pet behaviors


interface Pet {
void play();
}

// Dog class implementing both Animal and Pet interfaces


class Dog implements Animal, Pet {
@Override
public void eat() {
System.out.println("Dog is eating.");
2024-501-032 Suzan Rizvi
JAVA LAB

@Override
public void sleep() {
System.out.println("Dog is sleeping.");
}

@Override
public void play() {
System.out.println("Dog is playing.");
}
}

public class MultipleInheritanceExample {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.sleep();
dog.play();
}
}
Output:

Q13. Create a class Point (2-Dimensional) and extend it to a 3-


Dimensional point with class name Point3D. Create two instances in a
separate TestPoint class (one for 2D point and other for 3D point).
Populate the values and print the same
2024-501-032 Suzan Rizvi
JAVA LAB

Code:
// 2D Point class
class Point {
private int x;
private int y;

public Point(int x, int y) {


this.x = x;
this.y = y;
}

public String toString() {


return "(" + x + ", " + y + ")";
}
}

// 3D Point class extending 2D Point


class Point3D extends Point {
private int z;

public Point3D(int x, int y, int z) {


super(x, y);
this.z = z;
}

@Override
public String toString() {
return "(" + super.toString() + ", " + z + ")";
}
}

// TestPoint class to create instances and print values


public class TestPoint {
public static void main(String[] args) {
// Creating a 2D Point
2024-501-032 Suzan Rizvi
JAVA LAB

Point point2D = new Point(3, 5);


System.out.println("2D Point: " + point2D);

// Creating a 3D Point
Point3D point3D = new Point3D(1, 2, 4);
System.out.println("3D Point: " + point3D);
}
}
Output:

Q14. Create a class point and also create a class Line which is composed
of 2 Points StartPoint and EndPoint. Then create a class Triangle which is
composed of three lines. Populate the values and print the same
Code:
// Point class
class Point {
private int x;
private int y;

public Point(int x, int y) {


this.x = x;
this.y = y;
}

public String toString() {


return "(" + x + ", " + y + ")";
}

2024-501-032 Suzan Rizvi


JAVA LAB

// Line class composed of two Points


class Line {
private Point startPoint;
private Point endPoint;

public Line(Point startPoint, Point endPoint) {


this.startPoint = startPoint;
this.endPoint = endPoint;
}

public String toString() {


return "Line: " + startPoint + " to " + endPoint;
}
}

// Triangle class composed of three Lines


class Triangle {
private Line line1;
private Line line2;
private Line line3;

public Triangle(Line line1, Line line2, Line line3) {


this.line1 = line1;
this.line2 = line2;
this.line3 = line3;
}

public String toString() {


return "Triangle with lines:\n" + line1 + "\n" + line2 + "\n" + line3;
}
}

// TestTriangle class to create instances and print values


2024-501-032 Suzan Rizvi
JAVA LAB

public class TestTriangle {


public static void main(String[] args) {
// Creating Points
Point pointA = new Point(1, 1);
Point pointB = new Point(4, 5);
Point pointC = new Point(2, 6);
Point pointD = new Point(6, 3);
Point pointE = new Point(3, 2);

// Creating Lines
Line lineAB = new Line(pointA, pointB);
Line lineBC = new Line(pointB, pointC);
Line lineCA = new Line(pointC, pointA);
Line lineDE = new Line(pointD, pointE);
Line lineEA = new Line(pointE, pointA);

// Creating Triangle
Triangle triangle = new Triangle(lineAB, lineBC, lineCA);

System.out.println("Points:");
System.out.println("A: " + pointA);
System.out.println("B: " + pointB);
System.out.println("C: " + pointC);
System.out.println("D: " + pointD);
System.out.println("E: " + pointE);

System.out.println("\nLines:");
System.out.println(lineAB);
System.out.println(lineBC);
System.out.println(lineCA);
System.out.println(lineDE);
System.out.println(lineEA);

System.out.println("\nTriangle:");
System.out.println(triangle);
2024-501-032 Suzan Rizvi
JAVA LAB

}
}
Output:

Q15. Write a program in Java to demonstrate the concept of Exception


Handling through NullPointerException
Code:
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
String str = null;
System.out.println("Length of the string: " + str.length());
2024-501-032 Suzan Rizvi
JAVA LAB

} catch (NullPointerException e) {
System.out.println("NullPointerException occurred: " +
e.getMessage());
}
}
}
Output:

Q16. Write a program in Java to demonstrate the concept of Exception


Handling through StringIndexOutOfBoundsException.
Code:
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
String str = "Hello";
char ch = str.charAt(10); // Accessing character at index 10
which is out of bounds
System.out.println("Character at index 10: " + ch);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException
occurred: " + e.getMessage());
}
}
}
Output:

2024-501-032 Suzan Rizvi


JAVA LAB

Q17. Write a program in Java to demonstrate the


Concept of Exception Handling through
ArrayIndexOutOfBoundsException
Code:
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println("Element at index 3: " + numbers[3]); //
Accessing element at index 3 which is out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException
occurred: " + e.getMessage());
}
}
}
Output:

Q18. Write a program concept in Java to demonstrate the of Exception


Handling through FileNotFoundException
Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ExceptionHandlingExample {


public static void main(String[] args) {
try {
File file = new File("nonexistentfile.txt");
2024-501-032 Suzan Rizvi
JAVA LAB

Scanner scanner = new Scanner(file);


while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException occurred: " +
e.getMessage());
}
}
}
Output:

2024-501-032 Suzan Rizvi

You might also like