0% found this document useful (0 votes)
1 views32 pages

Java Lab Internal-1 Questions

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)
1 views32 pages

Java Lab Internal-1 Questions

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

1.

A) Create a class Vehicle with a method fuelEfficiency() and two subclasses Car and
Truck, each of which overrides the fuelEfficiency() method. Demonstrate dynamic
method dispatch by calling fuelEfficiency() for objects of both subclasses.
class Vehicle{public void fuelEfficiency(){[Link]("Vehicle fuel efficiency");}}
class Car extends Vehicle{@Override public void fuelEfficiency(){[Link]("Car fuel efficiency: 15 km/l");}}
class Truck extends Vehicle{@Override public void fuelEfficiency(){[Link]("Truck fuel efficiency: 8 km/l");}}
public class DynamicMethodDispatch{
public static void main(String[] args){
Vehicle myVehicle = new Vehicle();
Vehicle myCar = new Car();
Vehicle myTruck = new Truck();
[Link]();
[Link]();
[Link]();
}
}

B) Write a program that reads a line of integers, then display each integer and sum of
all integers using StringTokenizer.
import [Link];
public class StringTokenizerExample{
public static void main(String[] args){
String input = "10 20 30 40 50";
StringTokenizer tokenizer = new StringTokenizer(input);
int sum = 0;
while([Link]()){
int number = [Link]([Link]());
[Link](number);
sum += number;
}
[Link]("Sum of all numbers: " + sum);
}
}

2. A)Write a Java program to implement constructor overloading by creating a class


Rectangle that has three constructors: one without parameters, one with width and
height, and one with side length for a square. Demonstrate the usage of all three
constructors.
class Rectangle{int length,width;
public Rectangle(){length=0;width=0;}
public Rectangle(int length,int width){[Link]=length;[Link]=width;}
public Rectangle(int side){[Link]=side;[Link]=side;}
public int area(){return length*width;}
public int perimeter(){return 2*(length+width);}
}
public class Main{
public static void main(String[] args){
Rectangle rect1 = new Rectangle();
Rectangle rect2 = new Rectangle(5,10);
Rectangle rect3 = new Rectangle(4);

[Link]("Rectangle 1:");
[Link]("Area: " + [Link]());
[Link]("Perimeter: " + [Link]());

[Link]("\nRectangle 2:");
[Link]("Area: " + [Link]());
[Link]("Perimeter: " + [Link]());

[Link]("\nRectangle 3 (Square):");
[Link]("Area: " + [Link]());
[Link]("Perimeter: " + [Link]());
}
}

B) Write a java program to demonstrate local and member inner class


class OuterClass{int outer_x=10;
class InnerClass{int inner_x=5;
void display(){[Link]("Inner Class: "+inner_x);[Link]("Outer Class: "+outer_x);}}
void outerMethod(){InnerClass innerObject = new InnerClass();[Link]();}
public static void main(String[] args){OuterClass outerObject = new OuterClass();[Link]();}
}

3. A) Develop a Java program to demonstrate single and multiple inheritance using classes
and interfaces: Use a superclass Animal and subclasses like Dog and Bird, and also
include an interface CanFly to be implemented by the Bird class.
interface CanFly{void fly();}
class Animal{public void eat(){[Link]("Animal is eating.");}}
class Dog extends Animal{public void bark(){[Link]("Dog is barking.");}}
class Bird extends Animal implements CanFly{@Override public void fly(){[Link]("Bird is flying.");}public void
chirp(){[Link]("Bird is chirping.");}}
public class InheritanceExample{
public static void main(String[] args){
Dog dog = new Dog(); Bird bird = new Bird();
[Link](); [Link]();
[Link](); [Link](); [Link]();
}
}

B) Write java program(S) to show the usage of the “final” keyword for variable,
method, and class.
public class FinalKeywordExample{
public static void main(String[] args){
final double PI = 3.14159;
final class FinalClass{public final void finalMethod(){[Link]("This method cannot be overridden.");}}
FinalClass obj = new FinalClass();
[Link]();
}
}

4. A) Write a Java program to implement the concept of hierarchical inheritance. Create a


superclass Shape with two methods calculate and display the area and derive two
subclasses, Circle and Rectangle.
class Shape{public void calculateArea(){}public void displayArea(){}}
class Circle extends Shape{private double radius;public Circle(double radius){[Link]=radius;}@Override public void
calculateArea(){[Link]("Area of circle: "+[Link]*radius*radius);}@Override public void displayArea()
{calculateArea();}}
class Rectangle extends Shape{private double length,width;public Rectangle(double length,double width)
{[Link]=length;[Link]=width;}@Override public void calculateArea(){[Link]("Area of rectangle:
"+length*width);}@Override public void displayArea(){calculateArea();}}
public class Main{public static void main(String[] args){Circle circle = new Circle(5.0);Rectangle rectangle = new
Rectangle(4.0,6.0);[Link]();[Link]();}}
B) Develop a program that implements a simple calculator using switch-case to handle operations like addition, subtraction,
multiplication, and division based on user input.

5. Create two package mathOperations. Inside mathOperations, define a class


MathOperations that has methods to add, subtract, multiply, and divide two numbers.
In another package displayResults, create a class Display with a method to print the
result. Import mathOperations package in the program Display to perform operations.
package mathOperations;
public class MathOperations{
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 int divide(int a, int b){if(b==0)throw new ArithmeticException("Division by zero");return a/b;}
}

package displayResults;
import [Link];
public class Display{
public static void main(String[] args){
int num1 = 10, num2 = 5;
[Link]("Sum: " + [Link](num1, num2));
[Link]("Difference: " + [Link](num1, num2));
[Link]("Product: " + [Link](num1, num2));
[Link]("Quotient: " + [Link](num1, num2));
}
}

B) Implement a java program to print week of the day using a switch-case.


import [Link];
public class WeekdayPrinter{
public static void main(String[] args){
Scanner scanner = new Scanner([Link]);
[Link]("Enter the day number (1-7): ");
int day = [Link]();
switch(day){
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
case 4: [Link]("Thursday"); break;
case 5: [Link]("Friday"); break;
case 6: [Link]("Saturday"); break;
case 7: [Link]("Sunday"); break;
default: [Link]("Invalid day number");
}
}
}

6. A) Write a Java program to create a package named conversion containing classes


LengthConverter (for converting meters to kilometers) and TemperatureConverter (for
converting Celsius to Fahrenheit). Demonstrate the use of these classes in the main
program by importing the conversion package.
package conversion;
public class LengthConverter{public double metersToKilometers(double meters){return meters/1000;}}
package conversion;
public class TemperatureConverter{public double celsiusToFahrenheit(double celsius){return (celsius*9/5)+32;}}
import [Link];
import [Link];
public class ConverterDemo{
public static void main(String[] args){
LengthConverter lengthConverter = new LengthConverter();
TemperatureConverter temperatureConverter = new TemperatureConverter();
double kilometers = [Link](5000);
[Link]("5000 meters is equal to " + kilometers + " kilometers.");
double fahrenheit = [Link](25);
[Link]("25 degrees Celsius is equal to " + fahrenheit + " degrees Fahrenheit.");
}
}

B) Implement a java program to multiplication of two matrices.


7. A)Write a Java program that accepts a string from the user and counts the number of
vowels, consonants, digits, and spaces in the string.
import [Link];
public class CharacterCount{
public static void main(String[] args){
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String inputString = [Link]();
int vowels = 0, consonants = 0, digits = 0, spaces = 0;
for(int i=0;i<[Link]();i++){
char ch = [Link](i);
if([Link](ch)) digits++;
else if([Link](ch)) spaces++;
else if([Link](ch)){
if("AEIOUaeiou".indexOf(ch) != -1) vowels++;
else consonants++;
}
}
[Link]("Vowels: " + vowels);
[Link]("Consonants: " + consonants);
[Link]("Digits: " + digits);
[Link]("Spaces: " + spaces);
}
}

B) Write a program that reads a line of integers, then display each integer and sum of all
integers using StringTokenizer.
import [Link];
public class StringTokenizerExample{
public static void main(String[] args){
String input = "10 20 30 40 50";
StringTokenizer tokenizer = new StringTokenizer(input);
int sum = 0;
while([Link]()){
int number = [Link]([Link]());
[Link](number);
sum += number;
}
[Link]("Sum of all numbers: " + sum);
}

8. A) Develop a program that implements a simple calculator using a switch-case to handle


operations like addition, subtraction, multiplication, and division based on user input.
import [Link];
public class SimpleCalculator{
public static void main(String[] args){
Scanner scanner = new Scanner([Link]);
[Link]("Enter the first number: ");
double num1 = [Link]();
[Link]("Enter the second number: ");
double num2 = [Link]();
[Link]("Enter the operator (+, -, *, /): ");
char operator = [Link]().charAt(0);
double result;
switch(operator){
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/':
if(num2 == 0){[Link]("Error: Division by zero"); return;}
result = num1 / num2; break;
default: [Link]("Invalid operator"); return;
}
[Link]("Result: " + result);
}
}

B)Create a superclass BankAccount with a constructor to initialize accountNumber and


balance. Extend this class with SavingsAccount and CurrentAccount. Override a
method calculateInterest() in both subclasses. Demonstrate dynamic method dispatch by
creating objects of these subclasses.
abstract class BankAccount {
protected int accountNumber;
protected double balance;

public BankAccount(int accountNumber, double balance) {


[Link] = accountNumber;
[Link] = balance;
}

public abstract void calculateInterest();

public void displayBalance() {


[Link]("Account Number: " + accountNumber);
[Link]("Balance: " + balance);
}
}

class SavingsAccount extends BankAccount {


private double interestRate;

public SavingsAccount(int accountNumber, double balance, double interestRate) {


super(accountNumber, balance);
[Link] = interestRate;
}

@Override
public void calculateInterest() {
double interest = balance * interestRate / 100;
balance += interest;
[Link]("Interest added: " + interest);
}
}

class CurrentAccount extends BankAccount {


private double overdraftLimit;

public CurrentAccount(int accountNumber, double balance, double overdraftLimit) {


super(accountNumber, balance);
[Link] = overdraftLimit;
}

@Override
public void calculateInterest() {
// No interest for current accounts
}
}

public class BankAccountDemo {


public static void main(String[] args) {
SavingsAccount savingsAccount = new SavingsAccount(12345, 1000, 5.0);
CurrentAccount currentAccount = new CurrentAccount(67890, 2000, 1000);

[Link]();
[Link]();

[Link]();
[Link]();
}
}

9. A) Write a Java program that uses parameterized constructors in a class Employee. The
class should have employeeName, employeeID, and salary fields. Provide constructors
with different numbers of parameters and demonstrate constructor overloading.
class Employee {
String employeeName;
int employeeID;
double salary;

// Default constructor
public Employee() {
employeeName = "Unknown";
employeeID = 0;
salary = 0.0;
}

// Constructor with name and ID


public Employee(String employeeName, int employeeID) {
[Link] = employeeName;
[Link] = employeeID;
[Link] = 0.0;
}

// Constructor with all fields


public Employee(String employeeName, int employeeID, double salary) {
[Link] = employeeName;
[Link] = employeeID;
[Link] = salary;
}

public void displayEmployeeDetails() {


[Link]("Employee Name: " + employeeName);
[Link]("Employee ID: " + employeeID);
[Link]("Salary: " + salary);
}
}

public class Main {


public static void main(String[] args) {
Employee employee1 = new Employee();
Employee employee2 = new Employee("Alice", 123);
Employee employee3 = new Employee("Bob", 456, 50000.0);

[Link]();
[Link]();
[Link]();
}
}

B) Write a Java program to show the usage of the “super” keyword to access the
instance variables and methods and the usage of super() and this() methods.
class Parent {
int x = 10;

public void printX() {


[Link]("Parent x: " + x);
}
}

class Child extends Parent {


int x = 20;
public Child() {
super(); // Call the parent class's constructor
[Link]("Child constructor");
}

public void printX() {


[Link]("Child x: " + x);
[Link]("Parent x: " + super.x);
}
}

public class Main {


public static void main(String[] args) {
Child child = new Child();
[Link]();
}
}

10. A) Create a class Box that includes length, breadth, and height as fields. Write
constructors to initialize a cube and a rectangular box and print the volume for both
types of boxes.
class Box {
int length, breadth, height;

// Constructor for a cube


public Box(int side) {
length = breadth = height = side;
}

// Constructor for a rectangular box


public Box(int length, int breadth, int height) {
[Link] = length;
[Link] = breadth;
[Link] = height;
}

public int calculateVolume() {


return length * breadth * height;
}

public 1 void displayVolume() {


[Link]("Volume: " + calculateVolume());
}
}
public class Main {
public static void main(String[] args) {
Box cube = new Box(5);
Box rectangularBox = new Box(4, 6, 8);

[Link]();
[Link]();
}
}

B) Show the usage of the “super” keyword and super() in the above program.

11. A) Create a superclass Person and two subclasses Student and Employee. The Student
class should have fields for course and year, and Employee should have fields for
department and salary. Use a method displayDetails() in each class to display the
specific details. Demonstrate single inheritance.
class Person {
String name;
int age;

public Person(String name, int age) {


[Link] = name;
[Link] = age;
}

public void displayDetails() {


[Link]("Name: " + name);
[Link]("Age: " + age);
}
}

class Student extends Person {


String course;
int year;

public Student(String name, int age, String course, int year) {


super(name, age);
[Link] = course;
[Link] = year;
}

@Override
public void displayDetails() {
[Link]();
[Link]("Course: " + course);
[Link]("Year: " + year);
}
}

class Employee extends Person {


String department;
double salary;

public Employee(String name, int age, String department, double salary) {


super(name, age);
[Link] = department;
[Link] = salary;
}

@Override
public void displayDetails() {
[Link]();
[Link]("Department: " + department);
[Link]("Salary: " + salary);
}
}

public class InheritanceExample {


public static void main(String[] args) {
Student student = new Student("Alice", 20, "Computer Science", 3);
Employee employee = new Employee("Bob", 30, "IT", 50000.0);

[Link]();
[Link]();
}
}

B) Write a java program to demonstrate local and member inner class


class OuterClass {
int outer_x = 10;

class InnerClass {
int inner_x = 5;

void display() {
[Link]("Inner Class: " + inner_x);
[Link]("Outer Class: " + outer_x);
}
}

void outerMethod() {
InnerClass innerObject = new InnerClass();
[Link]();
}

public static void main(String[] args) {


OuterClass outerObject = new OuterClass();
[Link]();
}
}

12. A) Write a Java program to implement a multilevel inheritance using a Vehicle class as
the base class, Car as the intermediate class, and ElectricCar as the derived class.
Demonstrate how properties and methods are inherited across multiple levels.
class Vehicle {
protected String color;
protected int maxSpeed;

public Vehicle(String color, int maxSpeed) {


[Link] = color;
[Link] = maxSpeed;
}

public void displayVehicleDetails() {


[Link]("Color: " + color);
[Link]("Max Speed: " + maxSpeed);
}
}

class Car extends Vehicle {


private int numberOfDoors;

public Car(String color, int maxSpeed, int numberOfDoors) {


super(color, maxSpeed);
[Link] = numberOfDoors;
}

public void displayCarDetails() {


[Link]();
[Link]("Number of Doors: " + numberOfDoors);
}
}

class ElectricCar extends Car {


private int batteryRange;

public ElectricCar(String color, int maxSpeed, int numberOfDoors, int batteryRange) {


super(color, maxSpeed, numberOfDoors);
[Link] = batteryRange;
}

public void displayElectricCarDetails() {


[Link]();
[Link]("Battery Range: " + batteryRange);
}
}

public class MultilevelInheritanceExample {


public static void main(String[] args) {
ElectricCar electricCar = new ElectricCar("Red", 120, 4, 300);
[Link]();
}
}

B) Write java program(S) to show the usage of the “final” keyword for variable,
method, and class.
public class FinalKeywordExample {
public static void main(String[] args) {
// Final variable
final double PI = 3.14159;
// PI = 3.15; // This will cause a compilation error

// Final method
final class FinalClass {
public final void finalMethod() {
[Link]("This method cannot be overridden.");
}
}

FinalClass obj = new FinalClass();


[Link](); // This will work

// Cannot create a subclass of a final class


// class SubClass extends FinalClass {} // This will cause a compilation error
}
}

13. A) Design a Java program to implement the concept of an interface. Create an interface
Shape with methods draw() and calculateArea(). Implement this interface in two classes
Circle and Rectangle, and override these methods.
interface Shape {
void draw();
double calculateArea();
}

class Circle implements Shape {


private double radius;
public Circle(double radius) {
[Link] = radius;
}

@Override
public void draw() {
[Link]("Drawing a circle");
}

@Override
public double calculateArea() {
return [Link] * radius * radius;
}
}

class Rectangle implements Shape {


private double length;
private double width;

public Rectangle(double length, double width) {


[Link] = length;
[Link] = width;
}

@Override
public void draw() {
[Link]("Drawing a rectangle");
}

@Override
public double calculateArea() {
return length * width;
}
}

public class InterfaceExample {


public static void main(String[] args) {
Shape circle = new Circle(5.0);
Shape rectangle = new Rectangle(4.0, 6.0);

[Link]();
[Link]("Area of circle: " + [Link]());

[Link]();
[Link]("Area of rectangle: " + [Link]());
}
}

B) Create a class Counter with:


• A static variable count that keeps track of the number of objects created.
• A non-static variable id that uniquely identifies each object.
• A constructor that increments count and assigns a unique value to id for
each object.
Exercise: Write a Java program to create multiple instances of Counter and print the
value of count and id for each object.
class Counter {
private static int count;
private int id;

public Counter() {
count++;
id = count;
}

public void display() {


[Link]("Object ID: " + id);
[Link]("Total Objects: " + count);
}
}

public class Main {


public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

[Link]();
[Link]();
[Link]();
}
}

14. A) Implement a Java program to simulate a library management system. Use


inheritance and interfaces where Book, Journal, and Magazine are subclasses of Item,
and an interface Borrowable is implemented by items that can be borrowed.
interface Borrowable {
void borrow();
void returnItem();
}

class Item {
private String title;
private String author;
public Item(String title, String author) {
[Link] = title;
[Link] = author;
}

public String getTitle() {


return title;
}

public String getAuthor() {


return author;
}
}

class Book extends Item implements Borrowable {


private int ISBN;

public Book(String title, String author, int ISBN) {


super(title, author);
[Link] = ISBN;
}

@Override
public void borrow() {
[Link]("Book borrowed: " + title);
}

@Override
public void returnItem() {
[Link]("Book returned: " + title);
}
}

class Journal extends Item implements Borrowable {


private int issueNumber;
private String publicationDate;

public Journal(String title, String author, int issueNumber, String publicationDate) {


super(title, author);
[Link] = issueNumber;
[Link] = publicationDate;
}

@Override
public void borrow() {
[Link]("Journal borrowed: " + title + ", Issue: " + issueNumber);
}

@Override
public void returnItem() {
[Link]("Journal returned: " + title + ", Issue: " + issueNumber);
}
}

class Magazine extends Item implements Borrowable {


private int issueNumber;
private String publicationDate;

public Magazine(String title, String author, int issueNumber, String publicationDate) {


super(title, author);
[Link] = issueNumber;
[Link] = publicationDate;
}

@Override
public void borrow() {
[Link]("Magazine borrowed: " + title + ", Issue: " + issueNumber);
}

@Override
public void returnItem() {
[Link]("Magazine returned: " + title + ", Issue: " + issueNumber);
}
}

public class Library {


public static void main(String[] args) {
Book book = new Book("The Lord of the Rings", "J.R.R. Tolkien", 9780547991029);
Journal journal = new Journal("Nature", "Various Authors", 5892, "2023-11-27");
Magazine magazine = new Magazine("National Geographic", "Various Authors", 12, "December 2023");

[Link]();
[Link]();
[Link]();

[Link]();
[Link]();
[Link]();
}
}

B) Write a Java program to demonstrate Anonymous Inner class


public class AnonymousInnerClassExample{
public static void main(String[] args){
Runnable runnable = new Runnable(){public void run(){[Link]("This is an anonymous inner class.");}};
Thread thread = new Thread(runnable);
[Link]();
}
}
15. A) Implement a Java program that takes two integers and an operator from the user
operates and prints the result
import [Link];

public class ArithmeticOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Enter the first number: ");


int num1 = [Link]();

[Link]("Enter the second number: ");


int num2 = [Link]();

[Link]("Enter the operator (+, -, *, /): ");


char operator = [Link]().charAt(0);

int result;

switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0) {
[Link]("Error: Division by zero");
return;
}
result = num1 / num2;
break;
default:
[Link]("Invalid operator");
return;
}

[Link]("Result: " + result);


}
}

B) write a Java program to implement Hybrid Inheritance (single and hierarchical)


class Animal{public void eat(){[Link]("Animal eats");}}
class Dog extends Animal{public void bark(){[Link]("Dog barks");}}
class Cat extends Animal{public void meow(){[Link]("Cat meows");}}
public class HybridInheritance{
public static void main(String[] args){
Dog dog = new Dog(); Cat cat = new Cat();
[Link](); [Link]();
[Link](); [Link]();
}
}

16. A) write a java program to use the “final” keyword for variable, method and class
public class FinalKeywordExample {
public static void main(String[] args) {
// Final variable
final double PI = 3.14159;
// PI = 3.15; // This will cause a compilation error

// Final method
final class FinalClass {
public final void finalMethod() {
[Link]("This method cannot be overridden.");
}
}

FinalClass obj = new FinalClass();


[Link](); // This will work

// Cannot create a subclass of a final class


// class SubClass extends FinalClass {} // This will cause a compilation error
}
}

B) Implement a java program to multiplication of two matrices.


public class MatrixMultiplication {
public static void main(String[] args) {
int[][] m1 = {{1, 2, 3}, {4, 5, 6}};
int[][] m2 = {{7, 8}, {9, 10}, {11, 12}};
int rows1 = [Link], cols1 = m1[0].length, rows2 = [Link], cols2 = m2[0].length;
if (cols1 != rows2) return;
int[][] result = new int[rows1][cols2];
for (int i = 0; i < rows1; i++)
for (int j = 0; j < cols2; j++)
for (int k = 0; k < cols1; k++)
result[i][j] += m1[i][k] * m2[k][j];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
[Link](result[i][j] + " ");
}
[Link]();
}
}

17. write a java program to create an abstract class Accounts with the following details:
a) balance b) account number c) accountHolders name d) address

Methods: [Link]()-abstract [Link]()-abstract [Link]()-to show the


balance of the account number.

Create a subclass of this class SavingsAccount and add the following details:

Data Members: a)rateofInterest

Methods: a)calculateAmount() b)display()-To display rate of interest with new


balance and full account holder details.

Create another subclass of the Accounts class,i.e,Current Account with the following:

Data members: a)overdraftLimit

Method: a) display()—to show overdraft limit along with the full account holder
details.

Create objects of these two classes and call their [Link] appropriate constructors.

abstract class Accounts {

protected int balance;

protected int accountNumber;

protected String accountHolderName;

protected String address;


public Accounts(int balance, int accountNumber, String accountHolderName, String address) {

[Link] = balance;

[Link] = accountNumber;

[Link] = accountHolderName;

[Link] = address;

public abstract void withdraw(int amount);

public abstract void deposit(int amount);

public void display() {

[Link]("Account Number: " + accountNumber);

[Link]("Account Holder Name: " + accountHolderName);

[Link]("Address: " + address);

[Link]("Balance: " + balance);

class SavingsAccount extends Accounts {

private double rateOfInterest;

public SavingsAccount(int balance, int accountNumber, String accountHolderName, String address, double rateOfInterest)
{

super(balance, accountNumber, accountHolderName, address);

[Link] = rateOfInterest;

@Override

public void withdraw(int amount) {

if (balance - amount >= 0) {

balance -= amount;

[Link]("Amount withdrawn: " + amount);

} else {

[Link]("Insufficient balance.");
}

@Override

public void deposit(int amount) {

balance += amount;

[Link]("Amount deposited: " + amount);

public void calculateInterest() {

double interest = balance * rateOfInterest / 100;

balance += interest;

[Link]("Interest added: " + interest);

@Override

public void display() {

[Link]();

[Link]("Rate of Interest: " + rateOfInterest);

[Link]("New Balance: " + balance);

class CurrentAccount extends Accounts {

private int overdraftLimit;

public CurrentAccount(int balance, int accountNumber, String accountHolderName, String address, int overdraftLimit) {

super(balance, accountNumber, accountHolderName, address);

[Link] = overdraftLimit;

@Override

public void withdraw(int amount) {


if (balance - amount >= -overdraftLimit) {

balance -= amount;

[Link]("Amount withdrawn: " + amount);

} else {

[Link]("Overdraft limit exceeded.");

@Override

public void deposit(int amount) {

balance += amount;

[Link]("Amount deposited: " + amount);

@Override

public void display() {

[Link]();

[Link]("Overdraft Limit: " + overdraftLimit);

public class Main {

public static void main(String[] args) {

SavingsAccount savingsAccount = new SavingsAccount(1000, 12345, "John Doe", "123 Main St", 5.0);

CurrentAccount currentAccount = new CurrentAccount(2000, 67890, "Jane Smith", "456 Elm St", 1000);

[Link](500);

[Link]();

[Link]();

[Link](1500);

[Link](800);

[Link]();
}

18. Create a class named Employee with the following details:

Data Members:

a)name b)address c)age d)gender

Method:

a)display()-to show the employee details.

Create another class FullTimeEmployee that inherits the Employee class:

Data members:

a)salary b)designation

Method:

a)display()—to show the salary and designation along other employee details

create another class PartTimeEmployee that inherits the Employee class:


Data members:

a)workingHours b)ratePerHour

Methods:

a)calculatePay()-to calculate the amount payable

b)display()-to show the amount payable along with other employee details

create objects of these classes and call their [Link] appropriate constructors.

class Employee {

String name;

String address;

int age;

String gender;

public Employee(String name, String address, int age, String gender) {

[Link] = name;

[Link] = address;

[Link] = age;

[Link] = gender;

public void display() {

[Link]("Name: " + name);

[Link]("Address: " + address);

[Link]("Age: " + age);

[Link]("Gender: " + gender);

class FullTimeEmployee extends Employee {

double salary;

String designation;
public FullTimeEmployee(String name, String address, int age, String gender, double salary, String designation) {

super(name, address, age, gender);

[Link] = salary;

[Link] = designation;

@Override

public void display() {

[Link]();

[Link]("Salary: " + salary);

[Link]("Designation: " + designation);

class PartTimeEmployee extends Employee {

int workingHours;

double ratePerHour;

public PartTimeEmployee(String name, String address, int age, String gender, int workingHours, double ratePerHour) {

super(name, address, age, gender);

[Link] = workingHours;

[Link] = ratePerHour;

public double calculatePay() {

return workingHours * ratePerHour;

@Override

public void display() {

[Link]();

[Link]("Amount Payable: " + calculatePay());


}

public class Main {

public static void main(String[] args) {

FullTimeEmployee fte = new FullTimeEmployee("Alice", "123 Main St", 30, "Female", 50000.0, "Manager");

PartTimeEmployee pte = new PartTimeEmployee("Bob", "456 Elm St", 25, "Male", 20, 15.0);

[Link]();

[Link]();

19. a) Define a Person class with attributes name and age. Include a method greet() that
prints a greeting message including the person's name. Create an object of this class and
call the greet() method.
class Person {
String name;
int age;

public void greet() {


[Link]("Hello, my name is " + name + " and I am " + age + " years
old.");
}
}

public class Main {


public static void main(String[] args) {
Person person1 = new Person();
[Link] = "Alice";
[Link] = 30;
[Link]();
}
}

b) Modify the Person class to include a constructor that initializes the name and age
attributes. Create an object using this constructor and call the greet() method.
class Person {

String name;

int age;

public Person(String name, int age) {

[Link] = name;

[Link] = age;

public void greet() {

[Link]("Hello, my name is " + name + " and I am " + age + " years old.");

public class Main {

public static void main(String[] args) {

Person person2 = new Person("Bob", 25);

[Link]();

c) Write a java program to use “super” keyword to access the instance variables and
methods and usage of super() and this() methods.

class Parent {

int x = 10;

public void printX() {

[Link]("Parent x: " + x);

}
class Child extends Parent {

int x = 20;

public Child() {

super(); // Call the parent class's constructor

[Link]("Child constructor");

public void printX() {

[Link]("Child x: " + x);

[Link]("Parent x: " + super.x);

public class Main {

public static void main(String[] args) {

Child child = new Child();

[Link]();

20. A) write a java program to create a package , accessing, importing from another
package and use all access modifiers (public,private,default and protected) in the
package.
// Package 1: mypackage
package mypackage;

public class MyClass {


public int publicVariable = 10;
private int privateVariable = 20;
int defaultVariable = 30;
protected int protectedVariable = 40;
public void publicMethod() {
[Link]("Public method");
}

private void privateMethod() {


[Link]("Private method");
}

void defaultMethod() {
[Link]("Default method");
}

protected void protectedMethod() {


[Link]("Protected method");
}
}

// Package 2: mainpackage
package mainpackage;

import [Link];

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();

// Accessing public members


[Link]([Link]);
[Link]();

// Accessing protected members within the same package


[Link]();
[Link]();
}
}
b) Create a class MathOperations with:
o A static method square(int x) that returns the square of an integer.
o A static method cube(int x) that returns the cube of an integer.
o A static method factorial(int x) that returns the factorial of an integer.
Exercise: Write a Java program that calls these static methods from MathOperations
without creating an object of the class. Test the methods with various inputs.
class MathOperations {
public static int square(int x) {
return x * x;
}

public static int cube(int x) {


return x * x * x;
}

public static int factorial(int x) {


if (x == 0) {
return 1;
} else {
return x * factorial(x - 1);
}
}
}

public class Main {


public static void main(String[] args) {
int num = 5;

int squareResult = [Link](num);


int cubeResult = [Link](num);
int factorialResult = [Link](num);

[Link]("Square of " + num + " is: " + squareResult);


[Link]("Cube of " + num + " is: " + cubeResult);
[Link]("Factorial of " + num + " is: " + factorialResult);
}
}

21. a) Create a StringBuffer with the content "Hello". Perform the following operations:

Append " World" to it.

Insert "Java " before "World".

Replace "Java" with "Java Programming".

Delete "Programming".

Reverse the entire string.

b) Write a Java program to demonstrate local and member inner class

// a) StringBuffer Operations

import [Link].*;

public class StringBufferExample {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Hello");

[Link](" World");

[Link](6, "Java ");

[Link](6, 10, "Java Programming");

[Link](10, 21);

[Link]();

[Link](sb);

}
// b) Local and Member Inner Classes

class OuterClass {

int outer_x = 10;

class InnerClass {

int inner_x = 5;

void display() {

[Link]("Inner Class: " + inner_x + ", Outer Class: " + outer_x);

void outerMethod() {

InnerClass innerObject = new InnerClass();

[Link]();

public static void main(String[] args) {

OuterClass outerObject = new OuterClass();

[Link]();

You might also like