Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Java Practical

Bscit java practical

Uploaded by

Vivek Naik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Java Practical

Bscit java practical

Uploaded by

Vivek Naik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Write a program to Demonstrate use of user defined Packages

Source Code:
// Define package
package mypackage;
public class MathOperations {
// Method to add two numbers
public int add(int a, int b) {
return a + b;
}
// Method to subtract two numbers
public int subtract(int a, int b) {
return a - b;
}
}
Use of mypackage in another class
// Import the user-defined package
import mypackage.MathOperations;
public class Main {
public static void main(String[] args) {
// Create an object of the MathOperations class
MathOperations math = new MathOperations();
// Call methods from the MathOperations class
int sum = math.add(10, 5);
int difference = math.subtract(10, 5);
// Display the results
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
}
Aim : Write a programs to demonstrate the use of Adapter Class in
Event Handling
Source Code:
// Import required packages
import java.awt.event.*;
import javax.swing.*;
public class MouseAdapterExample {
public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("MouseAdapter Example");

// Create a label
JLabel label = new JLabel();
label.setBounds(100, 100, 200, 50);
label.setText("Mouse over me");
// Add MouseAdapter to handle mouse events
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked!");
}
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entered the label!");
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("Mouse exited the label!");
}
});
// Add label to frame
frame.add(label);

// Set frame properties


frame.setSize(400, 400);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Write a programs to demonstrate the use of Anonymous Inner
Class in Event Handling
Source Code:
// Import required packages
import java.awt.event.*;
import javax.swing.*;
public class AnonymousInnerClassKeyEventExample {
public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("Anonymous Inner Class Key Event Example");
// Create a text field
JTextField textField = new JTextField();
textField.setBounds(100, 100, 200, 50);
// Add KeyListener using an anonymous inner class
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed: " + e.getKeyChar());
}
});
// Add text field to frame
frame.add(textField);
// Set frame properties
frame.setSize(400, 400);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Write a program to raise built-in exceptions and raise them as per the
requirements.
Source Code:
public class ExceptionBuildIn {
public static void main(String[] args) {
try {
// Example of ArithmeticException
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: " + e.getMessage());
}
try {
// Example of NullPointerException
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("NullPointerException: " + e.getMessage());
}
try {
// Example of ArrayIndexOutOfBoundsException
int[] arr = new int[5];
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException: " + e.getMessage());
}
try {
// Example of IllegalArgumentException
throw new IllegalArgumentException("This is an illegal argument.");
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException: " + e.getMessage());
}
}
}
Write a program to define user defined exceptions and raise them as per the
requirements.
Source Code:
// Custom Exception Class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
// Main Class
public class UserDefinedException {
public static void main(String[] args) {
try {
validateAge(15);
} catch (InvalidAgeException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older.");
} else {
System.out.println("Age is valid.");
}
}
}
Write a java application to demonstrate 5 bouncing balls of different colors
using
threads.
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
class Ball {
private int x, y;
private int diameter;
private Color color;
private int xSpeed, ySpeed;
public Ball(int diameter, Color color) {
this.diameter = diameter;
this.color = color;
Random random = new Random();
this.x = random.nextInt(800 - diameter);
this.y = random.nextInt(600 - diameter);
this.xSpeed = random.nextInt(5) + 1;
this.ySpeed = random.nextInt(5) + 1;
}
public void update() {
x += xSpeed;
y += ySpeed;
if (x < 0 || x > 800 - diameter) {
xSpeed = -xSpeed;
}
if (y < 0 || y > 600 - diameter) {
ySpeed = -ySpeed;
}
}
public void draw(Graphics g) {
g.setColor(color);
g.fillOval(x, y, diameter, diameter);
}
}
class BouncingBallsPanel extends JPanel implements ActionListener {
private Ball[] balls;
private Timer timer;
public BouncingBallsPanel() {
balls = new Ball[5];
Color[] colors = {Color.MAGENTA, Color.RED, Color.BLUE, Color.YELLOW,
Color.BLACK};
for (int i = 0; i < balls.length; i++) {
balls[i] = new Ball(30, colors[i]);
}
timer = new Timer(20, this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Ball ball : balls) {
ball.update();
ball.draw(g);
}
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
}
public class BouncingBalls {
public static void main(String[] args) {
JFrame frame = new JFrame("Bouncing Balls");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new BouncingBallsPanel());
frame.pack();
frame.setVisible(true);
}
}
Write programs for the Flow Layout
Source Code:
import java.awt.*;
import javax.swing.*;
public class FlowLayoutExample {
JFrame frame;
FlowLayoutExample() {
frame = new JFrame();
// Creating buttons
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
// Adding buttons to the frame
frame.add(b1);
frame.add(b2);
frame.add(b3);
frame.add(b4);
frame.add(b5);
// Setting flow layout
frame.setLayout(new FlowLayout());
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
new FlowLayoutExample();
}
}
Write programs for the Grid Layout
Source code:
import java.awt.*;
import javax.swing.*;
public class GridLayoutExample {
JFrame frame;
GridLayoutExample() {
frame = new JFrame();
// Creating buttons
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
// Adding buttons to the frame
frame.add(b1);
frame.add(b2);
frame.add(b3);
frame.add(b4);
frame.add(b5);
frame.add(b6);
fame.add(b7);
frame.add(b8);
frame.add(b9);
// Setting grid layout with 3 rows and 3 columns
frame.setLayout(new GridLayout(3, 3));
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
new GridLayoutExample();
}
}
Write programs for the Border Layout
Source code:
import java.awt.*;
import javax.swing.*;
public class BorderLayoutExample {
JFrame frame;
BorderLayoutExample() {
frame = new JFrame();
// Creating buttons
JButton b1 = new JButton("North");
JButton b2 = new JButton("South");
JButton b3 = new JButton("East");
JButton b4 = new JButton("West");
JButton b5 = new JButton("Center");
// Adding buttons to the frame
frame.add(b1, BorderLayout.NORTH);
frame.add(b2, BorderLayout.SOUTH);
frame.add(b3, BorderLayout.EAST);
frame.add(b4, BorderLayout.WEST);
frame.add(b5, BorderLayout.CENTER);
// Setting border layout
frame.setLayout(new BorderLayout());
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
new BorderLayoutExample();
}
}
Create a swing application that randomly changes color on button click.
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class RandomColorButton extends JFrame
{
private JButton button;
public RandomColorButton() {
setLayout(new FlowLayout());
button = new JButton("Click me!");
add(button);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
changeColor();
}
});
setSize(300, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private void changeColor() {
Random random = new Random();
int red = random.nextInt(256);
int green = random.nextInt(256);
int blue = random.nextInt(256);
Color color = new Color(red, green, blue);
button.setBackground(color);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new RandomColorButton();
}
});
}
}
Create a Swing application to demonstrate use of TextArea using scrollpane to
show contest of text file in textarea selected using file chooser.
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class TextAreaApp extends JFrame {
private JTextArea textArea;
public TextAreaApp() {
setLayout(new BorderLayout());
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
JButton button = new JButton("Select File");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int result = fileChooser.showOpenDialog(TextAreaApp.this);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
try {
BufferedReader reader = new BufferedReader(new FileReader(selectedFile));
String line;
StringBuilder text = new StringBuilder();
while ((line = reader.readLine()) != null) {
text.append(line).append("\n");
}
reader.close();
textArea.setText(text.toString());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
add(button, BorderLayout.NORTH);
textArea = new JTextArea(20, 40);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane, BorderLayout.CENTER);
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TextAreaApp();
}
});
}
}
Write a programs to demonstrate the Action Event
Source Code:
// Import required packages
import java.awt.event.*;
import javax.swing.*;
public class ActionEventExample {
public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("ActionEvent Example");

// Create a button
JButton button = new JButton("Click Me");

// Set button properties


button.setBounds(100, 100, 150, 50);

// Add ActionListener to handle action event


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button was clicked!");
}
});
// Add button to frame
frame.add(button);

// Set frame properties


frame.setSize(400, 400);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Write a programs to demonstrate the Key Event
Source Code:
// Import required packages
import java.awt.event.*;
import javax.swing.*;
public class KeyEventExample {
public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("KeyEvent Example");
// Create a text field
JTextField textField = new JTextField();

// Set text field properties


textField.setBounds(100, 100, 200, 50);

// Add KeyListener to handle key events


textField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed: " + e.getKeyChar());
}
});

// Add text field to frame


frame.add(textField);

// Set frame properties


frame.setSize(400, 400);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Write a programs to demonstrate the selection Event
Source Code:
// Import required packages
import java.awt.event.*;
import javax.swing.*;
public class ItemEventExample {
public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("ItemEvent Example");
// Create a combo box
String[] options = {"Option 1", "Option 2", "Option 3"};
JComboBox<String> comboBox = new JComboBox<>(options);

// Set combo box properties


comboBox.setBounds(100, 100, 150, 50);

// Add ItemListener to handle selection event


comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
System.out.println("Selected: " + e.getItem());
}
}
});

// Add combo box to frame


frame.add(comboBox);

// Set frame properties


frame.setSize(400, 400);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Write a programs to demonstrate the Mouse Event
Source Code:
// Import required packages
import java.awt.event.*;
import javax.swing.*;
public class MouseEventExample {
public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("MouseEvent Example");

// Create a label
JLabel label = new JLabel();
label.setBounds(100, 100, 200, 50);
label.setText("Mouse over me");

// Add MouseListener to handle mouse events


label.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked!");
}
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entered the label!");
}
public void mouseExited(MouseEvent e) {
System.out.println("Mouse exited the label!");
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
});
// Add label to frame
frame.add(label);

// Set frame properties


frame.setSize(400, 400);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Write a programs to demonstrate the Focus Event
Source code:
// Import required packages
import java.awt.event.*;
import javax.swing.*;
public class FocusEventExample {
public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("FocusEvent Example");
// Create two text fields
JTextField textField1 = new JTextField("Click here first");
textField1.setBounds(50, 100, 150, 50);

JTextField textField2 = new JTextField("Now click here");


textField2.setBounds(250, 100, 150, 50);
// Add FocusListener to handle focus events
textField1.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
System.out.println("TextField 1 gained focus");
}
public void focusLost(FocusEvent e) {
System.out.println("TextField 1 lost focus");
}
});
textField2.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
System.out.println("TextField 2 gained focus");
}
public void focusLost(FocusEvent e) {
System.out.println("TextField 2 lost focus");
}
});
// Add text fields to frame
frame.add(textField1);
frame.add(textField2);
// Set frame properties
frame.setSize(450, 300);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Write a program to create a class and implement a default, overloaded and
copy Constructor.
Source Code:
import java.io.*;
class Employee
{
int e;
Employee()
{
e = 10;
}
Employee(int e)
{
this.e = e;
}
Employee(Employee p)
{
this.e = p.e;
}
public static void main(String args[])
{
Employee emp1 = new Employee();
Employee emp2 = new Employee(20);
Employee emp3 = new Employee(emp2);
System.out.println("Default constructor value:"+emp1.e);
System.out.println("Parameterised constructor value:"+emp2.e);
System.out.println("Copy constructor value:"+emp3.e);

}
}
Write a program to create a class and implement the concepts of Method
Overloading.
Source Code:
import java.io.*;
class Square
{
void find_area(int a)
{
System.out.println("Area is"+(a*a));
}
void find_perimeter(int a)
{
System.out.println("Perimeter is "+(4*a));
}

public static void main (String[] args)


{
Square s = new Square();
s.find_area(4);
s.find_perimeter(5);
}
}

Write a program to create a class and implement the concepts of Static


methods.
Source Code:
import java.io.*;
class Maths
{
public static int add(int a,int b)
{
return a+b;
}
public static int multiply(int a,int b)
{
return a*b;
}
public static void main( String[] args)
{
System.out.println(Maths.add(2,3));
System.out.println(Maths.multiply(4,5));
}
}
Write a program to implement the concepts of Inheritance and Method
overriding.
Source Code:
import java.io.*;
class Animal
{
void sound()
{
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal
{
@Override
void sound()
{
System.out.println("Dog barks");
}
}
public class AnimalClass
{
public static void main(String args[])
{
Animal animal = new Animal();
animal.sound();
Dog dog = new Dog();
dog.sound();
}
}
Write a program to implement the concepts of Abstract classes and methods.
Source Code:
import java.io.*;
abstract class animal{
abstract void eat();
void print()
{
System.out.println("Animal");
}
}
class cat extends animal
{
void eat()
{
System.out.println("Cat can eat veg or non veg");
}
void print_cat()
{
System.out.println("Animal is cat");
}
}
class rat extends animal
{
void eat()
{
System.out.println("Rat can eat tomato");
}
void print_rat()
{
System.out.println("Animal is rat");
}
}
class dog extends animal
{
void eat()
{
System.out.println("Dog can eat Bone");
}
void print_dog()
{
System.out.println("Animal is dog");
}
}
class program_1
{
public static void main(String[]args)
{
cat c=new cat();
c.print_cat();
c.eat();
c.print();
rat r=new rat();
r.print_rat();
r.eat();
r.print();
dog d=new dog();
d.print_dog();
d.eat();
d.print();
}
}

You might also like