Program 1
Question :
Write a program in Java to create a class date having three instance variables assign them with values in
an instance method using Command Line Argument and in another function print the date. Create another
class A where define the main function, at the end call the functions from the main function.
Code:
class Date{
int day;
int month;
int year;
void assign(int a, int b, int c){
day=a;
month=b;
year=c;
}
void show(){
System.out.println(day+" / "+month+" / "+year);
}
}
class A{
public static void main(String args[]){
Date obj=new Date();
obj.assign(Integer.parseInt(args[0]),Integer.parseInt(args[1]),Integer.parseInt(args[2]));
obj.show();
}
}
Output:
Program 2
Question :
Write a program in Java to create a class Complex and declare two instance variables, initialize them in an
instance method and display the complex number in another function. Create another class A where we
declare the main function and call the functions from there.
Code:
class Complex{
int real,img;
void assign(int a,int b){
real=a;
img=b;
}
void show(){
System.out.println(real+" +"+img+"i");
}
}
class A{
public static void main(String args[]){
Complex obj=new Complex();
obj.assign(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
obj.show();
}
}
Output:
Program 3
Question :
Write a program in Java to create a class Factorial and declare one instance variable, initialize it in an
instance method and display the factorial of the number in another function. Create another class A
where you declare the main function and call the functions from there.
Code:
class Factorial{
int n;
void assign(int a){
n=a;
}
void show(){
int i,p=1;
for(i=1;i<=n;i++)
p*=i;
System.out.println("The Factorial of "+n+" is "+p);;
}
}
class A{
public static void main(String args[]){
Factorial obj=new Factorial();
obj.assign(Integer.parseInt(args[0]));
obj.show();
}
}
Output:
Program 4
Question :
Write a program in Java to create a BOOK class that consists of the Book title, Author name and
price of the book. Print the details of the costly books.
Code:
import java.util.*;
class Book {
String title;
String author;
double price;
Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
}
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of books:");
int n = scanner.nextInt();
scanner.nextLine(); // Consume the newline left-over
Book[] ar = new Book[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter the book details (title, author, price):");
String title = scanner.nextLine();
String author = scanner.nextLine();
double price = scanner.nextDouble();
scanner.nextLine(); // Consume the newline left-over
ar[i] = new Book(title, author, price);
}
double mx = Double.MIN_VALUE;
// Find the maximum price
for (int i = 0; i < n; i++) {
if (ar[i].price > mx) {
mx = ar[i].price;
}
}
System.out.println("Costly books:");
for (int i = 0; i < n; i++) {
if (ar[i].price == mx) {
System.out.println("Title: " + ar[i].title);
System.out.println("Author: " + ar[i].author);
System.out.println("Price: " + ar[i].price);
}
}
scanner.close();
}
}
Output:
Program 5
Question :
Write a program in Java to create an EMPLOYEE class that contains the details of an employee, like
Name, Id, Salary. Copy the details of an employee to others during the instantiation of it. Also print the
count of the instances of the class being created.
Code:
import java.util.*;
class Employee {
String name;
int id;
int salary;
static int count = 0; // To keep track of the number of instances
// Constructor to initialize the employee details
Employee(String name, int id, int salary) {
this.name = name;
this.id = id;
this.salary = salary;
count++;
}
// Copy constructor to copy the details from another employee
Employee(Employee emp) {
this.name = emp.name;
this.id = emp.id;
this.salary = emp.salary;
count++;
}
// Method to display employee details
void display() {
System.out.println("Name: " + name);
System.out.println("ID: " + id);
System.out.println("Salary: " + salary);
}
// Static method to get the count of instances created
static int getCount() {
return count;
}
}
class EmployeeDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Employee[] empArray = new Employee[2];
System.out.println("Enter a name: ");
String name = sc.nextLine();
System.out.println("Enter an ID: ");
int id = sc.nextInt();
System.out.println("Enter a salary: ");
int salary = sc.nextInt();
empArray[0] = new Employee(name, id, salary);
System.out.println("\nDetails of the first employee:");
empArray[0].display();
// Create a new employee by copying the first one
Employee copyEmp = new Employee(empArray[0]);
// Display the details of the copied employee
System.out.println("\nDetails of the copied employee:");
copyEmp.display();
// Print the total count of Employee instances created
System.out.println("\nTotal instances of Employee class created: " + Employee.getCount());
sc.close();
}
}
Output:
Program 6
Question :
Write a program in java to implement stack.
Code:
import java.util.*;
class Stack {
int size;
int top = -1;
int[] arr;
Stack(int size) {
this.size = size;
arr = new int[size];
}
void push(int n) {
if (top == size - 1) {
System.out.println("Stack Overflow");
} else {
arr[++top] = n;
}
}
void pop() {
if (top == -1) {
System.out.println("Stack Underflow");
} else {
System.out.println("The deleted item is: " + arr[top]);
top--;
}
}
void display() {
if (top == -1) {
System.out.println("Stack is empty");
} else {
for (int i = 0; i <= top; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
}
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the stack");
int n = sc.nextInt();
Stack obj = new Stack(n);
while (true) {
System.out.println("Main Menu:");
System.out.println("1. Push 2. Pop 3. Display 4. Exit");
System.out.println("Enter your choice");
int ch = sc.nextInt();
switch (ch) {
case 1:
System.out.println("Enter a number");
int m = sc.nextInt();
obj.push(m);
break;
case 2:
obj.pop();
break;
case 3:
obj.display();
break;
case 4:
System.out.println("Exiting...");
sc.close();
System.exit(0);
default:
System.out.println("Wrong Choice");
}
}
}
}
Output:
Program 7
Question :
Write a program in Java to implement method overloading for adding two integers, two strings and two
complex numbers.
Code:
import java.util.Scanner;
public class Overload1 {
public int add(int a, int b) {
return a + b;
}
public String add(String a, String b) {
return a + b;
}
public ComplexNumber add(ComplexNumber a, ComplexNumber b) {
int realPart = a.getReal() + b.getReal();
int imaginaryPart = a.getImaginary() + b.getImaginary();
return new ComplexNumber(realPart, imaginaryPart);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Overload1 demo = new Overload1();
System.out.println("Enter the first integer:");
int int1 = scanner.nextInt();
System.out.println("Enter the second integer:");
int int2 = scanner.nextInt();
int intResult = demo.add(int1, int2);
System.out.println("Sum of integers: " + intResult);
scanner.nextLine(); // Consume the leftover newline
System.out.println("Enter the first string:");
String str1 = scanner.nextLine();
System.out.println("Enter the second string:");
String str2 = scanner.nextLine();
String strResult = demo.add(str1, str2);
System.out.println("Concatenation of strings: " + strResult);
System.out.println("Enter the real part of the first complex number:");
int real1 = scanner.nextInt();
System.out.println("Enter the imaginary part of the first complex number:");
int imag1 = scanner.nextInt();
ComplexNumber c1 = new ComplexNumber(real1, imag1);
System.out.println("Enter the real part of the second complex number:");
int real2 = scanner.nextInt();
System.out.println("Enter the imaginary part of the second complex number:");
int imag2 = scanner.nextInt();
ComplexNumber c2 = new ComplexNumber(real2, imag2);
ComplexNumber cResult = demo.add(c1, c2);
System.out.println("Sum of complex numbers: " + cResult);
scanner.close();
}
}
class ComplexNumber {
private int real;
private int imaginary;
public ComplexNumber(int real, int imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public int getReal() {
return real;
}
public int getImaginary() {
return imaginary;
}
public String toString() {
return real + " + " + imaginary + "i";
}
}
Output:
Program 8
Question :
Write a program in Java to overload the method area() to find the area of circle and rectangle.
Code:
import java.util.*;
public class AreaCalculator {
final double pi=3.14;
public double area(double radius) {
return pi * radius * radius;
}
public double area(double length, double width) {
return length * width;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
AreaCalculator calculator = new AreaCalculator();
System.out.println("Enter the radius of the circle:");
double radius = scanner.nextDouble();
double circleArea = calculator.area(radius);
System.out.println("Area of the circle: " + circleArea);
System.out.println("Enter the length of the rectangle:");
double length = scanner.nextDouble();
System.out.println("Enter the width of the rectangle:");
double width = scanner.nextDouble();
double rectangleArea = calculator.area(length, width);
System.out.println("Area of the rectangle: " + rectangleArea);
scanner.close();
}
}
Output:
Program 9
Question :
Write a program in Java to create a parent class with different access specifiers.
Code:
class A {
private int privateVar = 10;
protected int protectedVar = 20;
public int publicVar = 30;
int defaultVar = 40; // Default access specifier
// Method to display the private variable
void display() {
System.out.println("Private Variable: " + privateVar);
}
}
// Subclass inheriting from parent class A
class B extends A {
void show() {
// System.out.println(privateVar); // Private variable is not accessible
System.out.println("Protected Variable: " + protectedVar);
System.out.println("Public Variable: " + publicVar);
System.out.println("Default Variable: " + defaultVar); // Accessible if in the same package
}
}
public class Main {
public static void main(String[] args) {
A objA = new A();
System.out.println("Accessing variables from Parent class:");
objA.display(); // Displays only the private variable using its own method
B objB = new B();
System.out.println("\nAccessing variables from Subclass:");
objB.show(); // Displays accessible variables in the subclass
}
}
Output:
Program 10
Question :
Write a program in Java to create an interface for binary and octal conversion.
Code:
import java.util.Scanner;
interface BinaryConverter {
void toBinary(int num);
}
interface OctalConverter {
void toOctal(int num);
}
class NumberInput {
int num;
public void acceptNumber() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
num = scanner.nextInt();
}
}
class NumberConversion extends NumberInput implements BinaryConverter, OctalConverter {
public void toBinary(int num) {
System.out.println("Binary: " + Integer.toBinaryString(num));
}
public void toOctal(int num) {
System.out.println("Octal: " + Integer.toOctalString(num));
}
public void convert() {
acceptNumber();
toBinary(num);
toOctal(num);
}
}
public class HybridInheritanceExample {
public static void main(String[] args) {
NumberConversion obj = new NumberConversion();
obj.convert();
}
}
Output:
Program 11
Question :
Write a program in Java that defines a hierarchy of classes to represent boxes, weighted boxes, and
shipments. The Shipment class calculates the shipping cost based on the weight of the box and displays
the dimensions, weight, and cost.
Code:
class Box {
double length, width, height;
Box(double l, double w, double h) {
length = l;
width = w;
height = h;
}
double volume() {
return length * width * height;
}
}
class BoxWeight extends Box {
double weight;
BoxWeight(double l, double w, double h, double m) {
super(l, w, h);
weight = m;
}
}
class Shipment extends BoxWeight {
double cost;
Shipment(double l, double w, double h, double m) {
super(l, w, h, m);
if (weight > 50) {
cost = 45;
} else if (weight > 20) {
cost = 20;
} else {
cost = 0;
}
}
void display() {
System.out.println("Dimensions: " + length + " x " + width + " x " + height);
System.out.println("Weight: " + weight + " kg");
System.out.println("Shipping cost: $" + cost);
}
}
public class Main {
public static void main(String[] args) {
Shipment shipment1 = new Shipment(10, 20, 15, 55);
shipment1.display();
System.out.println();
Shipment shipment2 = new Shipment(10, 20, 15, 25);
shipment2.display();
System.out.println();
Shipment shipment3 = new Shipment(10, 20, 15, 15);
shipment3.display();
}
}
Output:
Program 12
Question :
Write a program in Java to create an abstract class Figure having one static variable pi and a static
function void area(). Create a class Square and Circle which extends to abstract class Figure to find the
area of the square and circle create a main function to find the area of the circle and square.
Code:
import java.util.*;
abstract class Figure {
final static double pi = 3.14;
abstract void area();
}
class Square extends Figure {
int a;
Square(int a) {
this.a = a;
}
void area() {
System.out.println("The area of square is: " + (a * a));
}
}
class Circle extends Figure {
int r;
Circle(int r) {
this.r = r;
}
void area() {
System.out.println("The area of circle is: " + (pi * r * r));
}
}
class Abs {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
Figure square = new Square(a);
square.area();
int r = sc.nextInt();
Figure circle = new Circle(r);
circle.area();
sc.close();
}
}
Output:
Program 13
Question :
Write a program in Java to create an interface Excurs where declare two functions computeResult() and
showGrade(). Create a class Student which will contain the name of the Student, their roll number and
marks of two subjects. Create a class Result which will extend to Student class and define the functions
mentioned in the interface and will compute the grade of the student.
Code:
interface Excurs {
double SCORE = 3.0;
void computeResult();
void showGrade();
}
class Student {
String name;
int rollNo;
double sub1;
double sub2;
Student(String name, int rollNo, double sub1, double sub2) {
this.name = name;
this.rollNo = rollNo;
this.sub1 = sub1;
this.sub2 = sub2;
}
}
class Result extends Student implements Excurs {
double total;
Result(String name, int rollNo, double sub1, double sub2) {
super(name, rollNo, sub1, sub2);
}
public void computeResult() {
total = (sub1 + sub2 + SCORE) / 2;
System.out.println("Total Marks: " + total);
}
public void showGrade() {
if (total >= 90) {
System.out.println("Grade: A");
} else if (total >= 75) {
System.out.println("Grade: B");
} else if (total >= 50) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: Fail");
}
}
}
public class Main {
public static void main(String[] args) {
Result student1 = new Result("Monjima Dey", 147, 99, 85);
student1.computeResult();
student1.showGrade();
}
}
Output:
Program 14
Question :
Write a program in Java to implement Hybrid Inheritance
Code:
// Interface 1
interface Animal {
void eat();
}
// Interface 2
interface Flyable {
void fly();
}
// Parent class
class Mammal {
void walk() {
System.out.println("Mammal walks");
}
}
// Child class combining class and interfaces (Hybrid inheritance)
class Bat extends Mammal implements Animal, Flyable {
@Override
public void eat() {
System.out.println("Bat eats insects");
}
@Override
public void fly() {
System.out.println("Bat flies");
}
// Inherited method from Mammal
void sleep() {
System.out.println("Bat sleeps hanging upside down");
}
}
public class Main {
public static void main(String[] args) {
Bat bat = new Bat();
bat.walk(); // Inherited from Mammal class
bat.eat(); // Implemented from Animal interface
bat.fly(); // Implemented from Flyable interface
bat.sleep(); // Bat's own method
}
}
Output:
Program 15
Question :
Write a program in Java to create a package P1 inside P1 there will be a Java Program A.java and C.java
create another package P2 which will contain B.java program. Using the four different access specifiers
we will understand where these access specifiers can be used.
Code:
To create a package we first need to create a Folder with the same name as the package name.
Inside P1 Package
A.java
package P1;
public class A {
public int publicVar = 10;
private int privateVar = 20;
protected int protectedVar = 30;
int defaultVar = 40;
public void showAccess() {
System.out.println("In A:");
System.out.println("Public: " + publicVar);
System.out.println("Private: " + privateVar);
System.out.println("Protected: " + protectedVar);
System.out.println("Default: " + defaultVar);
}
}
C.java
package P1;
public class C {
public void testAccess() {
A a = new A();
System.out.println("In C:");
System.out.println("Public: " + a.publicVar);
// Accessing protected variable from class A (within same package)
System.out.println("Protected: " + a.protectedVar);
// Accessing default variable (within same package)
System.out.println("Default: " + a.defaultVar);
// Cannot access private variable from class A (private variable is not accessible outside class A)
// System.out.println("Private: " + a.privateVar); // This would cause a compile error
}
}
How to compile and run package program:
javac P1\A.java
javac P1\C.java
java C
Inside P2 Package
B.java
package P2;
import P1.A; // Importing class A from P1
public class B {
public void testAccess() {
A a = new A();
System.out.println("In B:");
// Accessing public variable from class A (public is accessible everywhere)
System.out.println("Public: " + a.publicVar);
// Cannot access protected variable from class A (since B is in a different package)
// System.out.println("Protected: " + a.protectedVar); // This would cause a compile error
// Cannot access default (package-private) variable from class A (different package)
// System.out.println("Default: " + a.defaultVar); // This would cause a compile error
// Cannot access private variable from class A
// System.out.println("Private: " + a.privateVar); // This would cause a compile error
}
}
How to compile and run package program:
javac P2\B.java
java B
Interpretation:
Same Package Different Package
Same Class Outside the Subclass Outside the Subclass
class class
public yes yes yes yes yes
private yes no no no no
protected yes yes yes no yes
default yes yes yes no no
Program 16
Question :
Write a Program in JAVA to evaluate the expression z=65/(x-y) and handle the exception in
such a way that your program will not be aborted even if x=y.
Code:
import java.util.*;
public class Expression
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x,y;
double z;
try
{
System.out.println("Enter the value for x : ");
x = sc.nextInt();
System.out.println("Enter the value for y : ");
y = sc.nextInt();
z = 65/(x-y);
System.out.println("The result for the expression is = "+z);
}
catch(ArithmeticException e)
{
System.out.println("Divided by Zero !!..");
}
finally
{
sc.close();
System.out.println("Program executed successfully !!..");
}
}
}
Output:
Program 17
Question :
Write a program in JAVA to read an integer array of size 10 and also display the element at
the 12th index position of the array. Handle the exception in such a way that your program
will not abort.
Code:
import java.util.*;
public class Exception
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int a[] = new int[10];
System.out.println("Enter 10 integers : ");
for(int i=0; i<10; i++)
{
a[i] = sc.nextInt();
}
try
{
System.out.println("Element at 12th index: " + a[12]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception occurred: " +e.getMessage());
System.out.println("Index 12 is out of bounds for the array size 10 !!..");
}
finally
{
sc.close();
System.out.println("Program executed successfully !!..");
}
}
}
Output:
Program 18
Question :
Write a program in JAVA to create a Student class that contains the details about a student
like name, Roll, year, section. Create a student database of 10 students and print their details.
Handle the exception in such a way that your program will not be aborted even if you try to
access the element greater than index 10.
Code:
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
class Student {
String name;
int roll;
int year;
String section;
public Student(String name, int roll, int year, String section) {
this.name = name;
this.roll = roll;
this.year = year;
this.section = section;
}
public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Roll: " + roll);
System.out.println("Year: " + year);
System.out.println("Section: " + section);
}
}
public class StudentDatabase {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
System.out.println("Enter details of 10 students:");
for (int i = 0; i < 10; i++) {
System.out.println("Student " + (i + 1) + ":");
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Roll: ");
int roll = scanner.nextInt();
System.out.print("Year: ");
int year = scanner.nextInt();
scanner.nextLine();
System.out.print("Section: ");
String section = scanner.nextLine();
students.add(new Student(name, roll, year, section));
}
System.out.println("\nStudent details:");
try {
for (int i = 0; i <= 10; i++) {
students.get(i).displayDetails();
}
} catch (IndexOutOfBoundsException e) {
System.out.println("Attempted to access an invalid index! Exception handled.");
} finally {
System.out.println("Program executed successfully.");
}
scanner.close();
}
}
Output: