KASHI INSTITUTE OF TECHNOLOGY
Manage by: Jain Education Society
23 km Milestone, Varanasi-Allahabad Road, Mirzamurad, Varanasi (U.P.) E-mail:
info@kashiit.ac.in, Website: www.kashiit.ac.in Reception No: - 8115838661
By- Anupam
OOP’s WITH JAVA Lab (BCS-403)
Write Java Programs to illustrate the concept of the following:
1. Create simple java programs using command line arguments
a) WAP that takes input from user through command line argument and then prints whether a number is prime
or not.
b) Write a program to enter number through command line and check whether it is palindrome or not.
2. Use Java compiler and eclipse platform to write and execute java program
a) Write a program to print addition of 2 matrices in java
b) Write a program in java which creates the variable size array (Jagged Array) and print all the values using loop
statement.
3. Understand OOP concepts and basics of Java programming
a) Write a Java program to create a class called "Person" with a name and age attribute. Create two instances
of the "Person" class, set their attributes using the constructor, and print their name and age.
b) Write a Java program to create a class called Person with private instance variables name, age. and country.
Provide public getter and setter methods to access and modify these variables.
4. Create Java programs using inheritance and polymorphism
a) “Java does not support multiple inheritance but we can achieve it by interface”. Write a program to justify
the above statement.
b) Write a program in java to implement the following types of inheritance: • Single Inheritance •
Multilevel Inheritance
5. Implement error-handling techniques using exception handling and multithreading.
a) Write a Java program to implement user defined exception handling for negative amount entered.
b) Write a program in java which creates two threads, “Even” thread and “Odd” thread and print the even no
using Even Thread after every two seconds and odd no using Odd Thread after every five second.
6. Create java program with the use of java packages
a) Create a package named “Mathematics” and add a class “Matrix” with methods to add and subtract matrices
(2x2). Write a Java program importing the Mathematics package and use the classes defined in it.
7. Construct java program using Java I/O package
a) Write a program in java to take input from user by using all the following methods:
• Command Line Arguments • DataInputStream Class • BufferedReader Class • Scanner Class • Console Class
INDEX
S.NO. PROGRAM DATE SIGNATURE
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
Program – 1.a
AIM - WAP that takes input from user through command line
argument and then prints whether a number is prime or not.
Command-line arguments in Java
When
hjdhdhfhjhjnyou run a Java program from the terminal, you can pass values after the
class name.
These values are captured in the main(String[] args) array.
Algorithm
Take input from command-line arguments.
Convert the argument to an integer.
Check if the number is less than 2 (not prime).
Check divisibility from 2 up to √n.
If divisible by any number in the range, it's not prime.
Otherwise, it's prime.
Java Implementation
public class PrimeCheck {
public static void main(String[] args) {
// Check if an argument is provided
if (args.length == 0) {
System.out.println("Please provide a number as a command line argument.");
return;
}
// Parse the command-line argument to an integer
intnum = Integer.parseInt(args[0]);
// Check for numbers less than 2
if (num< 2) {
System.out.println(num + " is not a prime number.");
return;
}
// Assume the number is prime
booleanisPrime = true;
// Check divisibility up to the square root of num
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
// Print result
if (isPrime)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
OUTPUT
Program – 1.b
AIM - Write a program to enter number through command line
and check whether it is palindrome or not.
Algorithm
hjdhdhfhjhjn
1. Accept Input: Read the number from the command-line argument.
2. Convert Number: Store the number and reverse it.
3. Palindrome Check: Compare the original number with the reversed
number.
4. Output Result: Display whether the number is a palindrome or not.
Java Implementation
// PalindromeChecker.java
public class PalindromeChecker {
private int number;
// Constructor
public PalindromeChecker(int number) {
this.number = number;
}
// Method to check if the number is a palindrome
public boolean isPalindrome() {
int original = number;
int reversed = 0;
while (number != 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
return original == reversed;
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java PalindromeChecker <number>");
return;
}
try {
int inputNumber = Integer.parseInt(args[0]);
PalindromeChecker checker = new PalindromeChecker(inputNumber);
if (checker.isPalindrome()) {
System.out.println(inputNumber + " is a palindrome.");
} else {
System.out.println(inputNumber + " is not a palindrome.");
}
} catch (NumberFormatException e) {
System.out.println("Please enter a valid integer.");
}
}
}
OUTPUT
Program – 2.a
AIM - Write a program to print addition of 2 matrices in java
Algorithm
hjdhdhfhjhjn
1. Input Matrices: Initialize or input two matrices of the same dimensions.
2. Add Matrices: Add corresponding elements of both matrices.
3. Display Result: Print the resulting matrix.
Java Implementation
import java.util.Scanner;
class Matrix {
private int rows, cols;
private int[][] data;
// Constructor
public Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
data = new int[rows][cols];
}
// Method to read matrix elements
public void readMatrix(Scanner sc) {
System.out.println("Enter elements (" + rows + "x" + cols + "):");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
data[i][j] = sc.nextInt();
}
}
}
// Method to add two matrices
public Matrix add(Matrix other) {
if (this.rows != other.rows || this.cols != other.cols) {
throw new IllegalArgumentException("Matrix dimensions must match for addition.");
}
Matrix result = new Matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.data[i][j] = this.data[i][j] + other.data[i][j];
}
}
return result;
}
// Method to display the matrix
public void display() {
System.out.println("Matrix:");
for (int[] row : data) {
for (int val : row) {
System.out.print(val + "\t");
}
System.out.println();
}
}
}
public class MatrixAddition {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input dimensions
System.out.print("Enter number of rows: ");
int rows = sc.nextInt();
System.out.print("Enter number of columns: ");
int cols = sc.nextInt();
// Create and read matrices
Matrix matrix1 = new Matrix(rows, cols);
Matrix matrix2 = new Matrix(rows, cols);
System.out.println("Matrix 1:");
matrix1.readMatrix(sc);
System.out.println("Matrix 2:");
matrix2.readMatrix(sc);
// Add matrices and display result
Matrix sum = matrix1.add(matrix2);
System.out.println("Sum of matrices:");
sum.display();
sc.close();
}
}
OUTPUT
Program – 2.b
AIM - Write a program in java which creates the variable size array
(Jagged Array) and print all the values using loop statement.
What Is a Jagged Array?
hjdhdhfhjhjn
A jagged array in Java is an array of arrays where each sub-array can have a different
length. For example:
int[][] jagged = new int[3][];
jagged[0] = new int[2]; // Row 0 has 2 columns
jagged[1] = new int[4]; // Row 1 has 4 columns
jagged[2] = new int[1]; // Row 2 has 1 column
ALGORITHM
1. Declare Jagged Array: Create a 2D array where each row has a different column size.
2. Initialize Values: Fill the jagged array with values (either statically or from user
input).
3. Loop Through Rows: Use nested for loops to iterate and print the values.
4. Encapsulate Logic: Use a class to encapsulate array creation, storage, and printing.
Java Implementation
public class JaggedArrayExample {
public static void main(String[] args) {
// Declare and initialize the jagged array
int[][] jaggedArray = new int[3][]; // 3 rows
// Assign variable size to each row
jaggedArray[0] = new int[2]; // First row has 2 columns
jaggedArray[1] = new int[4]; // Second row has 4 columns
jaggedArray[2] = new int[3]; // Third row has 3 columns
// Initialize the jagged array with values
int value = 1;
for (int i = 0; i < jaggedArray.length; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
jaggedArray[i][j] = value++;
}
}
// Print the jagged array using nested loops
System.out.println("Jagged Array Contents:");
for (int i = 0; i < jaggedArray.length; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
}
System.out.println(); // New line after each row
}
}
}
OUTPUT
Program – 3.a
AIM - Write a Java program to create a class called "Person" with a
name and age attribute. Create two instances of the "Person" class, set
their attributes using the constructor, and print their name and age.
ALGORITHM
hjdhdhfhjhjn
1. Define Class: Create a Person class with two attributes: name and age.
2. Create Constructor: Add a constructor that takes name and age as parameters.
3. Create Objects: In the main() method, create two Person objects using the
constructor.
4. Display Information: Use a method or direct access to print name and age of both
persons.
Java Implementation
// Person class definition
public class Person {
// Attributes
String name;
int age;
// Constructor to initialize name and age
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display person details
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
// Main method to test the class
public static void main(String[] args) {
// Creating first person object
Person person1 = new Person("Alice", 25);
// Creating second person object
Person person2 = new Person("Bob", 30);
// Displaying their details
System.out.println("Person 1:");
person1.displayInfo();
System.out.println("\nPerson 2:");
person2.displayInfo();
}
}
OUTPUT
Program – 3.b
AIM - Write a Java program to create a class called Person with private
instance variables name, age. and country. Provide public getter and
setter methods to access and modify these variables.
ALGORITHM
hjdhdhfhjhjn
1. Define Class: Create a class Person with private variables: name, age, and country.
2. Create Getters/Setters: Provide public methods to get and set each variable.
3. Instantiate Object: Create an object of Person in the main() method.
4. Set Data: Use setter methods to assign values to the object.
5. Get Data: Use getter methods to retrieve and print the values.
Java Implementation
// Class definition
public class Person {
// Private instance variables
private String name;
private int age;
private String country;
// Getter for name
public String getName() {
return name;
}
// Setter for name
public void setName(String name) {
this.name = name;
}
// Getter for age
public int getAge() {
return age;
}
// Setter for age
public void setAge(int age) {
this.age = age;
}
// Getter for country
public String getCountry() {
return country;
}
// Setter for country
public void setCountry(String country) {
this.country = country;
}
// Method to display person information
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Country: " + country);
}
// Main method to test the class
public static void main(String[] args) {
// Create a Person object
Person person = new Person();
// Set values using setters
person.setName("Shanaya Keshari");
person.setAge(19);
person.setCountry("India");
// Display the values using getters or directly through a method
person.displayInfo();
}
}
OUTPUT
Program – 4.a
AIM - “Java does not support multiple inheritance but we can achieve
it by interface”. Write a program to justify the above statement.
INTRODUCTION
hjdhdhfhjhjn
Java restricts multiple
inheritance with classes to avoid ambiguity (e.g., the "diamond
problem"). However, Java allows a class to implement multiple interfaces, enabling
multiple inheritance of type (i.e., behavior or contracts without implementation).
So, while you cannot extend more than one class, you can implement multiple
interfaces, thus achieving multiple inheritance in a safe and structured way.
ALGORITHM
1. Create Interfaces: Define two interfaces with methods.
2. Implement Interfaces: Create a class that implements both interfaces.
3. Override Methods: Implement the interface methods in the class.
4. Create Object: Instantiate the class and call methods to show multiple behaviors
inherited.
5. Print Output: Display that the class has inherited behavior from both interfaces.
Java Implementation
// Interface 1
interface A {
void show();
}
// Interface 2
interface B {
void display();
}
// Class C implements both interfaces
class C implements A, B {
// Implementing method from Interface A
public void show() {
System.out.println("This is show() from Interface A");
}
// Implementing method from Interface B
public void display() {
System.out.println("This is display() from Interface B");
}
}
// Main class to run the program
public class MultipleInheritanceDemo {
public static void main(String[] args) {
C obj = new C();
obj.show(); // Calls method from Interface A
obj.display(); // Calls method from Interface B
}
}
OUTPUT
Program – 4.b
AIM - Write a program in java to implement the following types
of inheritance: • Single Inheritance • Multilevel Inheritance
INTRODUCTION
Inheritance in Java
hjdhdhfhjhjn
Inheritance is an OOP feature that allows one class to acquire the properties and
methods of another class. It promotes code reusability.
🔸 Types of Inheritance in Java:
1. Single Inheritance: One class inherits from one parent class.
2. Multilevel Inheritance: A class inherits from a derived class, forming a chain.
1. Single Inheritance
ALGORITHM
1. Create a base class Animal with a method eat().
2. Create a derived class Dog that extends Animal and adds bark().
3. In main(), create a Dog object and call both methods.
Java Implementation
// Parent class
class Animal {
void eat() {
System.out.println("Animal eats food");
}
}
// Child class inheriting from Animal
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
// Main class
public class SingleInheritanceDemo {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // Inherited method
d.bark(); // Own method
}
}
OUTPUT
2. Multilevel Inheritance
ALGORITHM
1. Use the previous Animal class.
2. Create a class Dog extending Animal.
3. Create another class Puppy extending Dog.
4. In main(), create a Puppy object and call all inherited methods.
Java Implementation
// Base class
class Vehicle {
void start() {
System.out.println("Vehicle starts");
}
}
// Derived class from Vehicle
class Car extends Vehicle {
void drive() {
System.out.println("Car is driving");
}
}
// Derived class from Car (third level)
class ElectricCar extends Car {
void charge() {
System.out.println("Electric car is charging");
}
}
// Main class
public class MultilevelInheritanceDemo {
public static void main(String[] args) {
ElectricCar ec = new ElectricCar();
ec.start(); // Method from Vehicle
ec.drive(); // Method from Car
ec.charge(); // Method from ElectricCar
}
}
OUTPUT
Program – 5.a
AIM - Write a Java program to implement user defined
exception handling for negative amount entered.
ALGORITHM
hjdhdhfhjhjn
1. Create Custom Exception Class: Extend Exception to define
NegativeAmountException.
2. Create Method: A method to accept an amount and throw exception if it's negative.
3. Handle Exception: Use try-catch block in main() to handle the custom exception.
4. Input from User: Use Scanner to get amount from user.
5. Print Result: Show message based on whether the amount was valid or not.
Java Implementation
// User-defined exception class
class NegativeAmountException extends Exception {
public NegativeAmountException(String message) {
super(message);
}
}
// Main class
public class BankTransaction {
// Method to deposit amount
static void deposit(double amount) throws NegativeAmountException {
if (amount < 0) {
// Throwing user-defined exception
throw new NegativeAmountException("Amount cannot be negative!");
} else {
System.out.println("Amount " + amount + " deposited successfully.");
}
}
public static void main(String[] args) {
try {
double amountToDeposit = -500; // Simulate user input
deposit(amountToDeposit);
} catch (NegativeAmountException e) {
System.out.println("Exception Caught: " + e.getMessage());
}
}
}
OUTPUT
Program – 5.b
AIM - Write a program in java which creates two threads, “Even” thread
and “Odd” thread and print the even no using Even Thread after every
two seconds and odd no using Odd Thread after every five second.
ALGORITHM
1. Create two classes (EvenThread and OddThread) that implement Runnable.
hjdhdhfhjhjn
2. In run(), use a loop to print even/odd numbers.
3. Add Thread.sleep(2000) in EvenThread, and Thread.sleep(5000) in OddThread.
4. In main(), create and start both threads.
Java Implementation
// Even thread class
class EvenThread extends Thread {
public void run() {
for (int i = 0; i <= 20; i += 2) {
System.out.println("Even Thread: " + i);
try {
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
System.out.println("EvenThread Interrupted");
}
}
}
}
// Odd thread class
class OddThread extends Thread {
public void run() {
for (int i = 1; i < 20; i += 2) {
System.out.println("Odd Thread: " + i);
try {
Thread.sleep(5000); // Sleep for 5 seconds
} catch (InterruptedException e) {
System.out.println("OddThread Interrupted");
}
}
}
}
// Main class
public class EvenOddThreadDemo {
public static void main(String[] args) {
EvenThread even = new EvenThread();
OddThread odd = new OddThread();
// Start both threads
even.start();
odd.start();
}
}
OUTPUT
Program – 6.a
AIM - Create a package named “Mathematics” and add a class “Matrix”
with methods to add and subtract matrices (2x2). Write a Java program
importing the Mathematics package and use the classes defined in it.
ALGORITHM
1.hjdhdhfhjhjn
Define the Matrix class in the Mathematics package.
o Store 2x2 matrix data in a 2D array.
o Create a constructor to initialize the matrix.
o Implement add (Matrix other) and subtract (Matrix other) methods that return a
new Matrix.
o Implement a display() method to print the matrix.
2. Create a main class (e.g., MatrixOperations) in a separate file.
o Import the Mathematics.Matrix class.
o Create instances of 2x2 matrices.
o Call add() and subtract() methods and display the results.
Java Implementation
// Simulating package and class in one file
class Matrix {
private int[][] mat;
public Matrix(int[][] values) {
if (values.length != 2 || values[0].length != 2 || values[1].length != 2) {
throw new IllegalArgumentException("Matrix must be 2x2.");
}
mat = values;
}
public Matrix add(Matrix other) {
int[][] result = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
result[i][j] = this.mat[i][j] + other.mat[i][j];
}
}
return new Matrix(result);
} public Matrix subtract(Matrix other) {
int[][] result = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
result[i][j] = this.mat[i][j] - other.mat[i][j];
}
}
return new Matrix(result);
}
public void display() {
for (int[] row : mat) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
}
}
public class Main {
public static void main(String[] args) {
int[][] values1 = {
{1, 2},
{3, 4}
};
int[][] values2 = {
{5, 6},
{7, 8}
};
Matrix m1 = new Matrix(values1);
Matrix m2 = new Matrix(values2);
System.out.println("Matrix 1:");
m1.display();
System.out.println("Matrix 2:");
m2.display();
Matrix sum = m1.add(m2);
System.out.println("Sum of matrices:");
sum.display();
Matrix diff = m1.subtract(m2);
System.out.println("Difference of matrices:");
diff.display();
}
}
OUTPUT
Program – 7.a
AIM - Write a program in java to take input from user by using all the
following methods:
• Command Line Arguments • DataInputStream Class • BufferedReader
Class • Scanner Class • Console Class
ALGORITHM
1. Accept and display command-line arguments.
2. Use DataInputStream to take a string input.
3.hjdhdhfhjhjn
Use BufferedReader to take an integer input.
4. Use Scanner to read a float input.
5. Use Console to read a password and print it as a masked value.
6. Print all values to confirm successful input using different methods.
Java Implementation
import java.io.*;
import java.util.Scanner;
public class InputDemo {
public static void main(String[] args) throws IOException {
System.out.println("----- Input Using Command Line Arguments -----");
if (args.length > 0) {
System.out.println("Command line argument: " + args[0]);
} else {
System.out.println("No command line argument provided.");
}
System.out.println("\n----- Input Using DataInputStream -----");
DataInputStream dis = new DataInputStream(System.in);
System.out.print("Enter a string using DataInputStream: ");
String dataInput = dis.readLine(); // Deprecated, but still works
System.out.println("You entered: " + dataInput);
System.out.println("\n----- Input Using BufferedReader -----");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a string using BufferedReader: ");
String bufferedInput = br.readLine();
System.out.println("You entered: " + bufferedInput);
System.out.println("\n----- Input Using Scanner -----");
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string using Scanner: ");
String scannerInput = sc.nextLine();
System.out.println("You entered: " + scannerInput);
System.out.println("\n----- Input Using Console (May not work in some IDEs) -----
");
Console console = System.console();
if (console != null) {
String consoleInput = console.readLine("Enter a string using Console: ");
System.out.println("You entered: " + consoleInput);
} else {
System.out.println("Console not available (run in terminal, not IDE).");
}
sc.close();
}
}
OUTPUT