Java Lab
Java Lab
Write a program to create a class electricity and calculate the bill based on the following
conditions.
If unit<100 bill=1.20*unit
Unit<200 bill=(100*1.20)+(unit-100*2)
Unit<300 bill=(100*1.20)+(unit-100*2)+(unit-200+3)
import java.util.Scanner;
class Electricity {
private int units;
public Electricity(int units) {
this.units = units;
}
public double calculateBill() {
double bill;
if (units < 100) {
bill = 1.20 * units;
} else if (units < 200) {
bill = (100 * 1.20) + (units - 100) * 2;
} else if (units < 300) {
bill = (100 * 1.20) + (100 * 2) + (units - 200) * 3;
} else {
System.out.println("For units greater than 300, additional conditions need to
be implemented.");
return -1;
}
return bill;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the units consumed: ");
int unitsConsumed = scanner.nextInt();
Electricity electricity = new Electricity(unitsConsumed);
double totalBill = electricity.calculateBill();
if (totalBill != -1) {
System.out.printf("The electricity bill for %d units is: Rs.%.2f%n", unitsConsumed, totalBill);
}
}
}
Output :
2. Write a program to create a class account with the instance variables accno, name, balance,
account_type. Define 4 methods getData(), display(), withdraw(), deposit().
import java.util.Scanner;
class Account {
private int accNo;
private String name;
private double balance;
private String accountType;
public void getData() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Account Number: ");
accNo = scanner.nextInt();
System.out.print("Enter Name: ");
scanner.nextLine();
name = scanner.nextLine();
System.out.print("Enter Initial Balance: ");
balance = scanner.nextDouble();
System.out.print("Enter Account Type: ");
accountType = scanner.next();
}
public void display() {
System.out.println("Account Number: " + accNo);
System.out.println("Name: " + name);
System.out.println("Balance: $" + balance);
System.out.println("Account Type: " + accountType);
}
public void withdraw(double amount) {
if (amount > 0 && amount <=
balance) { balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: $" + balance);
} else {
System.out.println("Invalid withdrawal amount or insufficient balance.");
}
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. Updated balance: $" + balance);
} else {
System.out.println("Invalid deposit amount.");
}
}
public static void main(String[] args) {
Account account = new Account();
account.getData(); System.out.println("\
nAccount Details:"); account.display();
account.withdraw(50.0);
account.deposit(100.0);
System.out.println("\nUpdated Account
Details:"); account.display();
}
}
Output :
3. Default constructor to create a class student(roll no, name, age and course) initialize these
instance variables using default constructors and print its content.
class Student {
private int rollNo;
private String name;
private int age;
private String course;
public Student() {
this.rollNo = 0;
this.name = "Unknown";
this.age = 0;
this.course = "Not specified";
}
public void display() {
System.out.println("Roll Number: " + rollNo);
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Course: " + course);
}
public static void main(String[] args) {
Student student = new Student();
System.out.println("Default Student Details:");
student.display();
}
}
Output :
4. Write a program to perform Fibonacci series using command line arguments.
public class FibonacciSeries {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Please provide the number of terms as a command line argument.");
return;
}
int numTerms = Integer.parseInt(args[0]);
if (numTerms <= 0) {
System.out.println("Please provide a positive integer as the number of terms.");
return;
}
System.out.println("Fibonacci Series with " + numTerms + " terms:");
int firstTerm = 0, secondTerm = 1;
for (int i = 0; i < numTerms; i++) {
System.out.print(firstTerm + " ");
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}
Output :
java FibonacciSeries 7
0112358
5. Write a program to create a class rectangle(length, breadth) define parameterized
constructor and calculate area and display them.
class Rectangle {
private double length;
private double breadth;
public Rectangle(double length, double breadth) {
this.length = length;
this.breadth = breadth;
}
public double calculateArea() {
return length * breadth;
}
public void display() {
System.out.println("Length: " + length);
System.out.println("Breadth: " + breadth);
System.out.println("Area: " + calculateArea());
}
public static void main(String[] args) {
Rectangle myRectangle = new Rectangle(5.0, 8.0);
System.out.println("Rectangle Details:");
myRectangle.display();
}
}
Output :
6. Write a program to calculate simple interest and amount using constructor overloading.
import java.util.Scanner;
class InterestCalculator {
private double principal;
private double rate;
private double time;
private double
simpleInterest; private
double amount;
public InterestCalculator(double principal, double rate, double time) {
this.principal = principal;
this.rate = rate;
this.time =
time;
}
public InterestCalculator(double principal, double rate, double time, double amount) {
this(principal, rate, time);
this.amount = amount;
}
public void calculateSimpleInterest()
{ simpleInterest = (principal * rate * time) /
100;
}
public void calculateAmount() {
amount = principal + simpleInterest;
}
public void display() {
System.out.println("Principal: Rs." + principal);
System.out.println("Rate: " + rate + "%");
System.out.println("Time: " + time + " years");
System.out.println("Simple Interest: $" + simpleInterest);
System.out.println("Amount: Rs." + amount);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Principal amount: ");
double principal = scanner.nextDouble();
System.out.print("Enter Rate of interest:
"); double rate = scanner.nextDouble();
System.out.print("Enter Time (in years): ");
double time = scanner.nextDouble();
InterestCalculator interestCalculator1 = new InterestCalculator(principal, rate, time);
interestCalculator1.calculateSimpleInterest();
interestCalculator1.calculateAmount();
System.out.println("\nDetails for Interest Calculator 1:");
interestCalculator1.display();
System.out.println("\n ");
System.out.print("Enter Amount: ");
double amount = scanner.nextDouble();
InterestCalculator interestCalculator2 = new InterestCalculator(principal, rate, time, amount);
interestCalculator2.calculateSimpleInterest();
System.out.println("\nDetails for Interest Calculator 2:");
interestCalculator2.display();
}
}
Output :
7. Write a program to show copy constructor STUDENT CLASS.
class Student {
private int rollNo;
private String name;
private int age;
private String course;
public Student(int rollNo, String name, int age, String course) {
this.rollNo = rollNo;
this.name = name;
this.age = age;
this.course = course;
}
public Student(Student originalStudent) {
this.rollNo = originalStudent.rollNo;
this.name = originalStudent.name;
this.age = originalStudent.age;
this.course = originalStudent.course;
}
public void display() {
System.out.println("Roll Number: " + rollNo);
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Course: " + course);
}
public static void main(String[] args) {
Student student1 = new Student(101, "John Doe", 20, "Computer Science");
System.out.println("Details of Original Student:");
student1.display();
Student student2 = new Student(student1);
System.out.println("\nDetails of Copied Student:");
student2.display();
}
}
Output :
8. Write a program to count number of objects using static method.
class ObjectCounter {
private static int objectCount =
0; public ObjectCounter() {
objectCount++;
}
public static int getObjectCount() {
return objectCount;
}
}
class ObjectCounterDemo {
public static void main(String[] args) {
ObjectCounter obj1 = new ObjectCounter();
ObjectCounter obj2 = new ObjectCounter();
ObjectCounter obj3 = new ObjectCounter();
System.out.println("Number of objects created: " + ObjectCounter.getObjectCount());
}
}
Output :
9. Write a program to create a class student with fields roll no, name, college and take college
as the static data member and display.
import java.util.Scanner;
class Student {
private int rollNo;
private String name;
private static String college;
public Student(int rollNo, String name) {
this.rollNo = rollNo;
this.name = name;
}
public static void setCollege(String collegeName) {
college = collegeName;
}
public void display() {
System.out.println("Roll Number: " + rollNo);
System.out.println("Name: " + name);
System.out.println("College: " + college);
}
}
class StudentDemo {
public static void main(String[] args)
{ Student.setCollege("XYZ College");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Roll Number: ");
int rollNo = scanner.nextInt();
System.out.print("Enter Name: ");
scanner.nextLine();
String name = scanner.nextLine();
Student student = new Student(rollNo, name);
System.out.println("\nStudent Details:");
student.display();
}
}
Output :
10. Write a program to find the area of a triangle, square and rectangle using method overloading.
import java.util.Scanner;
class AreaCalculator {
static double calculateArea(double base, double height) {
return 0.5 * base * height;
}
static double calculateArea(double side) {
return side * side;
}
static double calculateArea(float length, float width) {
return length * width;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the base of the triangle:
"); double base = scanner.nextDouble();
System.out.print("Enter the height of the triangle:
"); double height = scanner.nextDouble();
double triangleArea = calculateArea(base, height);
System.out.println("Area of the triangle: " + triangleArea);
System.out.print("\nEnter the side of the square: ");
double side = scanner.nextDouble();
double squareArea = calculateArea(side);
System.out.println("Area of the square: " + squareArea);
System.out.print("\nEnter the length of the rectangle: ");
float length = scanner.nextFloat();
System.out.print("Enter the width of the rectangle: ");
float width = scanner.nextFloat();
double rectangleArea = calculateArea(length, width);
System.out.println("Area of the rectangle: " + rectangleArea);
}
}
Output :
11. Write a program to create a class account with the instance variables accno, name, balance
define 2 methods getdata() and display(). Define another class current and saving account
which inherits from class accounts. Provide necessary details as per the requirements.
import java.util.Scanner;
class BankAccount {
protected int accNo;
protected String name;
protected double balance;
public void getData() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Account Number: ");
accNo = scanner.nextInt();
System.out.print("Enter Name: ");
scanner.nextLine();
name = scanner.nextLine();
System.out.print("Enter Initial Balance: ");
balance = scanner.nextDouble();
}
public void display() { System.out.println("\
nAccount Details:");
System.out.println("Account Number: " + accNo);
System.out.println("Name: " + name);
System.out.println("Balance: $" + balance);
}
}
class CurrentAccount extends BankAccount {
private double overdraftLimit;
public void getAdditionalData() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Overdraft Limit: ");
overdraftLimit = scanner.nextDouble();
}
public void display() {
super.display();
System.out.println("Overdraft Limit: $" + overdraftLimit);
}
}
class SavingsAccount extends BankAccount {
private double interestRate;
public void getAdditionalData() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Interest Rate: ");
interestRate = scanner.nextDouble();
}
public void display() {
super.display();
System.out.println("Interest Rate: " + interestRate + "%");
}
}
class BankDemo {
public static void main(String[] args) {
System.out.println("Enter details for Current Account:");
CurrentAccount currentAccount = new CurrentAccount();
currentAccount.getData();
currentAccount.getAdditionalData();
currentAccount.display();
System.out.println("\nEnter details for Savings Account:");
SavingsAccount savingsAccount = new SavingsAccount();
savingsAccount.getData();
savingsAccount.getAdditionalData();
savingsAccount.display();
}
}
Output :
12. Write a program to compute area of a rectangle, square, triangle using the concept of abstract
class and overriding. Create a class shape and class rectangle and square will extend the
shape class.
import java.util.Scanner;
abstract class Shape {
public abstract double calculateArea();
}
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double calculateArea() {
return length * width;
}
}
class Square extends Shape {
private double side;
public Square(double side) {
this.side = side;
}
public double calculateArea() {
return side * side;
}
}
class Triangle extends Shape
{ private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
public double calculateArea() {
return 0.5 * base * height;
}
}
class ShapeDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter length of Rectangle: ");
double rectLength = scanner.nextDouble();
System.out.print("Enter width of Rectangle: ");
double rectWidth = scanner.nextDouble();
Shape rectangle = new Rectangle(rectLength, rectWidth);
System.out.println("Area of Rectangle: " + rectangle.calculateArea());
System.out.print("\nEnter side of Square: ");
double squareSide = scanner.nextDouble();
Shape square = new Square(squareSide);
System.out.println("Area of Square: " + square.calculateArea()); System.out.print("\
nEnter base of Triangle: ");
double triangleBase = scanner.nextDouble();
System.out.print("Enter height of Triangle: ");
double triangleHeight = scanner.nextDouble();
Shape triangle = new Triangle(triangleBase, triangleHeight);
System.out.println("Area of Triangle: " + triangle.calculateArea());
}
}
Output :
13. Write a program to create a class circle with the final instance variables PI and radius. Define 2
methods circumference() and area().
import java.util.Scanner;
class Circle {
final double PI = 3.14159;
final double radius;
public Circle(double radius) {
this.radius = radius;
}
public double circumference() {
return 2 * PI * radius;
}
public double area() {
return PI * radius * radius;
}
}
class CircleDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the radius of the circle:
"); double radius = scanner.nextDouble();
Circle circle = new Circle(radius);
System.out.println("Circumference of the circle: " + circle.circumference());
System.out.println("Area of the circle: " + circle.area());
}
}
Output :
14. Write a program to find maximum and minimum elements in an array.
import java.util.Scanner;
public class ArrayMinMax {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array:
"); int size = scanner.nextInt();
int[] array = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
System.out.print("Element " + (i + 1) + ": ");
array[i] = scanner.nextInt();
}
int max = array[0];
int min = array[0];
for (int i = 1; i < size; i++) {
if (array[i] > max) {
max = array[i];
}
if (array[i] < min) {
min = array[i];
}
}
System.out.println("\nMaximum Element: " + max);
System.out.println("Minimum Element: " + min);
}
}
Output :
15. Write a program to search an element in the array.
import java.util.Scanner;
public class ArraySearch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array:
"); int size = scanner.nextInt();
int[] array = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
System.out.print("Element " + (i + 1) + ": ");
array[i] = scanner.nextInt();
}
System.out.print("Enter the element to search:
"); int searchElement = scanner.nextInt();
int position = -1;
for (int i = 0; i < size; i++) {
if (array[i] == searchElement) {
position = i;
break;
}
}
if (position != -1) {
System.out.println("Element found at index " + position);
} else {
System.out.println("Element not found in the array");
}
}
}
Output :
16. Write a program to define an interface shape with the abstract method as area(). Define
3 class triangle, rectangle an circle which will implement the shape interface and override its
area method.
interface Shape {
double
area();
}
class Triangle implements Shape {
private double base;
private double height;