0% found this document useful (0 votes)
5 views32 pages

Emailing JAVA_FILE_PART-II

The document contains Java programming examples demonstrating various concepts such as checked and unchecked exceptions, multithreading, file handling, event handling, and GUI applications using Swing. Each section provides a code snippet illustrating specific functionalities like reading from files, creating threads, handling user input, and implementing a simple calculator. Additionally, there are examples of custom exceptions and using Swing components to create interactive applications.

Uploaded by

Atish Kumar
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)
5 views32 pages

Emailing JAVA_FILE_PART-II

The document contains Java programming examples demonstrating various concepts such as checked and unchecked exceptions, multithreading, file handling, event handling, and GUI applications using Swing. Each section provides a code snippet illustrating specific functionalities like reading from files, creating threads, handling user input, and implementing a simple calculator. Additionally, there are examples of custom exceptions and using Swing components to create interactive applications.

Uploaded by

Atish Kumar
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/ 32

11. Write a program to demonstrate checked exception during file handling.

import java.io.*;
public class Q11 {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("nonexistentfile.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException occurred: " + e.getMessage());
}
}
}

BASIT REHMAN 09017702023 17


12. Write a program to demonstrate unchecked exception.

public class Q12 {


public static void main(String[] args) {
int a = 10;
int b = 0;
int result = a / b;
System.out.println("Result: " + result);
}
}

BASIT REHMAN 09017702023 18


13. Write a program to demonstrate creation of multiple child threads.

class MyThread extends Thread {


private String threadName;

MyThread(String name) {
this.threadName = name;
}
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " - Count: " + i);
try {
Thread.sleep(500); // Pause for 0.5 second
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
}
System.out.println(threadName + " has finished execution.");
}
}
public class Q13 {
public static void main(String[] args) {
// Creating child threads
MyThread t1 = new MyThread("Thread-1");
MyThread t2 = new MyThread("Thread-2");
MyThread t3 = new MyThread("Thread-3");

BASIT REHMAN 09017702023 19


// Starting child threads
t1.start();
t2.start();
t3.start();

System.out.println("Main thread has started all child threads.");


}
}

BASIT REHMAN 09017702023 20


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;

public class Q14 {


public static void main(String[] args) {
FileInputStream fis = null;
try {
// Replace with your actual file path
fis = new FileInputStream("example.txt");

int byteData;
while ((byteData = fis.read()) != -1) {
// Convert byte to character and print
System.out.print((char) byteData);
}
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e);
} catch (IOException e) {
System.out.println("Error reading file: " + e);
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {

BASIT REHMAN 09017702023 21


System.out.println("Error closing file: " + e);
}
}
}
}

BASIT REHMAN 09017702023 22


15. Write a program to demonstrate any event handling.

import javax.swing.*;
import java.awt.event.*;

public class Q15 {


public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("Event Handling Demo");

// Create a button
JButton button = new JButton("Click Me");
button.setBounds(100, 100, 100, 40);

// Create a label
JLabel label = new JLabel("Waiting for click...");
label.setBounds(90, 50, 200, 30);

// Add ActionListener to the button


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("Button Clicked!");
}
}
);

BASIT REHMAN 09017702023 23


// Add button and label to frame
frame.add(label);
frame.add(button);

frame.setSize(300, 250);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

BASIT REHMAN 09017702023 24


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:

class employee{

String name;

int age;

String address;
void getdata(String name, int age,String address){

this.name=name;

this.age=age;

this.address=address; }

void showdata(){

System.out.println("Name: "+name);

System.out.println("Age: "+age);

System.out.println("Address: "+address); }

public class Q16 {

public static void main(String[] args) {

employee CJ=new employee();

CJ.getdata("Carl Johnson", 26, "Grove Street Los Santos");

CJ.showdata(); }
}

BASIT REHMAN 09017702023 25


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;
public class Q17 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1, num2, choice;
double result = 0;
System.out.print("Enter first number: ");
num1 = sc.nextInt()
System.out.print("Enter second number: ");
num2 = sc.nextInt();
System.out.println("\nChoose an operation:");
System.out.println("1. Addition (+)");
System.out.println("2. Subtraction (-)");
System.out.println("3. Multiplication (*)");
System.out.println("4. Division (/)");
System.out.print("Enter your choice (1-4): ");
choice = sc.nextInt()
switch (choice) {
case 1:
result = num1 + num2;
System.out.println("Result: " + result);
break;

BASIT REHMAN 09017702023 26


case 2:
result = num1 - num2;
System.out.println("Result: " + result);
break;
case 3:
result = num1 * num2;
System.out.println("Result: " + result);
break;
case 4:
if (num2 != 0) {
result = (double) num1 / num2;
System.out.println("Result: " + result);
}
else {
System.out.println("Error: Division by zero is not allowed.");
}
break;
default:
System.out.println("Invalid choice. Please select between 1 to 4.");
}

sc.close();
}
}

BASIT REHMAN 09017702023 27


BASIT REHMAN 09017702023 28
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 Q18 {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String line = "";
System.out.println("Enter text (type 'STOP' to end):");
try {
while (true) {
line = reader.readLine(); // Read a line from the keyboard
if (line.equalsIgnoreCase("STOP")) {
System.out.println("Program terminated.");
break;
}
System.out.println("You typed: " + line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading input.");
e.printStackTrace(); }
}
}

BASIT REHMAN 09017702023 29


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.

// Custom Exception Class


class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}

// SavingsAccount Class
class SavingsAccount {
private String accountNumber;
private double balance;

public SavingsAccount(String accountNumber, double initialBalance) {


this.accountNumber = accountNumber;
this.balance = initialBalance;
}

public void depositAmount(double amount) {


if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
} else {
System.out.println("Deposit amount must be positive.");

BASIT REHMAN 09017702023 30


}
}

public void withdrawAmount(double amount) throws InsufficientFundsException {


if (amount > balance) {
throw new InsufficientFundsException("Withdrawal amount exceeds balance.");
}
else if (amount > 0) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
}
else {
System.out.println("Withdrawal amount must be positive.");
}
}

public double getBalance() {


return balance;
}
public String getAccountNumber() {
return accountNumber;
}
}

BASIT REHMAN 09017702023 31


public class Q19 {
public static void main(String[] args) {
SavingsAccount account = new SavingsAccount("123456789", 1000.00);

// Deposit Amount
account.depositAmount(500.00);
System.out.println("Current Balance: " + account.getBalance());

// Withdraw Amount
try {
account.withdrawAmount(200.00);
System.out.println("Current Balance: " + account.getBalance());

// Attempt to withdraw more than the balance


account.withdrawAmount(1500.00);
} catch (InsufficientFundsException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}

BASIT REHMAN 09017702023 32


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.

// First Runnable class to print the name


class NameRunnable implements Runnable {

public void run() {


System.out.println("Your Name"); // Replace "Your Name" with your actual
name
}
}

// Second Runnable class to print "Hello Java"


class HelloJavaRunnable implements Runnable {

public void run() {


System.out.println("Hello Java");
}
}

// Main class to create and start the threads


public class Q20 {
public static void main(String[] args) {
// Create instances of the Runnable classes
NameRunnable nameRunnable = new NameRunnable();
HelloJavaRunnable helloJavaRunnable = new HelloJavaRunnable();
// Create threads using the Runnable instances

BASIT REHMAN 09017702023 33


Thread thread1 = new Thread(nameRunnable);
Thread thread2 = new Thread(helloJavaRunnable);

// Start the threads


thread1.start();
thread2.start();

// Optionally, wait for threads to finish


try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + e.getMessage());
}
}
}

BASIT REHMAN 09017702023 34


21. Write program that uses swings to display combination of RGB using 3
scrollbars.

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

public class RGBColorMixer extends JFrame {


private JSlider redSlider;
private JSlider greenSlider;
private JSlider blueSlider;
private JPanel colorPanel;

public RGBColorMixer() {
setTitle("RGB Color Mixer");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Create sliders for Red, Green, and Blue


redSlider = createColorSlider("Red");
greenSlider = createColorSlider("Green");
blueSlider = createColorSlider("Blue");

// Create a panel to display the color


colorPanel = new JPanel();
colorPanel.setPreferredSize(new Dimension(400, 100));
updateColor();

BASIT REHMAN 09017702023 35


// Add components to the frame
add(redSlider, BorderLayout.NORTH);
add(greenSlider, BorderLayout.CENTER);
add(blueSlider, BorderLayout.SOUTH);
add(colorPanel, BorderLayout.PAGE_END);
}

private JSlider createColorSlider(String colorName) {


JSlider slider = new JSlider(0, 255, 0);
slider.setMajorTickSpacing(51);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.addChangeListener(e -> updateColor());
return slider;
}

private void updateColor() {


int red = redSlider.getValue();
int green = greenSlider.getValue();
int blue = blueSlider.getValue();
colorPanel.setBackground(new Color(red, green, blue));
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
RGBColorMixer mixer = new RGBColorMixer();
mixer.setVisible(true);

BASIT REHMAN 09017702023 36


});
}
}

BASIT REHMAN 09017702023 37


22. Write a swing application that uses atleast 5 swing controls

import java.awt.event.*;
import javax.swing.*;

public class SwingFormExample extends JFrame implements ActionListener {


JLabel nameLabel, genderLabel, hobbyLabel;
JTextField nameField;
JRadioButton maleButton, femaleButton;
JCheckBox readingBox, codingBox, musicBox;
JButton submitButton;
JTextArea outputArea;
ButtonGroup genderGroup;

public SwingFormExample() {
setTitle("Simple Swing Form");
setSize(400, 400);
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);

// Name
nameLabel = new JLabel("Name:");
nameLabel.setBounds(30, 30, 80, 20);
nameField = new JTextField();
nameField.setBounds(120, 30, 200, 25);

BASIT REHMAN 09017702023 38


// Gender
genderLabel = new JLabel("Gender:");
genderLabel.setBounds(30, 70, 80, 20);
maleButton = new JRadioButton("Male");
femaleButton = new JRadioButton("Female");
maleButton.setBounds(120, 70, 70, 20);
femaleButton.setBounds(200, 70, 100, 20);
genderGroup = new ButtonGroup();
genderGroup.add(maleButton);
genderGroup.add(femaleButton);

// Hobbies
hobbyLabel = new JLabel("Hobbies:");
hobbyLabel.setBounds(30, 110, 80, 20);
readingBox = new JCheckBox("Reading");
codingBox = new JCheckBox("Coding");
musicBox = new JCheckBox("Music");
readingBox.setBounds(120, 110, 80, 20);
codingBox.setBounds(200, 110, 80, 20);
musicBox.setBounds(280, 110, 80, 20);

// Submit button
submitButton = new JButton("Submit");
submitButton.setBounds(150, 150, 100, 30);
submitButton.addActionListener(this);

BASIT REHMAN 09017702023 39


// Output area
outputArea = new JTextArea();
outputArea.setBounds(30, 200, 320, 120);
outputArea.setEditable(false);

// Add to frame
add(nameLabel);
add(nameField);
add(genderLabel);
add(maleButton);
add(femaleButton);
add(hobbyLabel);
add(readingBox);
add(codingBox);
add(musicBox);
add(submitButton);
add(outputArea);

setVisible(true);
}

public void actionPerformed(ActionEvent e) {


String name = nameField.getText();
String gender = maleButton.isSelected() ? "Male" : femaleButton.isSelected() ?
"Female" : "Not Selected";
String hobbies = "";

BASIT REHMAN 09017702023 40


if (readingBox.isSelected()) hobbies += "Reading ";
if (codingBox.isSelected()) hobbies += "Coding ";
if (musicBox.isSelected()) hobbies += "Music ";

outputArea.setText("Name: " + name + "\nGender: " + gender + "\nHobbies: " +


hobbies);
}

public static void main(String[] args) {


new SwingFormExample();
}
}

BASIT REHMAN 09017702023 41


23. Write a program to implement border layout using Swing.

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

public class BorderLayoutExample extends JFrame {


public BorderLayoutExample() {
setTitle("BorderLayout Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Create components
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");

// Add components to the frame


add(northButton, BorderLayout.NORTH);
add(southButton, BorderLayout.SOUTH);
add(eastButton, BorderLayout.EAST);
add(westButton, BorderLayout.WEST);
add(centerButton, BorderLayout.CENTER);
}

BASIT REHMAN 09017702023 42


public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
BorderLayoutExample example = new BorderLayoutExample();
example.setVisible(true);
});
}
}

BASIT REHMAN 09017702023 43


24. Write a java program to insert and update details data in the database.

import java.sql.*;
public class q24 {
static final String JDBC_URL = "jdbc:mysql://localhost:3306/testdb";
static final String USER = "root"; // your DB username
static final String PASS = "3373"; // your DB password

public static void main(String[] args) {


insertUser("Alice", "[email protected]");
updateUserEmail(1, "[email protected]");
}

public static void insertUser(String name, String email) {


String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)";

try (Connection conn = DriverManager.getConnection(JDBC_URL, USER,


PASS);
PreparedStatement pstmt = conn.prepareStatement(insertSQL)) {

pstmt.setString(1, name);
pstmt.setString(2, email);

int rowsInserted = pstmt.executeUpdate();


System.out.println(rowsInserted + " row(s) inserted.");
}

BASIT REHMAN 09017702023 44


catch (SQLException e) {
e.printStackTrace();
}
}

public static void updateUserEmail(int userId, String newEmail) {


String updateSQL = "UPDATE users SET email = ? WHERE id = ?";

try (Connection conn = DriverManager.getConnection(JDBC_URL, USER,


PASS);
PreparedStatement pstmt = conn.prepareStatement(updateSQL)) {

pstmt.setString(1, newEmail);
pstmt.setInt(2, userId);

int rowsUpdated = pstmt.executeUpdate();


System.out.println(rowsUpdated + " row(s) updated.");

} catch (SQLException e) {
e.printStackTrace();
}
}
}

BASIT REHMAN 09017702023 45


25. Write a java program to retrieve data from database and display it on GUI.

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class q25 extends JFrame {


static final String JDBC_URL = "jdbc:mysql://localhost:3306/testdb";
static final String USER = "root";
static final String PASS = "3373";

public q25() {
setTitle("User List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 300);

// Table model and JTable


DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);

model.addColumn("ID");
model.addColumn("Name");
model.addColumn("Email");

BASIT REHMAN 09017702023 46


// Fetch and add data
try (Connection conn = DriverManager.getConnection(JDBC_URL, USER,
PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users")) {

while (rs.next()) {
model.addRow(new Object[]{
rs.getInt("id"),
rs.getString("name"),
rs.getString("email")
});
}

} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Database error: " + e.getMessage());
}

setVisible(true);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(q25::new);
}
}

BASIT REHMAN 09017702023 47


BASIT REHMAN 09017702023 48

You might also like