0% found this document useful (0 votes)
4 views69 pages

Java Record

The document contains multiple Java programs that demonstrate various programming concepts including interest calculation, Fibonacci series generation, prime number identification, matrix operations, class and object usage, method overloading, inheritance, user-defined exceptions, abstract classes, and package usage. Each section includes the aim of the program, source code, and a brief description of its functionality. The programs cover fundamental programming principles and provide practical examples for learners.

Uploaded by

u0370972
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
4 views69 pages

Java Record

The document contains multiple Java programs that demonstrate various programming concepts including interest calculation, Fibonacci series generation, prime number identification, matrix operations, class and object usage, method overloading, inheritance, user-defined exceptions, abstract classes, and package usage. Each section includes the aim of the program, source code, and a brief description of its functionality. The programs cover fundamental programming principles and provide practical examples for learners.

Uploaded by

u0370972
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 69

INTEREST CALCULATOR

Aim: Write a java program to calculate simple and compound interest.

Source Code
import java.util.Scanner;

public class InterestCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input principal amount


System.out.print("Enter the principal amount: ");
double principal = scanner.nextDouble();

// Input interest rate


System.out.print("Enter the annual interest rate (as a percentage): ");
double rate = scanner.nextDouble();

// Input time in years


System.out.print("Enter the time in years: ");
double time = scanner.nextDouble();

System.out.println("\nChoose an Option \n1.Simple Interest


\n2.Compound Interest");
int op = scanner.nextInt();

if (op == 1) {
double simpleInterest = (principal * rate * time) / 100;
System.out.println("\nSimple Interest: " + simpleInterest);
}
// Calculate simple interest

else {
double compoundInterest = principal * Math.pow((1 + rate / 100),
time) - principal;
System.out.println("Compound Interest: " + compoundInterest);

}
scanner.close();
}
}
Output
FIBONACCI SERIES

Aim: Write a java program to find the Fibonacci seires

Source Code
import java.util.Scanner;

public class FibonacciSeries {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the number of terms


System.out.print("Enter the number of Fibonacci terms to generate: ");
int n = scanner.nextInt();

// Display the Fibonacci series


System.out.println("\nFibonacci Series:");

// Call the method to generate and display the series


generateFibonacciSeries(n);

// Close the scanner


scanner.close();
}

// Method to generate and display Fibonacci series


static void generateFibonacciSeries(int n) {
int firstTerm = 0, secondTerm = 1;
for (int i = 0; i < n; i++) {
System.out.print(firstTerm + " ");

int nextTerm = firstTerm + secondTerm;


firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}
Output
PRIME NUMBERS

Aim: Write a java program to find the prime numbers.

Source Code
import java.util.Scanner;

public class PrimeNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input the range


System.out.print("Enter the start of the range: ");
int start = scanner.nextInt();

System.out.print("Enter the end of the range: ");


int end = scanner.nextInt();

// Find and display prime numbers in the range


System.out.println("Prime numbers in the range " + start + " to " + end +
":");
for (int num = start; num <= end; num++) {
if (isPrime(num)) {
System.out.print(num + " ");
}
}

// Close the scanner


scanner.close();
}

// Method to check if a number is prime


static boolean isPrime(int num) {
if (num < 2) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Output
MATRIX OPERATIONS

Aim: Write a java program to perform Matrix addition and Multiplication


operation.

Source Code
import java.util.*;

public class MatrixOperations {


Scanner scanner = new Scanner(System.in);

void CalculatorAddition() {
int m1[][] = new int[20][20];
int m2[][] = new int[20][20];
int row, col;
System.out.print("\nEnter the number of rows and columns of the
matrIces : ");
row = scanner.nextInt();
col = scanner.nextInt();
System.out.print("\nEnter the matrix 1 : ");
for (int i = 1; i <= row; i++) {
for (int j = 1; j <= col; j++) {
m1[i][j] = scanner.nextInt();
}
}
System.out.print("\nEnter the matrix 2 : ");
for (int i = 1; i <= row; i++) {
for (int j = 1; j <= col; j++) {
m2[i][j] = scanner.nextInt();
} }
System.out.println("\nADDITION RESULT : ");
for (int i = 1; i <= row; i++) {
for (int j = 1; j <= col; j++) {
m1[i][j] += m2[i][j];
System.out.print(m1[i][j] + "\t");
}
System.out.println();
}

void CalculatorMultiplication() {
int m1[][] = new int[20][20];
int m2[][] = new int[20][20];
int result[][] = new int[20][20];
int row1, col1, row2, col2;
System.out.print("\nEnter the number of rows and columns of the matrix
1 : ");
row1 = scanner.nextInt();
col1 = scanner.nextInt();
System.out.print("\nEnter the matrix 1 : ");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++) {
m1[i][j] = scanner.nextInt();
}
}
System.out.print("\nEnter the number of rows and columns of the matrix
2 : ");
row2 = scanner.nextInt();
col2 = scanner.nextInt();

if (col1 != row2) {
System.out.println("ERRORRRR!!!!!!!");
} else {

System.out.print("\nEnter the matrix 2 : ");


for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++) {
m2[i][j] = scanner.nextInt();
}
}
System.out.println("\nMULTIPLICATION RESULT : \n");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
for (int k = 0; k < col1; k++) {
result[i][j] += m1[i][k] * m2[k][j];
}
}
}
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
System.out.print(result[i][j] + "\t");
}
System.out.print("\n");
}

}
}
public static void main(String args[]) {
MatrixOperations mo = new MatrixOperations();
Scanner scanner = new Scanner(System.in);
int choice;

System.out.println(
"1. Matrix Addition \n2. Matrix Multiplication \n\nSelect your
choice :: ");
choice = scanner.nextInt();
if (choice == 2)
mo.CalculatorMultiplication();
else
mo.CalculatorAddition();

}
}
Output
CLASS AND OBJECT

Aim: Create a class Rectangle with member variable length and breadth, and a
member function area ().Find the area of rectangle using class and object
concepts

Source Code
import java.util.Scanner;

// Define the Rectangle class


class Rectangle {
// Member variables
double length;
double breadth;

// Member function to calculate area


double calculateArea() {
return length * breadth;
}
}

public class RectangleExample {


public static void main(String[] args) {
// Create an object of the Rectangle class
Rectangle myRectangle = new Rectangle();

// Input values for length and breadth


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the length of the rectangle: ");


myRectangle.length = scanner.nextDouble();

System.out.print("Enter the breadth of the rectangle: ");


myRectangle.breadth = scanner.nextDouble();

// Calculate and display the area using the object


double area = myRectangle.calculateArea();
System.out.println("Area of the rectangle: " + area);

// Close the scanner


scanner.close();
}
}
Output
METHOD OVERLOADING

Aim: Write a program to find the area of square and rectangle using method
overloading

Source Code
import java.util.Scanner;

public class AreaCalculator {

// Method to calculate the area of a square


static double calculateArea(double side) {
return side * side;
}

// Method to calculate the area of a rectangle


static double calculateArea(double length, double breadth) {
return length * breadth;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input for square


System.out.print("Enter the side of the square: ");
double side = scanner.nextDouble();

// Input for rectangle


System.out.print("Enter the length of the rectangle: ");
double length = scanner.nextDouble();
System.out.print("Enter the breadth of the rectangle: ");
double breadth = scanner.nextDouble();

// Calculate and display area for square


double areaSquare = calculateArea(side);
System.out.println("Area of the square: " + areaSquare);

// Calculate and display area for rectangle


double areaRectangle = calculateArea(length, breadth);
System.out.println("Area of the rectangle: " + areaRectangle);

// Close the scanner


scanner.close();
}
}
Output
SINGLE INHERITANCE

Aim: Write a program to illustrate single level inheritance with the super class
named player and subclass named CricketPlayer. The super class contains the
methods read_player and display_player().The read_player() reads the id and
name of the player and display_player displays the id and name of the player.

Source Code
import java.util.Scanner;

class Player {
int id;
String name;

void readPlayer() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter player ID: ");
id = scanner.nextInt();
System.out.print("Enter player name: ");
name = scanner.next();
}

void displayPlayer() {
System.out.println("Player Details");
System.out.println("Player ID: " + id);
System.out.println("Player Name: " + name);
}
}

class CricketPlayer extends Player {


}

public class InheritanceExample {


public static void main(String[] args) {
CricketPlayer cricketPlayer = new CricketPlayer();
cricketPlayer.readPlayer();
cricketPlayer.displayPlayer();
}
}
Output
MULTIPLE INHERITANCE

Aim: Write a program to illustrate multiple inheritances with classes named


Person, Employee, Faculty, and college. It includes an interface Bonus. Class
Person contains the two methods to read and display the person details. Class
Employee extends the class Person. Class Faculty extends Employee and
implements Bonus. Interface bonus contains a variable to assign bonus value
and use a method compute.

Source Code
import java.util.Scanner;

interface Bonus {
double bonusPercentage = 0.1;

void computeBonus();
}

class Person {
String name;
int age;

void readPersonDetails() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter person's name: ");
name = scanner.nextLine();
System.out.print("Enter person's age: ");
age = scanner.nextInt();
}

void displayPersonDetails() {
System.out.println("\n\nDetails of the Person");
System.out.println(“Person’s Name: “ + name);
System.out.println(“Person’s Age: “ + age);
}
}

class Employee extends Person {


int employeeId;

void readEmployeeDetails() {
readPersonDetails();
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter employee ID: “);
employeeId = scanner.nextInt();
}

void displayEmployeeDetails() {
displayPersonDetails();
System.out.println(“Employee ID: “ + employeeId);
}
}

class Faculty extends Employee implements Bonus {


double salary;

void readFacultyDetails() {
readEmployeeDetails();
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter faculty’s salary: “);
salary = scanner.nextDouble();

void displayFacultyDetails() {
displayEmployeeDetails();
System.out.println(“Faculty’s Salary: “ + salary);
}

@Override
public void computeBonus() {
double bonusAmount = salary * bonusPercentage;
System.out.println(“Bonus Amount: “ + bonusAmount);
}
}

class College {
public static void main(String[] args) {
Faculty faculty = new Faculty();
faculty.readFacultyDetails();
faculty.displayFacultyDetails();
faculty.computeBonus();
}
}
Output
USER DEFINED EXCEPTION

Aim: Write a program to illustrate user defined exception with class


MyException which takes a string as input and thread prints “string too large”
message when the string length is more than 10 characters.

Source Code
import java.util.Scanner;

class MyException extends Exception {


public MyException(String message) {
super(message);
}
}

public class UserDefinedExceptionExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();

// Check if the length is more than 10 characters


if (inputString.length() > 10) {
throw new MyException("String too large");
}

System.out.println("Entered string: " + inputString);


} catch (MyException e) {
System.out.println(“Exception: “ + e.getMessage());
} finally {
// Close the scanner
scanner.close();
}
}
}
Output
ABSTRACT CLASS

Aim: Create a class Figure that stores the two dimensions. Create an abstract
method area in figure. Derive two subclasses Rectangle and Triangle and
compute area

Source Code
import java.util.Scanner;
abstract class Figure {
double dimension1;
double dimension2;

abstract double area();


}
class Rectangle extends Figure {
Rectangle(double length, double width) {
dimension1 = length;
dimension2 = width;
}
@Override
double area() {
return dimension1 * dimension2;
}
}
class Triangle extends Figure {
Triangle(double base, double height) {
dimension1 = base;
dimension2 = height;
}
@Override
double area() {
return 0.5 * dimension1 * dimension2;
}
}

public class FigureExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter length of Rectangle: ");


double length = scanner.nextDouble();
System.out.print("Enter width of Rectangle: ");
double width = scanner.nextDouble();

Rectangle rectangle = new Rectangle(length, width);


System.out.println("Area of Rectangle: " + rectangle.area());

System.out.print("Enter base of Triangle: ");


double base = scanner.nextDouble();
System.out.print("Enter height of Triangle: ");
double height = scanner.nextDouble();

Triangle triangle = new Triangle(base, height);


System.out.println("Area of Triangle: " + triangle.area());

scanner.close();
}
}
Output
PACKAGES

Aim: Write a program to illustrate the use of packages through complex


number addition and subtraction.

Source Code
ComplexNumber.java
// ComplexNumber package
package complex;

// ComplexNumber class
public class ComplexNumber {
private double real;
private double imaginary;

// Constructor
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}

// Addition method
public ComplexNumber add(ComplexNumber other) {
double sumReal = this.real + other.real;
double sumImaginary = this.imaginary + other.imaginary;
return new ComplexNumber(sumReal, sumImaginary);
}

// Subtraction method
public ComplexNumber subtract(ComplexNumber other) {
double diffReal = this.real - other.real;
double diffImaginary = this.imaginary - other.imaginary;
return new ComplexNumber(diffReal, diffImaginary);
}

// Display method
public void display() {
System.out.println("Complex Number: " + real + " + " + imaginary + "i");
}
}

ComplexDemo.java

// Main program to use ComplexNumber package


import complex.ComplexNumber;
import java.util.*;

public class ComplexDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the real and imaginary part of complex number
1 : ");
double real1 = scanner.nextDouble();
double imaginary1 = scanner.nextDouble();

System.out.println("Enter the real and imaginary part of complex number


2 : ");
double real2 = scanner.nextDouble();
double imaginary2 = scanner.nextDouble();
// Create complex numbers
ComplexNumber num1 = new ComplexNumber(real1, imaginary1);
ComplexNumber num2 = new ComplexNumber(real2, imaginary2);

// Perform addition and subtraction


ComplexNumber sumResult = num1.add(num2);
ComplexNumber diffResult = num1.subtract(num2);

// Display results
num1.display();
num2.display();
System.out.println("Sum:");
sumResult.display();
System.out.println("Difference:");
diffResult.display();
}
}
Output
METHOD OVERRIDING

Aim: Write a Java program to override method greatest () for finding the
greatest of 2 numbers and 3 numbers

Source Code
class NumberOperations {
public int greatest(int num1, int num2) {
return (num1 > num2) ? num1 : num2;
}

public int greatest(int num1, int num2, int num3) {


return greatest(greatest(num1, num2), num3);
}
}

public class MethodOverridingExample {


public static void main(String[] args) {
NumberOperations operations = new NumberOperations();
int greatestOfTwo = operations.greatest(5, 8);
System.out.println("Greatest of 5 and 8: " + greatestOfTwo);
int greatestOfThree = operations.greatest(10, 3, 8);
System.out.println("Greatest of 10, 3, and 8: " + greatestOfThree);
}
}
Output
MOVING BALL

Aim: Write a program to illustrate the swing application by creating a SUBMIT


button to change the case of a given text.

Source Code
import javax.swing.*;
import java.awt.*;

public class MovingBall extends JPanel implements Runnable {


private int x, y, dx;
private Thread animator;

public MovingBall() {
x = 0; // initial x-coordinate of the ball
y = 100; // initial y-coordinate of the ball (center)
dx = 5; // speed of the ball
setBackground(Color.white);
setPreferredSize(new Dimension(400, 200)); // set preferred size of the
panel
startAnimation(); // start the animation
}

private void startAnimation() {


if (animator == null || !animator.isAlive()) {
animator = new Thread(this);
animator.start();
}
}
public void run() {
while (true) {
try {
Thread.sleep(100); // pause for a while
} catch (InterruptedException ex) {
System.out.println(ex);
}
x += dx; // move the ball
if (x > getWidth()) {
x = 0; // reset the ball to the left edge
}
repaint(); // request repainting of the panel
}
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawBall(g);
}

private void drawBall(Graphics g) {


g.setColor(Color.red);
g.fillOval(x, y, 20, 20); // draw the ball
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Moving Ball App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MovingBall());
frame.pack();
frame.setLocationRelativeTo(null); // center the frame on the screen
frame.setVisible(true);
});
}
}
Output
SWING APPLICATION

Aim: Write a program to illustrate the swing application by creating a SUBMIT


button to change the case of a given text.

Source Code
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CaseChangerApp {


public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGUI());
}

private static void createAndShowGUI() {


JFrame frame = new JFrame("Case Changer App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JTextField textField = new JTextField(20);


JButton submitButton = new JButton("Submit");
JLabel resultLabel = new JLabel("Result will be displayed here.");

submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String inputText = textField.getText();
String resultText = changeCase(inputText);
resultLabel.setText("Result: " + resultText);
}
});

JPanel panel = new JPanel();


panel.add(textField);
panel.add(submitButton);
panel.add(resultLabel);

frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}

private static String changeCase(String text) {


// Change the case of the text
return text.toUpperCase(); // You can modify this to change the case as
needed
}
}
Output
APPLET

Aim: a) Write a menu driven applet program to draw circle and triangle. The
radius of circle and sides of triangle are passed as parameters through HTML.
b) Develop an applet that receives an integer in one text field and compute the
factorial of that integer which returns in another text field when the button
“compute” clicks

Source Code for menu driven applet program


import java.awt.event.*;
import java.awt.*;
import java.applet.*;

/*<applet code=Menudriven width=400 height=400>

<param name="x1" value="100">

<param name="x2" value="180">

<param name="xa" value="100">

<param name="xb" value="250">


</applet>*/
public class Menudriven extends Applet implements ItemListener {
Label l;
Choice ch;
String n;

public void init() {


l = new Label("Select the shape:");
ch = new Choice();
ch.add("Select");
ch.add("Circle");
ch.add("Triangle");
add(l);
add(ch);
ch.addItemListener(this);
setBackground(Color.green);
}

public void itemStateChanged(ItemEvent ie) {


repaint();
}

public void paint(Graphics g) {


n = ch.getSelectedItem();
if (n.equals("Circle")) {
int a = Integer.parseInt(getParameter("x1"));
int b = Integer.parseInt(getParameter("x2"));
g.drawOval(a, b, b, b);
}
if (n.equals("Triangle")) {
int a = Integer.parseInt(getParameter("xa"));
int b = Integer.parseInt(getParameter("xb"));
int c = Integer.parseInt(getParameter("x1"));
g.drawLine(a, a, b, b);
g.drawLine(c, b, b, b);
g.drawLine(a, a, c, b);
}
}}
Output
Source Code for computing factorial of an integer
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
/*<applet code="Factorial" width=600 height=200> </applet> */
public class Factorial extends Applet implements ActionListener
{
Label l1,l2;
TextField t1,t2;
Button b1,b2;
public void init()
{
l1=new Label("Enter an integer value");
l2=new Label("Result:");
t1=new TextField(10);
t2=new TextField(10);
b1=new Button("Compute");
b2=new Button("Clear");
add(l1);
add(t1);
add(b1);
add(b2);
add(l2);
add(t2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
int n=Integer.parseInt(t1.getText());
int fact=1;
if(ae.getSource()==b1)
{
if(n==0||n==1)
{
fact=1;
t2.setText(String.valueOf(fact));
}
else
{
for(int i=1;i<=n;i++)
fact=fact*i;
}
t2.setText(String.valueOf(fact));
}
else if(ae.getSource()==b2)
{
t1.setText("");
t2.setText("");
}
}
}
Output
STRING SORTING

Aim: Write a java program to sort the given strings.

Source Code
import java.util.Arrays;
import java.util.Scanner;

public class StringSorting {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Prompt the user for the number of strings


System.out.print("Enter the number of strings: ");
int numStrings = scanner.nextInt();
scanner.nextLine(); // Consume the newline character

// Read strings from the user


String[] stringArray = new String[numStrings];
for (int i = 0; i < numStrings; i++) {
System.out.print("Enter string " + (i + 1) + ": ");
stringArray[i] = scanner.nextLine();
}

// Sorting the array


Arrays.sort(stringArray);

// Displaying the sorted array


System.out.println("Sorted Strings:");
for (String str : stringArray) {
System.out.println(str);
}

// Close the scanner


scanner.close();
}
}
Output
FILE

Aim: Write a java program that displays the number of characters, lines and
words in a text file.

Source Code
FileStatistics.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileStatistics {


public static void main(String[] args) {
// Replace "yourFileName.txt" with the actual path and name of your text
file
String fileName = "hello.txt";

try {
BufferedReader reader = new BufferedReader(new
FileReader(fileName));

int charCount = 0;
int wordCount = 0;
int lineCount = 0;

String line;
while ((line = reader.readLine()) != null) {
charCount += line.length();
wordCount += countWords(line);
lineCount++;
}

reader.close();

System.out.println("Number of Characters: " + charCount);


System.out.println("Number of Words: " + wordCount);
System.out.println("Number of Lines: " + lineCount);

} catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage());
}
}

private static int countWords(String line) {


String[] words = line.split("\\s+");
return words.length;
}
}

hello.txt
hello sangeetha
how are you?
hope you are doing well.
bye.
Output
THREAD

Aim: Write a program to create three threads in java. First thread displays
“GoodMorning” in every single second, the second thread displays “Hello” in
every 2 seconds and the third thread displays “Welcome” in every 3 seconds.

Source Code
class DisplayMessage extends Thread {
private String message;
private int interval;

public DisplayMessage(String message, int interval) {


this.message = message;
this.interval = interval;
}

public void run() {


while (true) {
System.out.println(message);
try {
Thread.sleep(interval * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class MultiThreadExample {


public static void main(String[] args) {
DisplayMessage thread1 = new DisplayMessage(“GoodMorning”, 1);
DisplayMessage thread2 = new DisplayMessage(“Hello”, 2);
DisplayMessage thread3 = new DisplayMessage(“Welcome”, 3);

thread1.start();
thread2.start();
thread3.start();
}
}
Output
MOUSE EVENTS

Aim: Write a program to implement the Mouse events in java.

Source Code
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

public class MouseEventExample extends JFrame {


private JLabel statusLabel;

public MouseEventExample() {
setTitle("Mouse Events Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

statusLabel = new JLabel("Move the mouse");


add(statusLabel, BorderLayout.SOUTH);

addMouseListener(new MyMouseListener());
addMouseMotionListener(new MyMouseMotionListener());
}

private class MyMouseListener implements MouseListener {


@Override
public void mouseClicked(MouseEvent e) {
statusLabel.setText("Mouse Clicked at (" + e.getX() + ", " + e.getY() +
")");
}

@Override
public void mousePressed(MouseEvent e) {
statusLabel.setText("Mouse Pressed at (" + e.getX() + ", " + e.getY() +
")");
}

@Override
public void mouseReleased(MouseEvent e) {
statusLabel.setText("Mouse Released at (" + e.getX() + ", " + e.getY() +
")");
}

@Override
public void mouseEntered(MouseEvent e) {
statusLabel.setText("Mouse Entered");
}

@Override
public void mouseExited(MouseEvent e) {
statusLabel.setText("Mouse Exited");
}
}

private class MyMouseMotionListener implements MouseMotionListener {


@Override
public void mouseMoved(MouseEvent e) {
statusLabel.setText("Mouse Moved at (" + e.getX() + ", " + e.getY() +
")");

@Override
public void mouseDragged(MouseEvent e) {
statusLabel.setText("Mouse Dragged at (" + e.getX() + ", " + e.getY() +
")");
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
MouseEventExample example = new MouseEventExample();
example.setVisible(true);
});
}
}
Output
DATABASE

Aim: Create a table student which contains roll_no, name, and marks of n
subjects with 5 records of data in Minimum. Write a java program to read data
from the table and displaying roll_no, name, total_marks and percentage of
each student
Source Code
import java.sql.*;
import java.util.*;
import java.io.*;
import java.lang.*;

public class Student {


static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/karthika";
static final String USER = "root";
static final String PASS = "root123";

public static void main(String args[])


{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String name=null;
int num,m1,m2,m3;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.print("\n Connecting to database");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("SUCCESS !");
for(int i=0;i<2;i++)
{
System.out.print("Enter Number : ");
num=Integer.parseInt(br.readLine());
System.out.print("Enter Name :");
name=br.readLine();
System.out.print("Enter Mark1 :");
m1=Integer.parseInt(br.readLine());
System.out.print("Enter Mark2 :");
m2=Integer.parseInt(br.readLine());
System.out.print("Enter Mark3 :");
m3=Integer.parseInt(br.readLine());
stmt=conn.createStatement();
String sql="INSERT INTO
student_new(number,name,mark1,mark2,mark3)
VALUES("+num+",'"+name+"',"+m1+","+m2+","+m3+")";
stmt.executeUpdate(sql);
}

String sql="UPDATE student_new SET total=mark1+mark2+mark3";


stmt.executeUpdate(sql);
sql="UPDATE student_new SET percentage=total/3";
stmt.executeUpdate(sql);
sql="SELECT * FROM student_new";
rs=stmt.executeQuery(sql);
System.out.println("Student Details\n");
System.out.println("Number\tName\tMark1\tMark2\tMark3\tTotal
Marks\tPercentage");
System.out.println("---------------------------------------------------------");
while(rs.next())
{
System.out.print(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getInt(3)+"
\t"+rs.getInt(4)+"\t"+rs.getInt(5)+"\t\t");
System.out.println(rs.getInt(6)+"\t\t"+rs.getInt(7));
}
System.out.println("SUCCESS !");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
try
{
if(stmt!=null)
conn.close();
}
catch(SQLException se)
{
}
}
}
}
Output

You might also like