Java Solution With Correc Tanswer
Java Solution With Correc Tanswer
Q1 Create a class named Student with properties like name, age, and studentId.
Implement a constructor to initialize these properties when a Student object is created.
Add methods to display student information.
this.name = name;
this.age = age;
this.studentId = studentId;
student1.displayInfo();
}
Write a program to print the area of a rectangle by creating a class named 'Area'
taking the values of its length and breadth as parameters of its constructor and
having a method named 'returnArea' which returns the area of the rectangle.
Length and breadth of rectangle are entered through keyboard.
import java.util.Scanner;
class Area {
private double length;
private double breadth;
scanner.close();
}
}
Write a program to store Student details such as name(String), roll no(int) and fees(float). Declare
two contructors, a default contructor with a print statement “System.out.println("Default");” and
a parameterized constructor to intialise all t\he three variables. Use this to execute the default
constructor from the parameterized constructor. Display the values using a display method.
// Default constructor
public Student() {
System.out.println("Default");
}
// Parameterized constructor
public Student(String name, int rollNo, float fees) {
// Invoking the default constructor from the parameterized constructor
this();
this.name = name;
this.rollNo = rollNo;
this.fees = fees;
}
// Person class
class Person {
protected String name;
protected int age;
// Default constructor
public Person() {
this.name = "Unknown";
this.age = 0;
}
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter methods
public String getName() {
return name;
}
// Parameterized constructor
public Student(String name, int age, String studentId) {
super(name, age);
this.studentId = studentId;
}
Create a superclass named Animal with a method sound(). Extend this class to create a
subclass named Dog with a method bark().
class Animal {
System.out.println("Dog barks");
animal.sound();
dog.sound();
dog.bark();
}
Create a superclass named Vehicle with a method start(). Extend this class to create a
subclass named Car, and then further extend Car to create a subclass named
SportsCar, each with additional methods.
class Vehicle {
public void start() {
System.out.println("Vehicle starts");
}
}
// Account superclass
class Account {
protected String accountNumber;
protected double balance;
@Override
public void withdraw(double amount) {
if (balance + overdraftLimit >= amount) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
} else {
System.out.println("Exceeds overdraft limit");
}
}
}
// Testing LoanAccount
LoanAccount loanAccount = new LoanAccount("LA001", 10000.0, 5.0);
loanAccount.displayBalance();
loanAccount.applyInterest();
loanAccount.displayBalance();
}
}
polymorphism and it's types with example
Write a program to demonstrate method overloading. A method which can add two numbers
should be overloaded: Once without parameters, once with two integer numbers and one with
two double numbers. Display the results in the methods.
}
Consider a scenario where you have a base class Shape with a method calculateArea() to
calculate the area of a shape. Now, you want to create subclasses Rectangle and Circle that
inherit from the Shape class. Both Rectangle and Circle should have their own implementation
of the calculateArea() method to calculate the area specific to their shape. Design the class
hierarchy and implement the calculateArea() method in each subclass to override the method
from the Shape class. Also, create instances of Rectangle and Circle, and demonstrate how the
overridden methods work.
// Shape class
class Shape {
public double calculateArea() {
return 0.0; // Default implementation for unknown shape
}
}
@Override
public double calculateArea() {
return length * width;
}
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
You are tasked with creating a simple system to manage shapes. Design an abstract class
Shape with abstract methods calculateArea() and calculatePerimeter(). Then, create concrete
subclasses such as Rectangle and Circle that extend the Shape class and implement the
abstract methods.
@Override
public double calculateArea() {
return length * width;
}
@Override
public double calculatePerimeter() {
return 2 * (length + width);
}
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
System.out.println("\nElephant:");
elephant.makeSound();
}
}
INTERFACE
You are creating a sorting algorithm library. Design an interface SortAlgorithm with a method
sort(int[] array). Then, create classes such as BubbleSort and MergeSort that implement the
SortAlgorithm interface and provide their own implementation of the sort() method to perform
sorting using the respective algorithms.
Provide constructors for each class if necessary, and demonstrate how to use these classes by
creating instances of BubbleSort and MergeSort, and calling their sort() methods with a sample
array.
// SortAlgorithm interface
interface SortAlgorithm {
void sort(int[] array);
}
Design a class Person to represent a person's name and age. Implement the Person class
with the following requirements:
It should have private instance variables name (String) and age (int).
Provide public methods getName() and getAge() to access the name and age variables,
respectively.
Implement a constructor that accepts parameters to initialize the name and age
variables.
Ensure that the age cannot be negative. If an attempt is made to set a negative age, set it
to 0
// Constructor
public Person(String name, int age) {
this.name = name;
if (age < 0) {
this.age = 0; // Set age to 0 if negative
} else {
this.age = age;
}
}
}
Exception Handaling: try catch throw throws and finally
Division Exception:
Write a Java program that takes two integers as input from the user and calculates their
division. Handle the ArithmeticException that may occur if the second number is zero.
import java.util.Scanner;
scanner.close();
}
}
Array Index Out of Bounds:
Define an array of integers. Attempt to access an element at an index beyond the array's
bounds. Handle the ArrayIndexOutOfBoundsException that may occur.
Create a Java class named Person with private instance variables for name, age, and
email. Provide public methods to set and get these variables.
Write another class to test the Person class by creating instances and
accessing/modifying the private variables using the public methods.
Package Practice:
package Practice;
// Constructor
public Person(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
// Getter methods
public String getName() {
return name;
}
// Setter methods
public void setName(String name) {
this.name = name;
}
package math;
if (num2 == 0) {
}
package app;
import math.Calculator;
}
Static Nested Class (Static Inner Class):
Question:
You are designing a music player application. Create a static nested class Song within the
MusicPlayer class to represent individual songs. The Song class should have instance variables
title and artist. Implement a method play() in the Song class that prints "Now playing [title] by
[artist]".
// Constructor
public Song(String title, String artist) {
this.title = title;
this.artist = artist;
}
Question:
You are developing a banking application. Create an inner class Transaction within the Account
class to represent individual transactions. The Transaction class should have instance variables
amount and timestamp. Implement a method printTransaction() in the Transaction class that
prints "Transaction of [amount] at [timestamp]".
import java.time.LocalDateTime;
// Constructor
public Transaction(double amount) {
this.amount = amount;
this.timestamp = LocalDateTime.now();
}
Question:
You are working on a game application. Create a method startGame() in the Game class. Inside
this method, define a local inner class Player representing a game player. The Player class should
have instance variables name and score. Implement a method displayScore() in the Player class
that prints "Player [name] scored [score]".
// Constructor
public Player(String name, int score) {
this.name = name;
this.score = score;
}
Question: Write a Java program that creates a simple interface Animal with a method
sound(). Implement this interface using an anonymous inner class and print "Woof"
inside the sound() method.
Question:
You are creating a program to manage employee information. Write a method writeToFile(String
data) in the EmployeeManager class that writes the provided data to a text file named
employees.txt. Use FileWriter and Bu eredWriter for writing the data to the file.
import java.io.FileWriter;
import java.io.IOException;
bu eredWriter.write(data);
} catch (IOException e) {