1) Method overloading and method overriding
// Method Overloading Example
class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
// Method to add two double numbers
public double add(double a, double b) {
return a + b;
}
}
// Method Overriding Example
class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
public class Main {
public static void main(String[] args) {
// Method Overloading
Calculator calculator = new Calculator();
int sum1 = calculator.add(5, 7);
double sum2 = calculator.add(3.5, 2.8);
System.out.println("Sum of integers: " + sum1);
System.out.println("Sum of doubles: " + sum2);
// Method Overriding
Shape shape = new Shape();
Shape circle = new Circle();
shape.draw(); // Calls the draw method in the Shape class
circle.draw(); // Calls the overridden draw method in the Circle class
}
}
2) Write a java program to display monthly and annual
interest on Rs.2000 and Rs.3000 respectively. Use
static variable and static function
class InterestCalculator {
static double principal; // Static variable to store the principal
amount
static double annualInterestRate; // Static variable to store the
annual interest rate
// Static method to calculate and display monthly interest
static void calculateAndDisplayMonthlyInterest() {
double monthlyInterest = (principal * annualInterestRate) / 12.0 /
100.0;
System.out.println("Monthly Interest on Rs." + principal + " at " +
annualInterestRate + "% annual interest rate: Rs." + monthlyInterest);
}
// Static method to calculate and display annual interest
static void calculateAndDisplayAnnualInterest() {
double annualInterest = (principal * annualInterestRate) / 100.0;
System.out.println("Annual Interest on Rs." + principal + " at " +
annualInterestRate + "% annual interest rate: Rs." + annualInterest);
}
}
public class Main {
public static void main(String[] args) {
InterestCalculator.principal = 2000; // Set the principal amount
InterestCalculator.annualInterestRate = 5.0; // Set the annual
interest rate (5% in this example)
// Calculate and display monthly and annual interest for Rs. 2000
InterestCalculator.calculateAndDisplayMonthlyInterest();
InterestCalculator.calculateAndDisplayAnnualInterest();
InterestCalculator.principal = 3000; // Set a different principal
amount
InterestCalculator.annualInterestRate = 6.0; // Set a different
annual interest rate (6% in this example)
// Calculate and display monthly and annual interest for Rs. 3000
InterestCalculator.calculateAndDisplayMonthlyInterest();
InterestCalculator.calculateAndDisplayAnnualInterest();
}
}
3) Write a java program to demonstrate use of interface
// Define an interface named "Shape"
interface Shape {
double getArea(); // Interface method to calculate the area
double getPerimeter(); // Interface method to calculate the perimeter
}
// Create a class "Circle" that implements the "Shape" interface
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
// Create a class "Rectangle" that implements the "Shape" interface
class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double getArea() {
return length * width;
}
@Override
public double getPerimeter() {
return 2 * (length + width);
}
}
public class Main {
public static void main(String[] args) {
// Create instances of Circle and Rectangle
Circle circle = new Circle(5.0);
Rectangle rectangle = new Rectangle(4.0, 6.0);
// Use the interface methods to calculate and display area and
perimeter
System.out.println("Circle Area: " + circle.getArea());
System.out.println("Circle Perimeter: " + circle.getPerimeter());
System.out.println("Rectangle Area: " + rectangle.getArea());
System.out.println("Rectangle Perimeter: " +
rectangle.getPerimeter());
}
}
4) Write a java program to use abstract class.
// Define an abstract class named "Shape"
abstract class Shape {
// Abstract methods to calculate area and perimeter
public abstract double getArea();
public abstract double getPerimeter();
// Concrete method
public void displayInfo() {
System.out.println("This is a shape.");
}
}
// Create a concrete subclass "Circle" that extends the "Shape"
abstract class
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
// Additional method specific to Circle
public void displayCircleInfo() {
System.out.println("This is a circle.");
}
}
public class Main {
public static void main(String[] args) {
// Create an instance of the Circle class
Circle circle = new Circle(5.0);
// Use the abstract class methods
System.out.println("Circle Area: " + circle.getArea());
System.out.println("Circle Perimeter: " + circle.getPerimeter());
// Use the concrete method of the abstract class
circle.displayInfo();
// Use the method specific to the Circle class
circle.displayCircleInfo();
}
}
5) Develop a package and use it in another program
package mypackage;
public class MyClass {
public void displayMessage() {
System.out.println("Hello from MyClass in the mypackage
package!");
}
}
import mypackage.MyClass; // Import the MyClass class from the
mypackage package
public class MainProgram {
public static void main(String[] args) {
MyClass myObj = new MyClass(); // Create an instance of
MyClass
myObj.displayMessage(); // Use the MyClass method
}
}
6:-Write a java program for Exception handling.(try
and catch)
public class ExceptionHandlingErrorExample {
public static void main(String[] args) {
try {
int result = divideByZero();
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.err.println("An error occurred: " +
e.getMessage());
}
}
public static int divideByZero() {
int numerator = 10;
int denominator = 0;
return numerator / denominator; // This will cause an
ArithmeticException
}
}
7:-Write a java program for Exception handling.(try
and catch and throws)
import java.io.IOException;
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class A {
public static void main(String[] args) {
try {
// Simulate a custom exception using "throw"
int age = 15;
if (age < 18) {
throw new CustomException("You must be at
least 18 years old.");
}
// Simulate an I/O exception using "throws"
// This is a checked exception that should be
declared in the method signature
throw new IOException("Simulated I/O exception");
} catch (CustomException e) {
System.err.println("Custom Exception: " +
e.getMessage());
} catch (IOException e) {
System.err.println("I/O Exception: " +
e.getMessage());
} finally {
System.out.println("This block is always
executed.");
}
}
}
8)Create a file and perform operation on that file.
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
public class FileOperationsExample {
public static void main(String[] args) {
try {
// Create a file named "example.txt" in the current directory
File file = new File("example.txt");
// Check if the file already exists
if (file.exists()) {
System.out.println("File already exists.");
} else {
// Create a new file
file.createNewFile();
System.out.println("File created: " + file.getName());
}
// Write data to the file
FileWriter writer = new FileWriter(file);
writer.write("Hello, this is a sample text written to the file.");
writer.close();
System.out.println("Data written to the file.");
// Read and display data from the file
FileReader reader = new FileReader(file);
int character;
System.out.println("Data read from the file:");
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
System.err.println("An error occurred: " + e.getMessage());
}
}
}
10:-Design home page using AWT swing
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Myframe extends JFrame{
JTextField t1,t2;
JButton b1;
JLabel l1,l2,l3;
Myframe(){
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
l1 = new JLabel("Login Form");
l1.setFont(new Font("Time New Roman",Font.BOLD,30));
l1.setForeground(Color.RED);
l1.setBounds(130,10,300,30);
add(l1);
t1 = new JTextField(60);
t2 = new JPasswordField(60);
b1 = new JButton("Login");
t1.setBounds(100,60,120,30);
t2.setBounds(100,100,120,30);
b1.setBounds(120,140,80,30);
add(t1);
add(t2);
add(b1);
}
}
class Loginform{
public static void main(String args[]){
Myframe f = new Myframe();
f.setTitle("LoginForm");
f.setVisible(true);
f.setSize(400,300);
}
10) Develop a swing GUI base standard calculator
program. Using event handling, layout of swing
package
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
class calculator extends JFrame implements ActionListener {
static JFrame f;
static JTextField l;
String s0, s1, s2;
calculator()
{
s0 = s1 = s2 = "";
}
public static void main(String args[])
{
f = new JFrame("calculator");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassNa
me());
}
catch (Exception e) {
System.err.println(e.getMessage());
}
calculator c = new calculator();
l = new JTextField(16);
l.setEditable(false);
JButton b0, b1, b2, b3, b4, b5, b6, b7, b8,
b9, ba, bs, bd, bm, be, beq, beq1;
b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");
beq1 = new JButton("=");
ba = new JButton("+");
bs = new JButton("-");
bd = new JButton("/");
bm = new JButton("*");
beq = new JButton("C");
be = new JButton(".");
JPanel p = new JPanel();
bm.addActionListener(c);
bd.addActionListener(c);
bs.addActionListener(c);
ba.addActionListener(c);
b9.addActionListener(c);
b8.addActionListener(c);
b7.addActionListener(c);
b6.addActionListener(c);
b5.addActionListener(c);
b4.addActionListener(c);
b3.addActionListener(c);
b2.addActionListener(c);
b1.addActionListener(c);
b0.addActionListener(c);
be.addActionListener(c);
beq.addActionListener(c);
beq1.addActionListener(c);
p.add(l);
p.add(ba);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bs);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(bm);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);
p.setBackground(Color.blue);
f.add(p);
f.setSize(200, 220);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') ||
s.charAt(0) == '.') {
// if operand is present then add to second no
if (!s1.equals(""))
s2 = s2 + s;
else
s0 = s0 + s;
l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == 'C') {
// clear the one letter
s0 = s1 = s2 = "";
l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == '=') {
double te;
if (s1.equals("+"))
te = (Double.parseDouble(s0) +
Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) -
Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) /
Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) *
Double.parseDouble(s2));
l.setText(s0 + s1 + s2 + "=" + te);
s0 = Double.toString(te);
s1 = s2 = "";
}
else {
if (s1.equals("") || s2.equals(""))
s1 = s;
else {
double te;
if (s1.equals("+"))
te = (Double.parseDouble(s0) +
Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) -
Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) /
Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) *
Double.parseDouble(s2));
s0 = Double.toString(te);
s1 = s;
s2 = "";
}
l.setText(s0 + s1 + s2);
}
}
}
11) Create a stopwatch using swing GUI
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class StopwatchApp extends JFrame {
private JLabel timeLabel;
private JButton startButton;
private JButton stopButton;
private JButton lapButton;
private JTextArea lapTextArea;
private JScrollPane scrollPane;
private long startTime;
private long elapsedTime;
private boolean isRunning;
private boolean isPaused;
private Timer timer;
public StopwatchApp() {
setTitle("Stopwatch with Lap Counting");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initUI();
setLocationRelativeTo(null);
setVisible(true);
}
private void initUI() {
timeLabel = new JLabel("00:00:00.000");
timeLabel.setFont(new Font("Arial", Font.PLAIN, 40));
timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
startButton = new JButton("Start");
stopButton = new JButton("Stop");
lapButton = new JButton("Lap");
lapTextArea = new JTextArea(10, 20);
scrollPane = new JScrollPane(lapTextArea);
lapTextArea.setEditable(false);
startButton.addActionListener(new
ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!isRunning) {
start();
startButton.setEnabled(false);
lapButton.setEnabled(true);
stopButton.setEnabled(true);
}
}
});
stopButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
if (isRunning) {
stop();
startButton.setEnabled(true);
lapButton.setEnabled(false);
stopButton.setEnabled(false);
}
}
});
lapButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (isRunning) {
lap();
}
}
});
JPanel buttonPanel = new JPanel(new
GridLayout(1, 3));
buttonPanel.add(startButton);
buttonPanel.add(stopButton);
buttonPanel.add(lapButton);
JPanel lapPanel = new JPanel(new BorderLayout());
lapPanel.add(new JLabel("Lap Times:"),
BorderLayout.NORTH);
lapPanel.add(scrollPane, BorderLayout.CENTER);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(timeLabel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.CENTER);
mainPanel.add(lapPanel, BorderLayout.SOUTH);
add(mainPanel);
}
private void start() {
if (!isPaused) {
startTime = System.currentTimeMillis() -
elapsedTime;
} else {
startTime = System.currentTimeMillis();
isPaused = false;
}
isRunning = true;
timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
elapsedTime = System.currentTimeMillis() -
startTime;
updateDisplay(elapsedTime);
}
});
timer.start();
}
private void stop() {
timer.stop();
isRunning = false;
}
private void lap() {
String lapTime = formatTime(elapsedTime);
lapTextArea.append(lapTime + "\n");
lapTextArea.setCaretPosition(lapTextArea.getDocument().getLen
gth());
}
private void updateDisplay(long time) {
String formattedTime = formatTime(time);
timeLabel.setText(formattedTime);
}
private String formatTime(long time) {
long millis = time % 1000;
long seconds = (time / 1000) % 60;
long minutes = (time / (1000 * 60)) % 60;
long hours = (time / (1000 * 60 * 60)) % 24;
return String.format("%02d:%02d:%02d.%03d", hours,
minutes, seconds, millis);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new StopwatchApp();
}
});
}
}