You are on page 1of 28

1.

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;

public Triangle(double base, double height) {


this.base = base;
this.height = height;
}
public double area() {
return 0.5 * base * height;
}
}
class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double area() {
return length * width;
}
}
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double area() {
return Math.PI * radius * radius;
}
}
class ShapeDemo {
public static void main(String[] args) {
Triangle triangle = new Triangle(5, 8);
System.out.println("Area of Triangle: " + triangle.area());
Rectangle rectangle = new Rectangle(4, 6);
System.out.println("Area of Rectangle: " + rectangle.area());
Circle circle = new Circle(3);
System.out.println("Area of Circle: " + circle.area());
}
}
Output :
17. Write a program to create a class thread and demonstrate its working.
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ": Count - " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class ThreadDemo {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.setName("MyThread");
myThread.start();
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ": Main Count - " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Output :
18. Write a program to implement methods in the thread class.
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ": Count - " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class ThreadMethodsDemo {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.setName("MyThread");
myThread.start();
System.out.println("Thread ID: " + myThread.getId());
System.out.println("Thread Name: " + myThread.getName());
System.out.println("Thread Priority: " + myThread.getPriority());
System.out.println("Is Thread Alive? " + myThread.isAlive());
try {
myThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Is Thread Alive? " + myThread.isAlive());
myThread.setPriority(Thread.MAX_PRIORITY);
System.out.println("Updated Thread Priority: " + myThread.getPriority());
}
}
Output :
19. Write a program to establish connection with the database using JDBC.
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/xyz","root","1
23");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Output :
112 Varsha Pandey
20. Write a program to retrieve records from student table using JDBC create a database in mysql
with the table student and fields as rollno, name, age and college.
import java.sql.*;
class RetrieveStudentRecords {
String JDBC_URL = "jdbc:mysql://localhost:3306/xyz";
String USER = "root";
String PASSWORD = "123";
String SELECT_QUERY = "SELECT rollno, name, age, college FROM student";
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
PreparedStatement preparedStatement = connection.prepareStatement(SELECT_QUERY);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
int rollNo = resultSet.getInt("rollno");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
String college = resultSet.getString("college");
System.out.println("Roll No: " + rollNo);
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("College: " + college);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Output :
Roll No: 112
Name: Varsha Pandey
Age: 21
College: Graphic Era Hill University
Roll No: 45
Name: Priyanka
Age: 19
College: Graphic Era Hill University
21. Write a program to create a database emp with the table employee attributes emp_id, salary,
designation. Establish a connection with the database and retrieve the records.
import java.sql.*;
class EmployeeDatabaseExample {
String JDBC_URL = "jdbc:mysql://localhost:3306/emp";
String USER = "root";
String PASSWORD = "123";
String CREATE_TABLE_QUERY = "CREATE TABLE IF NOT EXISTS employee (emp_id INT PRIMARY
KEY, salary DOUBLE, designation VARCHAR(255))";
String INSERT_RECORD_QUERY = "INSERT INTO employee (emp_id, salary, designation) VALUES (?,
?, ?)";
String SELECT_RECORDS_QUERY = "SELECT * FROM employee";
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
Statement statement = connection.createStatement();
statement.executeUpdate(CREATE_TABLE_QUERY);
insertRecords(connection);
retrieveRecords(connection);
}
catch (Exception e) {
e.printStackTrace();
}
}
static void insertRecords(Connection connection) throws SQLException {
PreparedStatement preparedStatement =
connection.prepareStatement(INSERT_RECORD_QUERY);
preparedStatement.setInt(1, 101);
preparedStatement.setDouble(2, 50000.0);
preparedStatement.setString(3, "Software Engineer");
preparedStatement.executeUpdate();
preparedStatement.setInt(1, 102);
preparedStatement.setDouble(2, 60000.0);
preparedStatement.setString(3, "Senior Software Engineer");
preparedStatement.executeUpdate();
preparedStatement.setInt(1, 103);
preparedStatement.setDouble(2, 70000.0);
preparedStatement.setString(3, "Team Lead");
preparedStatement.executeUpdate();
System.out.println("Records inserted successfully.");
}
static void retrieveRecords(Connection connection) throws SQLException {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(SELECT_RECORDS_QUERY);
while (resultSet.next()) {
int empId = resultSet.getInt("emp_id");
double salary = resultSet.getDouble("salary");
String designation = resultSet.getString("designation");
System.out.println("Emp ID: " + empId);
System.out.println("Salary: " + salary);
System.out.println("Designation: " + designation);
}
}
}
Output :
Records inserted successfully
Emp ID: 101
Salary: 50000.0
Designation: Software Engineer
Emp ID: 102
Salary: 60000.0
Designation: Senior Software Engineer
Emp ID: 103
Salary: 70000.0
Designation: Team Lead
22. Write a program to implement bubble sort.
class BubbleSort {
public static void main(String[] args) {
int[] array = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Original Array:");
printArray(array);
bubbleSort(array);
System.out.println("\nSorted Array:");
printArray(array);
}
static void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
if (!swapped) {
break;
}
}
}
static void printArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}
}
Output :
23. Write a program to demonstrate the use of executequery() methods.
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/xyz","root","1
23");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Output :
112 Varsha Pandey

You might also like