java file 1-25
java file 1-25
Write a program declaring a class Rectangle with data member’s length and breadth and
member functions Input, Output and CalcArea.
import java.util.Scanner;
class Rectangle {
float length;
float breadth;
OUTPUT:
Piyush 06917702023 1
2. Write a program to demonstrate use of method overloading to calculate area of square,
rectangle and triangle.
import java.util.Scanner;
class AreaCalculator {
Piyush 06917702023 2
OUTPUT:
Piyush 06917702023 3
3. Write a program to demonstrate the use of static variable, static method and static block
import java.util.Scanner;
class StaticDemo {
static int count;
static
{
count = 0;
}
public StaticDemo() {
count++;
}
StaticDemo.displayCount();
}
}
OUTPUT:
Piyush 06917702023 4
4. Write a program to demonstrate concept of ``this``.
class Const
{
int a,b;
@Override
public String toString()
{
return this.a + "+" + this.b;
}
Const(int a,int b)
{
this.a=a;
this.b=b;
}
Const(int a)
{
this(a,a);
}
Const()
{
this(0);
}
};
class Main
{
public static void main(String[] args)
{
Const one=new Const(10,13);
Const two=new Const(20);
Const three=new Const();
System.out.println(one);
System.out.println(two);
System.out.println(three);
}
}
OUTPUT:
Piyush 06917702023 5
5. Write a program to demonstrate multi-level and hierarchical inheritance
//Multi-level
class Animal {
void speak()
{
System.out.println("this is animal");
}
}
one.speak();
}
}
OUTPUT:
Piyush 06917702023 6
//Hierarchical
class Animal {
void speak()
{
System.out.println("Animal makes a sound");
}
}
dog.speak();
cat.speak();
}
}
OUTPUT:
Piyush 06917702023 7
6. Write a program to use super() to invoke base class constructor.
class Animal {
void speak()
{
System.out.println("Animal makes a sound");
}
}
dog.speak();
}
}
OUTPUT:
Piyush 06917702023 8
7. Write a program to demonstrate run-time polymorphism.
class Animal {
void speak()
{
System.out.println("Animal makes a sound");
}
}
dog.speak();
}
}
OUTPUT:
Piyush 06917702023 9
8. Write a program to demonstrate the concept of aggregation.
import java.util.Scanner;
class Address {
String city;
String state;
String country;
class Employee {
int id;
String name;
Address address;
class AggregationDemo {
public static void main(String[] args) {
Address address1 = new Address("New York", "NY", "USA");
Address address2 = new Address("Los Angeles", "CA", "USA");
emp1.display();
emp2.display();
}
}
Piyush 06917702023 10
OUTPUT:
Piyush 06917702023 11
9. Write a program to demonstrate the concept of abstract class with constructor and ``final``
method.
Shape(String name)
{
this.name = name;
}
@Override
void draw() {
System.out.println("Drawing a Circle");
}
}
OUTPUT:
Piyush 06917702023 12
10. Write a program to demonstrate the concept of interface when two interfaces have unique
methods and same data members
Shape(String name)
{
this.name = name;
}
@Override
void draw() {
System.out.println("Drawing a Circle");
}
}
OUTPUT:
Piyush 06917702023 13
11. Write a program to demonstrate checked exception during file handling.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
} catch (FileNotFoundException e) {
Output:
Piyush 06917702023 14
12. Write a program to demonstrate unchecked exception.
Output:
Piyush 06917702023 15
13. Write a program to demonstrate creation of multiple child threads
MyThread(String name) {
threadName = name;
}
Output:
Piyush 06917702023 16
14. Write a program to use Byte stream class to read from a text file and display the
content on the output screen
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
try {
fis = new FileInputStream("sample.txt");
int byteData;
System.out.println("File Content:");
while ((byteData = fis.read()) != -1) {
System.out.print((char) byteData);
}
} catch (FileNotFoundException e) {
System.out.println("The file was not found.");
} catch (IOException e) {
System.out.println("Error reading the file.");
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
System.out.println("Error closing the file.");
}
}
}
}
Output:
Piyush 06917702023 17
15. Write a program to demonstrate any event handling.
import java.awt.*;
import java.awt.event.*;
Button btn;
EventHandlingDemo() {
setTitle("Event Handling Example");
setSize(300, 200);
setLayout(new FlowLayout());
setVisible(true);
btn = new Button("Click Me");
btn.addActionListener(this);
add(btn);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
}
public void actionPerformed(ActionEvent e) {
System.out.println("Button was clicked!");
}
public static void main(String[] args) {
new EventHandlingDemo();
}
}
Output:
Piyush 06917702023 18
16. Create a class employee which have name, age and address of employee, include
methods getdata() and showdata(), getdata() takes the input from the user, showdata()
display the data in following format: Name: Age: Address:
import java.util.Scanner;
class Employee {
String name;
int age;
String address;
void getdata() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
name = sc.nextLine();
System.out.print("Enter age: ");
age = sc.nextInt();
sc.nextLine(); // Consume leftover newline
System.out.print("Enter address: ");
address = sc.nextLine();
}
void showdata() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Address: " + address);
}
}
Output:
Piyush 06917702023 19
17. Write a Java program to perform basic Calculator operations. Make a menu driven
program to select operation to perform (+ - * / ). Take 2 integers and perform operation
as chosen by user.
import java.util.Scanner;
int choice;
int num1, num2;
boolean exit = false;
while (!exit) {
System.out.println("\n--- Basic Calculator ---");
System.out.println("1. Addition (+)");
System.out.println("2. Subtraction (-)");
System.out.println("3. Multiplication (*)");
System.out.println("4. Division (/)");
System.out.println("5. Exit");
System.out.print("Choose an operation (1-5): ");
choice = sc.nextInt();
if (choice == 5) {
System.out.println("Exiting the calculator. Goodbye!");
exit = true;
continue;
}
switch (choice) {
case 1:
System.out.println("Result = " + (num1 + num2));
break;
case 2:
System.out.println("Result = " + (num1 - num2));
break;
case 3:
System.out.println("Result = " + (num1 * num2));
break;
case 4:
if (num2 == 0) {
System.out.println("Error: Division by zero is not allowed.");
} else {
System.out.println("Result = " + (num1 / num2));
}
break;
default:
System.out.println("Invalid choice! Please choose a valid option (1-5).");
Piyush 06917702023 20
}
}
sc.close();
}
}
Output:
Piyush 06917702023 21
18. Write a program to make use of BufferedStream to read lines from the keyboard
until 'STOP' is typed.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
try {
while (true) {
System.out.print("> ");
inputLine = reader.readLine();
if (inputLine.equalsIgnoreCase("STOP")) {
System.out.println("Exiting the program.");
break;
}
System.out.println("You entered: " + inputLine);
}
} catch (IOException e) {
System.out.println("An error occurred while reading input.");
}
}
}
Output:
Piyush 06917702023 22
19. Write a program declaring a Java class called SavingsAccount with members
``accountNumber`` and ``Balance``. Provide member functions as ``depositAmount ()``
and ``withdrawAmount ()``. If user tries to withdraw an amount greater than their
balance then throw a user-defined exception.
import java.util.Scanner;
class SavingsAccount {
private int accountNumber;
private double balance;
Piyush 06917702023 23
SavingsAccount account = new SavingsAccount(accNo, initialBal);
while (running) {
System.out.println("\n--- MENU ---");
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Show Balance");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();
try {
switch (choice) {
case 1:
System.out.print("Enter amount to deposit: ");
double dep = sc.nextDouble();
account.depositAmount(dep);
break;
case 2:
System.out.print("Enter amount to withdraw: ");
double wd = sc.nextDouble();
account.withdrawAmount(wd);
break;
case 3:
account.showBalance();
break;
case 4:
running = false;
System.out.println("Thank you for using the banking system!");
break;
default:
System.out.println("Invalid choice!");
}
} catch (InsufficientBalanceException e) {
System.out.println(e.getMessage());
}
}
sc.close();
}
}
Piyush 06917702023 24
Output:
Piyush 06917702023 25
20. Write a program creating 2 threads using Runnable interface. Print your name in
``run ()`` method of first class and "Hello Java" in ``run ()`` method of second thread.
t1.start();
t2.start();
}
}
Output:
Piyush 06917702023 26
21. Write program that uses swings to display combination of RGB using 3 scrollbars.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public RGBColorMixer() {
setTitle("RGB Color Mixer");
setSize(400, 300);
setLayout(new BorderLayout());
add(controlPanel, BorderLayout.SOUTH);
redBar.addAdjustmentListener(this);
greenBar.addAdjustmentListener(this);
blueBar.addAdjustmentListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void adjustmentValueChanged(AdjustmentEvent e) {
int r = redBar.getValue();
int g = greenBar.getValue();
int b = blueBar.getValue();
colorPanel.setBackground(new Color(r, g, b));
}
Piyush 06917702023 27
Output:
Piyush 06917702023 28
22. Write a swing application that uses atleast 5 swing controls
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
JTextField nameField;
JComboBox<String> genderBox;
JCheckBox agreeCheckBox;
JButton submitButton;
JTextArea outputArea;
public SimpleForm() {
setTitle("User Form");
setSize(400, 300);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
Piyush 06917702023 29
}
}
Output:
Piyush 06917702023 30
import javax.swing.*;
import java.awt.*;
public BorderLayoutExample() {
setTitle("BorderLayout Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
Output:
24. Write a java program to insert and update details data in the database.
Piyush 06917702023 31
//Mysql
CREATE DATABASE myskool;
USE myskool;
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(100),
grade VARCHAR(10)
);
//Java
import java.sql.*;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, username, password);
String insertQuery = "INSERT INTO students (id, name, grade) VALUES (?, ?, ?)";
PreparedStatement insertStmt = conn.prepareStatement(insertQuery);
insertStmt.setInt(1, 1);
insertStmt.setString(2, "Rahul Sharma");
insertStmt.setString(3, "8th");
insertStmt.executeUpdate();
System.out.println(" Data inserted.");
String updateQuery = "UPDATE students SET grade = ? WHERE id = ?";
PreparedStatement updateStmt = conn.prepareStatement(updateQuery);
updateStmt.setString(1, "9th");
updateStmt.setInt(2, 1);
updateStmt.executeUpdate();
System.out.println(" Data updated.");
// Close connection
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Piyush 06917702023 32
Output:
25. Write a java program to retrieve data from database and display it on GUI.
Piyush 06917702023 33
//Mysql
CREATE DATABASE schoolDB;
USE schoolDB;
//Java
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import java.util.Vector;
Piyush 06917702023 34
ResultSet rs = stmt.executeQuery(query)) {
while (rs.next()) {
Vector<Object> row = new Vector<>();
row.add(rs.getInt("student_id")); // Changed column name to student_id
row.add(rs.getString("student_name")); // Changed column name to student_name
row.add(rs.getInt("student_age")); // Changed column name to student_age
model.addRow(row);
}
table.setModel(model);
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Error loading data: " + e.getMessage());
}
}
}
Output:
Piyush 06917702023 35