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 [Link];
class Electricity {
private int units;
public Electricity(int units) {
[Link] = 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 {
[Link]("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([Link]);
[Link]("Enter the units consumed: ");
int unitsConsumed = [Link]();
Electricity electricity = new Electricity(unitsConsumed);
double totalBill = [Link]();
if (totalBill != -1) {
[Link]("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 [Link];
class Account {
private int accNo;
private String name;
private double balance;
private String accountType;
public void getData() {
Scanner scanner = new Scanner([Link]);
[Link]("Enter Account Number: ");
accNo = [Link]();
[Link]("Enter Name: ");
[Link]();
name = [Link]();
[Link]("Enter Initial Balance: ");
balance = [Link]();
[Link]("Enter Account Type: ");
accountType = [Link]();
}
public void display() {
[Link]("Account Number: " + accNo);
[Link]("Name: " + name);
[Link]("Balance: $" + balance);
[Link]("Account Type: " + accountType);
}
public void withdraw(double amount) {
if (amount > 0 && amount <=
balance) { balance -= amount;
[Link]("Withdrawal successful. Remaining balance: $" + balance);
} else {
[Link]("Invalid withdrawal amount or insufficient balance.");
}
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("Deposit successful. Updated balance: $" + balance);
} else {
[Link]("Invalid deposit amount.");
}
}
public static void main(String[] args) {
Account account = new Account();
[Link](); [Link]("\
nAccount Details:"); [Link]();
[Link](50.0);
[Link](100.0);
[Link]("\nUpdated Account
Details:"); [Link]();
}
}
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() {
[Link] = 0;
[Link] = "Unknown";
[Link] = 0;
[Link] = "Not specified";
}
public void display() {
[Link]("Roll Number: " + rollNo);
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Course: " + course);
}
public static void main(String[] args) {
Student student = new Student();
[Link]("Default Student Details:");
[Link]();
}
}
Output :
4. Write a program to perform Fibonacci series using command line arguments.
public class FibonacciSeries {
public static void main(String[] args) {
if ([Link] != 1) {
[Link]("Please provide the number of terms as a command line argument.");
return;
}
int numTerms = [Link](args[0]);
if (numTerms <= 0) {
[Link]("Please provide a positive integer as the number of terms.");
return;
}
[Link]("Fibonacci Series with " + numTerms + " terms:");
int firstTerm = 0, secondTerm = 1;
for (int i = 0; i < numTerms; i++) {
[Link](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) {
[Link] = length;
[Link] = breadth;
}
public double calculateArea() {
return length * breadth;
}
public void display() {
[Link]("Length: " + length);
[Link]("Breadth: " + breadth);
[Link]("Area: " + calculateArea());
}
public static void main(String[] args) {
Rectangle myRectangle = new Rectangle(5.0, 8.0);
[Link]("Rectangle Details:");
[Link]();
}
}
Output :
6. Write a program to calculate simple interest and amount using constructor overloading.
import [Link];
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) {
[Link] = principal;
[Link] = rate;
[Link] =
time;
}
public InterestCalculator(double principal, double rate, double time, double amount) {
this(principal, rate, time);
[Link] = amount;
}
public void calculateSimpleInterest()
{ simpleInterest = (principal * rate * time) /
100;
}
public void calculateAmount() {
amount = principal + simpleInterest;
}
public void display() {
[Link]("Principal: Rs." + principal);
[Link]("Rate: " + rate + "%");
[Link]("Time: " + time + " years");
[Link]("Simple Interest: $" + simpleInterest);
[Link]("Amount: Rs." + amount);
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter Principal amount: ");
double principal = [Link]();
[Link]("Enter Rate of interest:
"); double rate = [Link]();
[Link]("Enter Time (in years): ");
double time = [Link]();
InterestCalculator interestCalculator1 = new InterestCalculator(principal, rate, time);
[Link]();
[Link]();
[Link]("\nDetails for Interest Calculator 1:");
[Link]();
[Link]("\n ");
[Link]("Enter Amount: ");
double amount = [Link]();
InterestCalculator interestCalculator2 = new InterestCalculator(principal, rate, time, amount);
[Link]();
[Link]("\nDetails for Interest Calculator 2:");
[Link]();
}
}
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) {
[Link] = rollNo;
[Link] = name;
[Link] = age;
[Link] = course;
}
public Student(Student originalStudent) {
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
}
public void display() {
[Link]("Roll Number: " + rollNo);
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Course: " + course);
}
public static void main(String[] args) {
Student student1 = new Student(101, "John Doe", 20, "Computer Science");
[Link]("Details of Original Student:");
[Link]();
Student student2 = new Student(student1);
[Link]("\nDetails of Copied Student:");
[Link]();
}
}
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();
[Link]("Number of objects created: " + [Link]());
}
}
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 [Link];
class Student {
private int rollNo;
private String name;
private static String college;
public Student(int rollNo, String name) {
[Link] = rollNo;
[Link] = name;
}
public static void setCollege(String collegeName) {
college = collegeName;
}
public void display() {
[Link]("Roll Number: " + rollNo);
[Link]("Name: " + name);
[Link]("College: " + college);
}
}
class StudentDemo {
public static void main(String[] args)
{ [Link]("XYZ College");
Scanner scanner = new Scanner([Link]);
[Link]("Enter Roll Number: ");
int rollNo = [Link]();
[Link]("Enter Name: ");
[Link]();
String name = [Link]();
Student student = new Student(rollNo, name);
[Link]("\nStudent Details:");
[Link]();
}
}
Output :
10. Write a program to find the area of a triangle, square and rectangle using method overloading.
import [Link];
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([Link]);
[Link]("Enter the base of the triangle:
"); double base = [Link]();
[Link]("Enter the height of the triangle:
"); double height = [Link]();
double triangleArea = calculateArea(base, height);
[Link]("Area of the triangle: " + triangleArea);
[Link]("\nEnter the side of the square: ");
double side = [Link]();
double squareArea = calculateArea(side);
[Link]("Area of the square: " + squareArea);
[Link]("\nEnter the length of the rectangle: ");
float length = [Link]();
[Link]("Enter the width of the rectangle: ");
float width = [Link]();
double rectangleArea = calculateArea(length, width);
[Link]("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 [Link];
class BankAccount {
protected int accNo;
protected String name;
protected double balance;
public void getData() {
Scanner scanner = new Scanner([Link]);
[Link]("Enter Account Number: ");
accNo = [Link]();
[Link]("Enter Name: ");
[Link]();
name = [Link]();
[Link]("Enter Initial Balance: ");
balance = [Link]();
}
public void display() { [Link]("\
nAccount Details:");
[Link]("Account Number: " + accNo);
[Link]("Name: " + name);
[Link]("Balance: $" + balance);
}
}
class CurrentAccount extends BankAccount {
private double overdraftLimit;
public void getAdditionalData() {
Scanner scanner = new Scanner([Link]);
[Link]("Enter Overdraft Limit: ");
overdraftLimit = [Link]();
}
public void display() {
[Link]();
[Link]("Overdraft Limit: $" + overdraftLimit);
}
}
class SavingsAccount extends BankAccount {
private double interestRate;
public void getAdditionalData() {
Scanner scanner = new Scanner([Link]);
[Link]("Enter Interest Rate: ");
interestRate = [Link]();
}
public void display() {
[Link]();
[Link]("Interest Rate: " + interestRate + "%");
}
}
class BankDemo {
public static void main(String[] args) {
[Link]("Enter details for Current Account:");
CurrentAccount currentAccount = new CurrentAccount();
[Link]();
[Link]();
[Link]();
[Link]("\nEnter details for Savings Account:");
SavingsAccount savingsAccount = new SavingsAccount();
[Link]();
[Link]();
[Link]();
}
}
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 [Link];
abstract class Shape {
public abstract double calculateArea();
}
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
}
public double calculateArea() {
return length * width;
}
}
class Square extends Shape {
private double side;
public Square(double side) {
[Link] = side;
}
public double calculateArea() {
return side * side;
}
}
class Triangle extends Shape
{ private double base;
private double height;
public Triangle(double base, double height) {
[Link] = base;
[Link] = height;
}
public double calculateArea() {
return 0.5 * base * height;
}
}
class ShapeDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter length of Rectangle: ");
double rectLength = [Link]();
[Link]("Enter width of Rectangle: ");
double rectWidth = [Link]();
Shape rectangle = new Rectangle(rectLength, rectWidth);
[Link]("Area of Rectangle: " + [Link]());
[Link]("\nEnter side of Square: ");
double squareSide = [Link]();
Shape square = new Square(squareSide);
[Link]("Area of Square: " + [Link]()); [Link]("\
nEnter base of Triangle: ");
double triangleBase = [Link]();
[Link]("Enter height of Triangle: ");
double triangleHeight = [Link]();
Shape triangle = new Triangle(triangleBase, triangleHeight);
[Link]("Area of Triangle: " + [Link]());
}
}
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 [Link];
class Circle {
final double PI = 3.14159;
final double radius;
public Circle(double radius) {
[Link] = 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([Link]);
[Link]("Enter the radius of the circle:
"); double radius = [Link]();
Circle circle = new Circle(radius);
[Link]("Circumference of the circle: " + [Link]());
[Link]("Area of the circle: " + [Link]());
}
}
Output :
14. Write a program to find maximum and minimum elements in an array.
import [Link];
public class ArrayMinMax {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the array:
"); int size = [Link]();
int[] array = new int[size];
[Link]("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
[Link]("Element " + (i + 1) + ": ");
array[i] = [Link]();
}
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];
}
}
[Link]("\nMaximum Element: " + max);
[Link]("Minimum Element: " + min);
}
}
Output :
15. Write a program to search an element in the array.
import [Link];
public class ArraySearch {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the array:
"); int size = [Link]();
int[] array = new int[size];
[Link]("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
[Link]("Element " + (i + 1) + ": ");
array[i] = [Link]();
}
[Link]("Enter the element to search:
"); int searchElement = [Link]();
int position = -1;
for (int i = 0; i < size; i++) {
if (array[i] == searchElement) {
position = i;
break;
}
}
if (position != -1) {
[Link]("Element found at index " + position);
} else {
[Link]("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) {
[Link] = base;
[Link] = 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) {
[Link] = length;
[Link] = width;
}
public double area() {
return length * width;
}
}
class Circle implements Shape {
private double radius;
public Circle(double radius) {
[Link] = radius;
}
public double area() {
return [Link] * radius * radius;
}
}
class ShapeDemo {
public static void main(String[] args) {
Triangle triangle = new Triangle(5, 8);
[Link]("Area of Triangle: " + [Link]());
Rectangle rectangle = new Rectangle(4, 6);
[Link]("Area of Rectangle: " + [Link]());
Circle circle = new Circle(3);
[Link]("Area of Circle: " + [Link]());
}
}
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++) {
[Link]([Link]().getName() + ": Count - " + i);
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
}
class ThreadDemo {
public static void main(String[] args) {
MyThread myThread = new MyThread();
[Link]("MyThread");
[Link]();
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + ": Main Count - " + i);
try {
[Link](500);
} catch (InterruptedException e) {
[Link]();
}
}
}
}
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++) {
[Link]([Link]().getName() + ": Count - " + i);
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
}
class ThreadMethodsDemo {
public static void main(String[] args) {
MyThread myThread = new MyThread();
[Link]("MyThread");
[Link]();
[Link]("Thread ID: " + [Link]());
[Link]("Thread Name: " + [Link]());
[Link]("Thread Priority: " + [Link]());
[Link]("Is Thread Alive? " + [Link]());
try {
[Link]();
} catch (InterruptedException e) {
[Link]();
}
[Link]("Is Thread Alive? " + [Link]());
[Link](Thread.MAX_PRIORITY);
[Link]("Updated Thread Priority: " + [Link]());
}
}
Output :
19. Write a program to establish connection with the database using JDBC.
import
[Link].*; class
MysqlCon{
public static void main(String args[]){
try{
[Link]("[Link]");
Connection con=[Link]( "jdbc:mysql://localhost:3306/xyz","root","1
23");
Statement stmt=[Link]();
ResultSet rs=[Link]("select * from emp");
while([Link]())
[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
[Link]();
}
catch(Exception e){
[Link](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 [Link].*;
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 {
[Link]("[Link]");
Connection connection = [Link](JDBC_URL, USER, PASSWORD);
PreparedStatement preparedStatement =
[Link](SELECT_QUERY); ResultSet resultSet =
[Link]();
while ([Link]()) {
int rollNo = [Link]("rollno");
String name = [Link]("name");
int age = [Link]("age");
String college = [Link]("college");
[Link]("Roll No: " + rollNo);
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("College: " + college);
}
}
catch (Exception e)
{ [Link](
);
}
}
}
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 [Link].*;
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 {
[Link]("[Link]");
Connection connection = [Link](JDBC_URL, USER, PASSWORD);
Statement statement = [Link]();
[Link](CREATE_TABLE_QUERY);
insertRecords(connection);
retrieveRecords(connection);
}
catch (Exception e)
{ [Link](
);
}
}
static void insertRecords(Connection connection) throws SQLException {
PreparedStatement preparedStatement =
[Link](INSERT_RECORD_QUERY);
[Link](1, 101);
[Link](2, 50000.0);
[Link](3, "Software Engineer");
[Link]();
[Link](1, 102);
[Link](2, 60000.0);
[Link](3, "Senior Software Engineer");
[Link]();
[Link](1, 103);
[Link](2, 70000.0);
[Link](3, "Team Lead");
[Link]();
[Link]("Records inserted successfully.");
}
static void retrieveRecords(Connection connection) throws SQLException {
Statement statement = [Link]();
ResultSet resultSet = [Link](SELECT_RECORDS_QUERY);
while ([Link]()) {
int empId = [Link]("emp_id");
double salary = [Link]("salary");
String designation = [Link]("designation");
[Link]("Emp ID: " + empId);
[Link]("Salary: " + salary);
[Link]("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};
[Link]("Original Array:");
printArray(array);
bubbleSort(array); [Link]("\
nSorted Array:"); printArray(array);
}
static void bubbleSort(int[] arr) {
int n = [Link];
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) {
[Link](value + " ");
}
[Link]();
}
}
Output :
23. Write a program to demonstrate the use of executequery() methods.
import
[Link].*; class
MysqlCon{
public static void main(String args[]){
try{
[Link]("[Link]");
Connection con=[Link]( "jdbc:mysql://localhost:3306/xyz","root","1
23");
Statement stmt=[Link]();
ResultSet rs=[Link]("select * from emp");
while([Link]())
[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
[Link]();
}
catch(Exception e){
[Link](e);
}
}
}
Output :
112 Varsha Pandey