0% found this document useful (0 votes)
27 views

Java Practical File (11-25)

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

Java Practical File (11-25)

practical file for java programing
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

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.*; public
class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
Double num1 = sc.nextDouble();
System.out.println("Enter Second Number: ");
Double num2 = sc.nextDouble();
System.out.println("Choose the operator(+,-,/,*): ");
char op = sc.next().charAt(0);
double o = 0;
switch (op)
{ case '+':
o = num1 + num2;
break; case '-':
o = num1 - num2;
break;
case '/':
o = num1 / num2;
break; case '*':
o = num1 * num2;
break; case 'r':
o = num1 * num2;
break; default:
System.out.println("you enter wrong input");
}
System.out.println("the final result: ");
System.out.println(num1 + " " + op + " " + num2
+ " = " + o);
sc.close();
}
}
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;

public class Employee


{ private String name;
private int age;
private String address;

public void getData() {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter employee name:");
this.name = scanner.nextLine();
System.out.println("Enter employee age:");
this.age = scanner.nextInt();
scanner.nextLine(); // Consume newline character
System.out.println("Enter employee address:");
this.address = scanner.nextLine();
}
public void showData() {
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
System.out.println("Address: " + this.address);
}
public static void main(String[] args)
{ Employee employee = new Employee();
employee.getData();
System.out.println("\nEmployee Details:");
employee.showData();
}
}
15. Write a program to demonstrate any event handling.
import javax.swing.*; import
java.awt.*; import
java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class EventHandlingDemo extends JFrame implements ActionListener


{ private JLabel label;
private JButton button;

public EventHandlingDemo()
{ setTitle("Event Handling Demo");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

label = new JLabel("No button click yet.");


button = new JButton("Click me!");

button.addActionListener(this);

setLayout(new FlowLayout());

add(label);
add(button);

setVisible(true);
}

public void actionPerformed(ActionEvent e) {


if (e.getSource() == button) {
label.setText("Button clicked!");
}
}

public static void main(String[] args) {

EventHandlingDemo demo = new EventHandlingDemo();


}
}
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.IOException;
import java.io.InputStreamReader;

public class BufferedStreamDemo


{ public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter lines (type 'STOP' to end):");


try {
String line;
while ((line = reader.readLine()) != null) {
if (line.equals("STOP")) {
break;
}
System.out.println("You entered: " + line);
}
} catch (IOException e) {
System.err.println("Error reading input: " + e.getMessage());
} finally {
try {
reader.close();
} catch (IOException e) {
System.err.println("Error closing input stream: " + e.getMessage());
}
}
}
}
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.*;

public class ByteStreamFileReader


{ public static void main(String[] args)
{ String fileName = "example.txt";
try {
FileInputStream fis = new FileInputStream(fileName);
BufferedInputStream bis = new BufferedInputStream(fis);

int data;
while ((data = bis.read()) != -1)
{ System.out.print((char) data);
}
bis.close();
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}
13. Write a program to demonstrate creation of multiple child threads.
class MyThread extends Thread { public void run() {
System.out.println(Thread.currentThread().getName() + " is running.");
}
}

public class MultipleThreadsDemo {


public static void main(String[] args) {

for (int i = 1; i <= 5; i++) {


MyThread thread = new MyThread();
thread.start();
}
}
}

12. Write a program to demonstrate unchecked exception


public class UncheckedExceptionDemo
{ public static void main(String[] args) {
int[] numbers = {1, 2, 3};
int index = 4;
try {

int result = numbers[index];


System.out.println("Result: " + result);
} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Array index out of bounds!");


}

System.out.println("Program continues after the exception.");


}
}
11. Write a program to demonstrate checked exception during file handling.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class FileHandlingDemo {


public static void main(String[] args) {
try {

File file = new File("example.txt");


FileReader fr = new FileReader(file);

int data;
while ((data = fr.read()) != -1)
{ System.out.print((char) data);
}

fr.close();
} catch (FileNotFoundException e) {

System.out.println("File not found: " + e.getMessage());


} catch (Exception e) {

System.out.println("An error occurred: " + e.getMessage());


}
}
}
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.
class MyRunnable1 implements Runnable {
public void run() {
System.out.println("My name is Aryan.");
}
}

class MyRunnable2 implements Runnable {


public void run() {
System.out.println("Hello Java");
}
}

public class TwoThreadsDemo


{ public static void main(String[] args)
{

MyRunnable1 runnable1 = new MyRunnable1();


MyRunnable2 runnable2 = new MyRunnable2();

Thread thread1 = new Thread(runnable1);


Thread thread2 = new Thread(runnable2);

thread1.start();
thread2.start();
}
}
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 class RGBColorChooser extends JFrame {


private JScrollBar redScrollBar;
private JScrollBar greenScrollBar;
private JScrollBar blueScrollBar;
private JPanel colorPanel;

public RGBColorChooser()
{ setTitle("RGB Color Chooser");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

redScrollBar = new JScrollBar(JScrollBar.HORIZONTAL, 0, 1, 0, 256);


greenScrollBar = new JScrollBar(JScrollBar.HORIZONTAL, 0, 1, 0, 256);
blueScrollBar = new JScrollBar(JScrollBar.HORIZONTAL, 0, 1, 0, 256);

colorPanel = new JPanel();


colorPanel.setBackground(Color.BLACK);

getContentPane().setLayout(new GridLayout(4, 1));


getContentPane().add(redScrollBar);
getContentPane().add(greenScrollBar);
getContentPane().add(blueScrollBar);
getContentPane().add(colorPanel);

redScrollBar.addAdjustmentListener(new ScrollbarListener());
greenScrollBar.addAdjustmentListener(new ScrollbarListener());
blueScrollBar.addAdjustmentListener(new ScrollbarListener());
}

private class ScrollbarListener implements AdjustmentListener


{ public void adjustmentValueChanged(AdjustmentEvent e) {
int red = redScrollBar.getValue();
int green = greenScrollBar.getValue(); int
blue = blueScrollBar.getValue(); Color
color = new Color(red, green, blue);
colorPanel.setBackground(color);
}
}
public static void main(String[] args)
{ SwingUtilities.invokeLater(new Runnable() {
public void run() {
RGBColorChooser colorChooser = new RGBColorChooser();
colorChooser.setVisible(true);
}
});
}
}
22. Write a swing application that uses atleast 5 swing controls
import javax.swing.*; import java.awt.*;
import java.awt.event.*;

public class SwingControlsDemo extends JFrame {


private JLabel label; private JTextField textField;
private JButton button; private JCheckBox
checkBox; private JRadioButton radioButton1;
private JRadioButton radioButton2;
private ButtonGroup radioButtonGroup;

public SwingControlsDemo()
{ setTitle("Swing Controls Demo");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

label = new JLabel("Enter your name:");


label.setHorizontalAlignment(JLabel.CENTER);

textField = new JTextField(20);

button = new JButton("Submit");


button.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent e) {
String name = textField.getText();
JOptionPane.showMessageDialog(null, "Hello, " + name +
"!");
}
});
checkBox = new JCheckBox("Agree to terms");

radioButton1 = new JRadioButton("Option 1");


radioButton2 = new JRadioButton("Option 2");
radioButtonGroup = new ButtonGroup();
radioButtonGroup.add(radioButton1);
radioButtonGroup.add(radioButton2);

setLayout(new GridLayout(6, 1));


add(label);
add(textField);
add(button);
add(checkBox);
add(radioButton1);
add(radioButton2);
}
public static void main(String[] args)
{ SwingUtilities.invokeLater(new Runnable() {
public void run() {
SwingControlsDemo demo = new SwingControlsDemo();
demo.setVisible(true);
}
});
}
}
23. Write a program to implement border layout using Swing.
import javax.swing.*;
import java.awt.*;

public class BorderLayoutDemo extends JFrame


{ public BorderLayoutDemo()
{ setTitle("BorderLayout Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton northButton = new JButton("North");


JButton southButton = new JButton("South");
JButton eastButton = new JButton("East");
JButton westButton = new JButton("West");
JButton centerButton = new JButton("Center");

setLayout(new BorderLayout());

add(northButton, BorderLayout.NORTH);
add(southButton, BorderLayout.SOUTH);
add(eastButton, BorderLayout.EAST);
add(westButton, BorderLayout.WEST);
add(centerButton, BorderLayout.CENTER);
}
public static void main(String[] args)
{ SwingUtilities.invokeLater(new Runnable() {
public void run() {
BorderLayoutDemo demo = new BorderLayoutDemo();
demo.setVisible(true);
}
});
}
}
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.
class InsufficientFundsException extends Exception
{ public InsufficientFundsException(String message) {
super(message);
}
}
public class SavingsAccount
{ private int accountNumber;
private double balance;
public SavingsAccount(int accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}

public void depositAmount(double amount) {


balance += amount;
System.out.println("Deposited $" + amount + " successfully.");
}

public void withdrawAmount(double amount) throws InsufficientFundsException {


if (amount > balance) {
throw new InsufficientFundsException("Withdrawal amount exceeds available balance.");
}
balance -= amount;
System.out.println("Withdrawn $" + amount + " successfully.");
}

public double getBalance() {


return balance;
}
public static void main(String[] args) {
SavingsAccount account = new SavingsAccount(123456, 1000);
try {
account.withdrawAmount(500);
account.withdrawAmount(700); // This will throw an exception
} catch (InsufficientFundsException e) {
System.out.println("Exception: " + e.getMessage());
}
}}
11. Write a program to demonstrate checked exception during file handling import
java.io.*;

public class CheckedExceptionDemo {


public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("nonexistentfile.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);

String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

bufferedReader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
}
}
24. Write a java program to insert and update details data in the database.
25. Write a java program to retrieve data from database and display it on GUI.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy