0% found this document useful (0 votes)
7 views

Manish Java

The document contains Java programming exercises demonstrating various concepts such as input handling using Scanner and BufferedReader, loops, arrays, classes, and method overloading. Each section includes code snippets for tasks like multiplying numbers, calculating factorials, checking even/odd, and performing matrix operations. The author, Vansh Kakkar, provides solutions for each question with clear examples.

Uploaded by

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

Manish Java

The document contains Java programming exercises demonstrating various concepts such as input handling using Scanner and BufferedReader, loops, arrays, classes, and method overloading. Each section includes code snippets for tasks like multiplying numbers, calculating factorials, checking even/odd, and performing matrix operations. The author, Vansh Kakkar, provides solutions for each question with clear examples.

Uploaded by

NOBODY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

01413702024 BCA104P OOPJ Lab

Ques 1. Write a program to demonstrate the use of Scanner class, command line
arguments and BufferedReader for taking input from the user.
(a) Multiply a number by 2
(b) Add three numbers take input using BufferedReader
(c) Check If a Number Is Even or
Odd. Solution:
(a) Multiply a number by 2
import java.util.*;
class mul{
public static void main (String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
System.out.print("Enter a number: ");
int n1;
Scanner scanner=new Scanner(System.in);
n1=scanner.nextInt();
n1=n1*2;
System.out.println("Desired number: " + n1);
}
}

1
01413702024 BCA104P OOPJ Lab

(b) Add three numbers take input using BufferedReader


import java.io.*;
class AddNumbers
{
void addThreeNumbers() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
System.out.print("Enter first number: ");
int a = Integer.parseInt(reader.readLine());
System.out.print("Enter second number:
"); int b =
Integer.parseInt(reader.readLine());
System.out.print("Enter third number: ");
int c = Integer.parseInt(reader.readLine());
int sum = a + b + c;
System.out.println("Sum: " + sum);
}
}
public class InputDemo {
public static void main(String[] args) throws IOException
{ AddNumbers a = new AddNumbers();
a.addThreeNumbers();
}
}

2
01413702024 BCA104P OOPJ Lab

(c) Check If a Number Is Even or Odd.


import java.io.*;
class evenOrOdd{
public static void main(String[] args) throws
IOException{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
BufferedReader reader = new BufferedReader( new InputStreamReader(System.in));
System.out.print("Enter your number: ");
int a =
Integer.parseInt(reader.readLine()); if(a
%2==0){
System.out.println("This is an even number");
}
else{
System.out.println("This is an odd number");
}
reader.close();
}
}

3
01413702024 BCA104P OOPJ Lab

Ques 2. Write a program to demonstrate the use of loops, break and continue
statements.
(a) Calculate the factorial of a number.
(b) Create an infinite loop and use break to exit based on a condition, such as user
input or a specific value.
(c) Print Odd or Even Numbers: Loop through numbers and use continue to skip
numbers that don’t match the condition (e.g., skip even numbers when printing
odd numbers).
(d) Find Non-Divisible Numbers: Loop through numbers in a range and skip
numbers divisible by a given value using continue.
Solution:
(a) Calculate the factorial of a number.
import java.util.Scanner;
public class LoopDemo{
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
System.out.print("Enter number: ");
int num = scanner.nextInt();
long factorial = 1;
for (int i = 1; i <= num; i++)
{ factorial *= i;
}
System.out.println("Factorial of " + num + " is: " + factorial);
scanner.close();
}
}

4
01413702024 BCA104P OOPJ Lab

(b) Create an infinite loop and use break to exit based on a condition, such as user
input or a specific value.
import java.util.Scanner;
public class LoopDemo1{
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
System.out.println("Infinite loop - type 'exit' to stop:");
while (true) {
System.out.print("Enter something (type 'exit' to stop): ");
String input = scanner.next();
if (input.equalsIgnoreCase("exit")) {
break;
}
System.out.println("You entered: " + input);
}
scanner.close();
}
}

5
01413702024 BCA104P OOPJ Lab

(c) Print Odd or Even Numbers: Loop through numbers and use continue to skip
numbers that don’t match the condition (e.g., skip even numbers when printing
odd numbers).
import java.util.Scanner;
public class evenno{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No: 01413702024");
System.out.println("Printing Even Numbers from 1 to 10: ");
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) {
continue;
}
System.out.print(i + " ");
}
System.out.println();

scanner.close();
}
}

6
01413702024 BCA104P OOPJ Lab

(d) Find Non-Divisible Numbers: Loop through numbers in a range and skip
numbers divisible by a given value using continue.
import java.util.Scanner;
public class skipdivisor {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
System.out.print("Enter a number to skip multiples of: ");
int skipDivisor = scanner.nextInt();
System.out.println("Numbers from 1 to 20 not divisible by " + skipDivisor + ":");
for (int i = 1; i <= 20; i++) {
if (i % skipDivisor == 0) {
continue;
}
System.out.print(i + " ");
}
scanner.close();
}
}

7
01413702024 BCA104P OOPJ Lab

Ques 3. Write a program to demonstrate various operations on 1D and 2D arrays:


(a) add the elements of an array.
(b) Copy Elements from One Array to Another: Create a new array and copy
elements from the original array.
(c) Check if an Array is Palindromic
(d) Find the Largest and Smallest Elements in an array
(e) Perform Matrix Addition
(f) Multiply two matrices using nested
loops. Solution:
(a) add the elements of an array.
public class SumArray {
public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
int[] arr = {34, 45, 17, 9, 11};
int sum = 0;

for (int num : arr)


{ sum += num;
}

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


}
}

8
01413702024 BCA104P OOPJ Lab

(b) Copy Elements from One Array to Another: Create a new array and copy
elements from the original array.
import java.util.Arrays;

public class CopyArray{


public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
int[] original = {41, 27, 15, 65, 50};
int[] copy = new int[original.length];

for (int i = 0; i < original.length; i++)


{ copy[i] = original[i];
}

System.out.println("Copied array: " + Arrays.toString(copy));


}
}

9
01413702024 BCA104P OOPJ Lab

(c) Check if an Array is Palindromic


public class PalindromeArray {
public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
int[] arr = {1, 2, 3, 2, 1};
boolean isPalindrome = true;

for (int i = 0; i < arr.length / 2; i++) {


if (arr[i] != arr[arr.length - 1 - i]) {
isPalindrome = false;
break;
}
}

if (isPalindrome) {
System.out.println("The array is a palindrome.");
} else {
System.out.println("The array is not a palindrome.");
}
}
}

10
01413702024 BCA104P OOPJ Lab

(d) Find the Largest and Smallest Elements in an array


public class MinMaxArray {
public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
int[] arr = {45, 22, 41, 14, 67, 102, 4};

int min = arr[0];


int max = arr[0];

for (int num : arr) {


if (num < min) min = num;
if (num > max) max = num;
}

System.out.println("Smallest: " + min);


System.out.println("Largest: " + max);
}
}

11
01413702024 BCA104P OOPJ Lab

(e) Perform Matrix Addition


public class MatrixAddition {
public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
int[][] A = {{1, 2},{3, 4}};
int[][] B = {{5, 6},{7, 8}};
int[][] sum = new int[2][2];

for (int i = 0; i < A.length; i++) {


for (int j = 0; j < A[0].length; j++)
{ sum[i][j] = A[i][j] + B[i][j];
}
}

System.out.println("Resultant Matrix after Addition:");


for (int[] row : sum) {
for (int val : row)
{ System.out.print(val + " ");
}
System.out.println();
}
}
}

12
01413702024 BCA104P OOPJ Lab

(f) Multiply two matrices using nested loops.


public class MatrixMultiplication
{ public static void main(String[]
args) {
System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
int[][] A = {{1, 7},{3, 6}};
int[][] B = {{5, 2},{1, 8}};
int[][] product = new int[2][2];

for (int i = 0; i < A.length; i++) {


for (int j = 0; j < B[0].length; j++) {
for (int k = 0; k < A[0].length; k++)
{ product[i][j] += A[i][k] * B[k][j];
}
}
}

System.out.println("Resultant Matrix after Multiplication:");


for (int[] row : product) {
for (int val : row)
{ System.out.print(val + " ");
}
System.out.println();
}
}
}

13
01413702024 BCA104P OOPJ Lab

Ques 4. Write a program to demonstrate classes, objects, member functions and data
members:
(a) Declaring a class Rectangle with data member’s length and breadth and member
functions Input, Output and CalculateArea.
(b) Create a class employee which have name, age and address of employee, include
methods getdata() and showdata(), getdata() takes the input from the user,
showdata() display the data in following format:
Name:
Age:
Address:
Solution:
(a) Declaring a class Rectangle with data member’s length and breadth and member
functions Input, Output and CalculateArea.
import java.util.Scanner;

class Rectangle {
double length, breadth;
void input() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter length: ");
length = sc.nextDouble();
System.out.print("Enter breadth: ");
breadth = sc.nextDouble();
}
void output()
{ System.out.println("Length: " +
length);
System.out.println("Breadth: " + breadth);
}
void calculateArea() {
double area = length * breadth;
System.out.println("Area of Rectangle: " + area);
}
14
01413702024 BCA104P OOPJ Lab

public static void main(String[] args)


{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
Rectangle rect = new Rectangle();
rect.input();
rect.output();
rect.calculateArea();
}
}

15
01413702024 BCA104P OOPJ Lab

(b) Create a class employee which have name, age and address of employee, include
methods getdata() and showdata(), getdata() takes the input from the user,
showdata() display the data in following format:
Name:
Age:
Address:

import java.util.Scanner;
class Employee {
String name, address;
int age;
void getdata() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Name: ");
name = sc.nextLine();
System.out.print("Enter Age: ");
age = sc.nextInt();
sc.nextLine();
System.out.print("Enter Address:
"); address = sc.nextLine();
}
void showdata()
{ System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Address: " +
address);
}
public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
Employee emp = new Employee();
emp.getdata();
16
01413702024 BCA104P OOPJ Lab

emp.showdata();
}
}

17
01413702024 BCA104P OOPJ Lab

Ques 5. Write a program to demonstrate use of method overloading:


(a) calculate area of square, rectangle and triangle
(b) add two integers, three integers, and two double
numbers Solution:
(a) calculate area of square, rectangle and triangle
class AreaCalculator
{ void area(int side) {
System.out.println("Area of Square: " + (side * side));
}
void area(int length, int breadth) {
System.out.println("Area of Rectangle: " + (length * breadth));
}
void area(double base, double height)
{ double area = 0.5 * base * height;
System.out.println("Area of Triangle: " + area);
}
public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
AreaCalculator calc = new AreaCalculator();
calc.area(7);
calc.area(4, 9);
calc.area(5.1, 3.4);
}
}

18
01413702024 BCA104P OOPJ Lab

(b) add two integers, three integers, and two double numbers
class Adder {
int add(int a, int b)
{ return a + b;
}
int add(int a, int b, int c)
{ return a + b + c;
}
double add(double a, double b)
{ return a + b;
}
public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
Adder obj = new Adder();

System.out.println("Sum of 10 and 20: " + obj.add(10, 20));


System.out.println("Sum of 1, 2, and 3: " + obj.add(1, 2, 3));
System.out.println("Sum of 5.5 and 4.5: " + obj.add(5.5, 4.5));
}
}

19
01413702024 BCA104P OOPJ Lab

Ques 6. Write a program to demonstrate the use of static variable, static method and
static block.
(a) Maintain a shared counter across all instances of a class. Create a StudentCount
class where a static variable count keeps track of the total number of students.
Each time a new student object is created, the count increases.
(b) Create an ArithmeticUtilityClass to add, subtract, divide, and multiply two
numbers using static methods.
Create a static block to demonstrate that static block is executed automatically, and that
too before invoking the constructor of the class.
Solution:
(a) Maintain a shared counter across all instances of a class. Create a StudentCount
class where a static variable count keeps track of the total number of students.
Each time a new student object is created, the count increases.
class StudentCount
{ static int count =
0; StudentCount() {
count++;
System.out.println("Student created. Current student count: " + count);
}
public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
StudentCount s1 = new StudentCount();
StudentCount s2 = new StudentCount();
StudentCount s3 = new StudentCount();
StudentCount s4 = new StudentCount();
System.out.println("Total number of students: " + StudentCount.count);
}
}

20
01413702024 BCA104P OOPJ Lab

(b) Create an ArithmeticUtilityClass to add, subtract, divide, and multiply two


numbers using static methods.
public class ArithmeticUtilityClass
{ static {
System.out.println("Static block executed: Initializing Arithmetic Utility...");
}

public static int add(int a, int b)


{ return a + b;
}

public static int subtract(int a, int b)


{ return a - b;
}

public static int multiply(int a, int b)


{ return a * b;
}

public static double divide(double a, double b) {


if (b == 0) {
System.out.println("Division by zero is not allowed.");
return 0;
}
return a / b;
}

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

21
01413702024 BCA104P OOPJ Lab

public static void main(String[] args)


{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
System.out.println("Addition: " + ArithmeticUtilityClass.add(10, 5));
System.out.println("Subtraction: " + ArithmeticUtilityClass.subtract(10, 5));
System.out.println("Multiplication: " + ArithmeticUtilityClass.multiply(10, 5));
System.out.println("Division: " + ArithmeticUtilityClass.divide(10, 5));

ArithmeticUtilityClass obj = new ArithmeticUtilityClass();


}
}

22
01413702024 BCA104P OOPJ Lab

Ques 7. Write a program to demonstrate the usage of constructors.


(a) Define a Student class with both a default constructor and a parameterized
constructor to initialize student details like name, age and course.
(b) Create an Employee class that demonstrates how constructors initialize
employee details.
(c) Initializes car details using constructors and demonstrates constructor
overloading.
Solution:
(a) Define a Student class with both a default constructor and a parameterized
constructor to initialize student details like name, age and course.
class Student
{ String
name; int
age; String
course;

Student() {
name = "Not Provided";
age = 0;
course = "Undecided";
}

Student(String n, int a, String c)


{ this.name = n;
this.age = a;
this.course = c;
}

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

23
01413702024 BCA104P OOPJ Lab

course); System.out.println();

24
01413702024 BCA104P OOPJ Lab

public static void main(String[] args)


{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
Student s1 = new Student(); // Calls default constructor
Student s2 = new Student("Daksh", 21, "Computer Science");

System.out.println("Student 1 (Default):");
s1.display();

System.out.println("Student 2 (Parameterized):");
s2.display();
}
}

25
01413702024 BCA104P OOPJ Lab

(b) Create an Employee class that demonstrates how constructors initialize


employee details.
class Employee1
{ String name;
int id;
String department;
Employee1(String n, int i, String d)
{
this.name = n;
this.id = i;
this.department = d;
}
void display()
{ System.out.println("Name: " +
name); System.out.println("ID: " + id);
System.out.println("Department: " + department);
}
public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
Employee1 emp = new Employee1("John Doe", 101, "Finance");
System.out.println("Employee Details:");
emp.display();
}
}

26
01413702024 BCA104P OOPJ Lab

(c) Initializes car details using constructors and demonstrates constructor


overloading.
class Car
{ String
brand; String
model; int
year;

Car() {
brand = "Unknown";
model =
"Unknown"; year =
0;
}

Car(String b, String m) {
brand = b;
model = m;
year = 2024;
}

Car(String b, String m, int y)


{ brand = b;
model = m;
year = y;
}

void display()
{ System.out.println("Brand: " +
brand); System.out.println("Model: " +
model); System.out.println("Year: " +

27
01413702024 BCA104P OOPJ Lab

year); System.out.println();
}

28
01413702024 BCA104P OOPJ Lab

public static void main(String[] args)


{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
Car car1 = new Car();
Car car2 = new Car("BMW", "X5");
Car car3 = new Car("Mahindra", "XUV700", 2023);

System.out.println("Car 1 (Default):");
car1.display();

System.out.println("Car 2 (2-Arg Constructor):");


car2.display();

System.out.println("Car 3 (3-Arg Constructor):");


car3.display();
}
}

29
01413702024 BCA104P OOPJ Lab

Ques 8. Write a program to demonstrate concept of ``this``.


(a) how “this” is used to differentiate between instance variables and method
parameters when they have the same name.
(b) show how “this” can be used to call another constructor within the same class,
allowing constructor chaining.
Solution:
(a) how “this” is used to differentiate between instance variables and method
parameters when they have the same name.
class Student1
{ String
name; int age;
Student1(String name, int age)
{ this.name = name;
this.age = age;
}
void display()
{ System.out.println("Name: " +
name); System.out.println("Age: " +
age);
}
public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
Student1 s = new Student1("Rohan", 21);
s.display();
}
}

30
01413702024 BCA104P OOPJ Lab

(b) show how “this” can be used to call another constructor within the same class,
allowing constructor chaining.
class Book
{ String title;
String author;
double price;

Book(String title) {
this(title, "Unknown", 0.0);
}

Book(String title, String author)


{ this(title, author, 0.0); //
}

Book(String title, String author, double price)


{ this.title = title;
this.author = author;
this.price = price;
}

void display()
{ System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Price: $" + price);
System.out.println();
}

public static void main(String[] args)


{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");

31
01413702024 BCA104P OOPJ Lab

Book b1 = new Book("Java Basics");


Book b2 = new Book("Data Structures", "John Doe");
Book b3 = new Book("Advanced Java", "Jane Smith", 749);

b1.display();
b2.display();
b3.display();
}
}

32
01413702024 BCA104P OOPJ Lab

Ques 9. Write a program to demonstrate creation and importing of packages in java.


Also, demonstrate the use of public, private, default access modifiers.
Create two packages each containing two classes including public class. Define data
members and member functions using default, public, and private access modifiers.
Access these members within the same package and from a different package. Observe
and explain the accessibility of each modifier in different scenarios.
Solution:
1. Package1 – ClassA
package package1;
public class ClassA {
public int publicVar = 100;
int defaultVar = 200;
private int privateVar = 300;

public void display() {


System.out.println("Inside ClassA:");
System.out.println("Public Var: " + publicVar);
System.out.println("Default Var: " +
defaultVar); System.out.println("Private Var: "
+ privateVar);
}
}

2. Package1 – ClassB
package package1;
import package2.ClassC;
import package2.ClassD;

public class ClassB {


public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");

33
01413702024 BCA104P OOPJ Lab

System.out.println("=== Accessing ClassA from ClassB (Same Package) ===");

34
01413702024 BCA104P OOPJ Lab

ClassA objA = new ClassA();


objA.display();
System.out.println("Access from ClassB:");
System.out.println("Public Var: " + objA.publicVar);
System.out.println("Default Var: " + objA.defaultVar);
// System.out.println("Private Var: " + objA.privateVar); // Not accessible

System.out.println("\n=== Accessing ClassA from ClassC (Different Package) ===");


ClassC objC = new ClassC();
objC.accessClassA();

System.out.println("\n=== Accessing ClassD (Different Package Public Class) ===");


ClassD objD = new ClassD();
objD.display();
}
}

3. Package2 – ClassC
package package2;
import package1.ClassA;

public class ClassC {


public void accessClassA()
{ ClassA obj = new
ClassA();
System.out.println("Public Var from ClassA: " + obj.publicVar);
// System.out.println("Default Var: " + obj.defaultVar); // Not accessible
// System.out.println("Private Var: " + obj.privateVar); // Not accessible
}
}

35
01413702024 BCA104P OOPJ Lab

4. Package2 – ClassD
package package2;
public class ClassD {
public void display() {
System.out.println("Inside ClassD from packagetwo (public class).");
}
}
Compiling Files

Accessing private variable from ClassA in ClassB

Accessing default and private variables from ClassA (Package1) to ClassC (Package2)

36
01413702024 BCA104P OOPJ Lab

Ques 10. Write a Java program to demonstrate single-level, multi-level, and


hierarchical inheritance, while also showcasing the use of the protected access modifier
and other access modifiers.
Implementation Requirements:
( ) Single-Level Inheritance:
 Create an Employee class with attributes and methods.
 Create a Programmer class that extends the Employee class.
(b) Multi-Level Inheritance:
 Extend the Programmer class by creating a Hacker class, forming a multi-level
inheritance chain.
(c) Hierarchical Inheritance:
 Create two separate classes, Clerk and Programmer, both extending the
Employee class to demonstrate hierarchical inheritance.
Ensure that different access modifiers are used for certain attributes or methods in the
base class to observe their accessibility in subclasses within same or different packages.
Solution:
(a) Single-Level Inheritance:
class Employee
{ protected String
name; public double
salary;

public void setDetails(String name, double salary)


{ this.name = name;
this.salary = salary;
}

public void showDetails()


{ System.out.println("Name: " + name);
System.out.println("Salary: $" + salary);
}
}

37
01413702024 BCA104P OOPJ Lab

class Programmer extends Employee


{ String language;

public void setLanguage(String language)


{ this.language = language;
}

public void showProgrammerDetails()


{ System.out.println("Programming Language: " +
language);
}
}

public class SingleLevelInheritance


{ public static void main(String[] args)
{
System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
Programmer p = new Programmer();
p.setDetails("Alice", 85000);
p.setLanguage("Java");
p.showDetails();
p.showProgrammerDetails();
}
}

38
01413702024 BCA104P OOPJ Lab

(b) Multi-Level Inheritance:


class Employee
{ protected String
name; public double
salary;
public void setDetails(String name, double salary)
{ this.name = name;
this.salary = salary;
}
public void showDetails()
{ System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
}
}
class Programmer extends Employee
{ String language;
public void setLanguage(String language)
{ this.language = language;
}
}
class Hacker extends Programmer
{ String specialty;

public void setSpecialty(String specialty)


{ this.specialty = specialty;
}
public void showHackerDetails()
{ System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
System.out.println("Language: " + language);
System.out.println("Specialty: " + specialty);
39
01413702024 BCA104P OOPJ Lab

}
}

public class MultiLevelInheritance


{ public static void main(String[] args)
{
System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.:
01413702024"); Hacker h = new Hacker();
h.setDetails("Madhav", 75000);
h.setLanguage("Python");
h.setSpecialty("Testing");
h.showHackerDetails();
}
}

40
01413702024 BCA104P OOPJ Lab

(c) Hierarchical Inheritance:


class Employee
{ protected String
name; public double
salary;
public void setDetails(String name, double salary)
{ this.name = name;
this.salary = salary;
}
}
class Programmer extends Employee
{ String language;
public void setLanguage(String language)
{ this.language = language;
}
public void showProgrammerDetails()
{ System.out.println("Name: " + name);
System.out.println("Salary: $" + salary);
System.out.println("Programming Language: " + language);
}
}

class Clerk extends Employee {


int typingSpeed;
public void setTypingSpeed(int speed)
{ this.typingSpeed = speed;
}
public void showClerkDetails()
{ System.out.println("Name: " + name);
System.out.println("Salary: $" + salary);
System.out.println("Typing Speed: " + typingSpeed + " WPM");

41
01413702024 BCA104P OOPJ Lab

}
}

public class HierarchicalInheritance


{ public static void main(String[] args)
{
System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
Programmer p = new Programmer();
p.setDetails("Charlie", 78000);
p.setLanguage("C++");
p.showProgrammerDetails();

Clerk c = new Clerk();


c.setDetails("Diana", 40000);
c.setTypingSpeed(65);
c.showClerkDetails();
}
}

42
01413702024 BCA104P OOPJ Lab

Ques 11.
(a) Write a program to demonstrate method overriding. Create an employee class
and a programmer class extending employee class. Override method of employee
class in programmer class.
(b) Write a program to demonstrate the use of super keyword.
 To refer immediate parent class instance variable.
 To invoke parent class method inside overriding method of subclass.
 To invoke parent class constructor, enabling constructor
chaining. Solution:
(a) Write a program to demonstrate method overriding. Create an employee class
and a programmer class extending employee class. Override method of employee
class in programmer class.
class Employee {
String name = "Generic Employee";
double salary = 50000;
public void showDetails()
{ System.out.println("Employee Name: " +
name); System.out.println("Salary: $" + salary);
}
}
class Programmer extends Employee
{ String language = "Java";
public void showDetails()
{ System.out.println("Programmer Name: " + name);
System.out.println("Salary: $" + salary);
System.out.println("Programming Language: " + language);
}
}

public class MethodOverridingDemo


{ public static void main(String[] args)
{
System.out.println("Name: Vansh Kakkar");
43
01413702024 BCA104P OOPJ Lab

System.out.println("Enroll No.: 01413702024");


Programmer p = new Programmer();
p.name = "Varun";
p.salary = 85000;
p.language = "Python";

p.showDetails();
}
}

44
01413702024 BCA104P OOPJ Lab

(b) Write a program to demonstrate the use of super keyword.


 To refer immediate parent class instance variable.
 To invoke parent class method inside overriding method of subclass.
 To invoke parent class constructor, enabling constructor chaining.
class Employee {
String name = "Employee";
double salary;
Employee(String name, double salary)
{ this.name = name;
this.salary = salary;
System.out.println("Employee constructor called");
}
public void showDetails() {
System.out.println("Name from Employee: " + name);
System.out.println("Salary from Employee: " + salary);
}
}
class Programmer extends Employee {
String name = "Programmer";
Programmer(String name, double salary)
{
super(name, salary);
System.out.println("Programmer constructor called");
}
public void showDetails() {
System.out.println("Name from Programmer: " + name);
System.out.println("Name from Employee using super: " + super.name);
super.showDetails();
}
}

45
01413702024 BCA104P OOPJ Lab

public class SuperKeywordDemo


{ public static void main(String[]
args) {
System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
Programmer p = new Programmer("Manandeep", 90000);
p.showDetails();
}
}

46
01413702024 BCA104P OOPJ Lab

Ques 12. Write a program to demonstrate the use of final keyword.


(a) Final with variables
(b) Final with methods
(c) Final with classes
Solution:
(a) Final with variables
public class FinalVariableDemo {
public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
final int MAX_VALUE = 100;
System.out.println("MAX_VALUE: " + MAX_VALUE);

MAX_VALUE = 200; // Cannot assign a value to final variable


}
}

Assigning value to final variable:

47
01413702024 BCA104P OOPJ Lab

(b) Final with methods


class Vehicle {
public final void showType()
{ System.out.println("This is a generic
vehicle.");
}
}

class Car extends Vehicle


{ public void showType() {
System.out.println("This is a car."); //Cannot override final method
}
}

public class FinalMethodDemo {


public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
Car c = new Car();
c.showType();
}
}

Overriding final method:

48
01413702024 BCA104P OOPJ Lab

(c) Final with classes


final class Constants {
public static final double PI = 3.14159;

public void display()


{ System.out.println("PI value is: " +
PI);
}
}

class MathConstants extends Constants {} // Cannot inherit from final class

public class FinalClassDemo {


public static void main(String[] args)
{ System.out.println("Name: Gunjan Duggal");
System.out.println("Enroll No.: 02313702024");
Constants c = new Constants();
c.display();
}
}

Inheritance from final class:

49
01413702024 BCA104P OOPJ Lab

Ques 13. Write a program to demonstrate run-time polymorphism


Solution:
class Animal {
public void sound()
{ System.out.println("Animal makes a
sound");
}
}

class Dog extends Animal


{ public void sound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal


{ public void sound() {
System.out.println("Cat meows");
}
}

public class RuntimePolymorphismDemo


{ public static void main(String[] args) {
System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
Animal a; // reference of parent class

a = new Dog(); // object of Dog


a.sound(); // Dog's version of sound() is called

a = new Cat(); // object of Cat


50
01413702024 BCA104P OOPJ Lab

a.sound(); // Cat's version of sound() is called


}
}

51
01413702024 BCA104P OOPJ Lab

Ques 14. Write a program to demonstrate the concept of abstract class


Solution:
abstract class Shape
{ abstract void draw();

void display() {
System.out.println("This is a
shape.");
}
}

class Circle extends Shape


{ void draw() {
System.out.println("Drawing a Circle");
}
}

class Rectangle extends Shape


{ void draw() {
System.out.println("Drawing a Rectangle");
}
}

public class AbstractClassDemo {


public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
Shape s; // abstract class reference

s = new Circle(); // referencing Circle object


s.display();
52
01413702024 BCA104P OOPJ Lab

s.draw();

System.out.println();

s = new Rectangle(); // referencing Rectangle object


s.display();
s.draw();
}
}

53
01413702024 BCA104P OOPJ Lab

Ques 15. Write program to create and implement an interface. Also, demonstrate the
concept of multiple inheritance in Java.
Solution:
interface Printable {
void print();
}
interface Showable
{ void show();
}
class Document implements Printable, Showable
{ public void print() {
System.out.println("Printing document...");
}
public void show()
{ System.out.println("Showing
document...");
}
}
public class InterfaceDemo {
public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
Document doc = new Document();
doc.print(); // from Printable
doc.show(); // from Showable
}
}

54
01413702024 BCA104P OOPJ Lab

Ques 16. Write java programs to:


(a) Write data to a file using FileOutputStream
(b) Read data from a file using FileInputStream.
(c) Append data to a file using FileWriter.
(d) Read data from a file using FileReader.
(e) Write primitive datatypes like int, byte, char, double to a file
using DataOutputStream.
(f) Read primitive datatypes like int, byte, char, double from a file
using DataInputStream.
Solution:
(a) Write data to a file using FileOutputStream
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFileOutputStream


{ public static void main(String[] args)
{
System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
String data = "This is a string written using FileOutputStream.";

try (FileOutputStream fos = new FileOutputStream("output.txt")) {


fos.write(data.getBytes());
System.out.println("Data written to file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

55
01413702024 BCA104P OOPJ Lab

56
01413702024 BCA104P OOPJ Lab

(b) Read data from a file using FileInputStream.


import java.io.FileInputStream;
import java.io.IOException;

public class ReadFileInputStream


{ public static void main(String[]
args) {
System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
try (FileInputStream fis = new FileInputStream("output.txt"))
{ int data;
while ((data = fis.read()) != -1) {
System.out.print((char)data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

57
01413702024 BCA104P OOPJ Lab

(c) Append data to a file using FileWriter.


import java.io.FileWriter;
import java.io.IOException;

public class AppendFileWriter {


public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
String dataToAppend = "\nAppended text using FileWriter.";

try (FileWriter fw = new FileWriter("output.txt", true)) {


fw.write(dataToAppend);
System.out.println("Data appended successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

58
01413702024 BCA104P OOPJ Lab

(d) Read data from a file using FileReader.


import java.io.FileReader;
import java.io.IOException;

public class ReadFileReader {


public static void main(String[] args)
{ System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
try (FileReader fr = new FileReader("output.txt"))
{ int ch;
while ((ch = fr.read()) != -1)
{ System.out.print((char) ch);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

59
01413702024 BCA104P OOPJ Lab

(e) Write primitive datatypes like int, byte, char, double to a file
using DataOutputStream.
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class
WriteDataOutputStream{ public static
void main(String[] args){
System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
try (DataOutputStream dout = new DataOutputStream(new
FileOutputStream("sample.txt"))) {
dout.writeByte(72);
dout.writeInt(101);
dout.writeChar('A');
dout.writeDouble(23.33);
dout.writeBoolean(true);
}catch (IOException e) {
System.out.println("Error writing file:"+ e.getMessage());
}
}
}

60
01413702024 BCA104P OOPJ Lab

(f) Read primitive datatypes like int, byte, char, double from a file
using DataInputStream.
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.EOFException;
public class
ReadDataInputStream{ public static
void main(String[] args){
System.out.println("Name: Vansh Kakkar");
System.out.println("Enroll No.: 01413702024");
try(DataInputStream din = new DataInputStream(new FileInputStream("sample.txt")))
{ while (true) {
System.out.println(din.readByte());
System.out.println(din.readInt());
System.out.println(din.readChar());
System.out.println(din.readDouble());
System.out.println(din.readBoolean());
}
}catch(EOFException e){
System.out.println("EOFException caught End of file reached.");
}catch (IOException e){
System.out.println("IOException occurred:" + e.getMessage());
}
}
}

61

You might also like