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

2nd Half Java File_merged (1)

The document contains a series of practical Java programming tasks, including implementing data structures, creating user-defined exceptions, and handling GUI components with AWT and Swing. Each task is accompanied by a brief description and sample code demonstrating the implementation. The tasks cover various Java concepts such as threading, event handling, and database operations.

Uploaded by

royal GAMMER
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

2nd Half Java File_merged (1)

The document contains a series of practical Java programming tasks, including implementing data structures, creating user-defined exceptions, and handling GUI components with AWT and Swing. Each task is accompanied by a brief description and sample code demonstrating the implementation. The tasks cover various Java concepts such as threading, event handling, and database operations.

Uploaded by

royal GAMMER
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

INDEX

Sno. Practical Questions Date Signature


16 Write a Java program to implement vector [use:
addelement(),elementat().removeelement(),size().]

17 Create a user defined exception named


“nomatchexception” that is fired when the
string entered by the user is not “india”
18 Write a Java program to show even & odd
numbers by thread
19 Write a Java program that draws different color
shapes on an swing program .set the
foreground & background color as red & blue
20 Write a Java program to show moving banner by
swing
21 Write a Java program to demonstrate the use of
equals(), trim() ,length() , substring(),
compareto() of string class
22 Write a Java program to demonstrate the use of
equals() and == in Java
23 Write a Java program to implement all mouse events
and mouse motion events.

24 Write a Java program to implement keyboard


events

25 Write a Java program using AWT to create a simple


calculator
26 Create a login form using AWT controls like labels,
buttons, textboxes, checkboxes,
list, checkboxgroup. The selected checkbox item
names should be displayed
27 Create a login form using Swing controls like Jlabels,
Jbuttons, Jtextboxes, Jcheckboxes.
28 Write a Java program to show all layout managers.
(4 layout managers)
29 Create swing program with two buttons named
‘audio’ and ‘image’. When user will
press button ‘audio’ then an audio file should play in
the program, and if user press
button ‘image’ then an image should see in as
output
30 Create a Java applet with three buttons
‘red’,’green’,’blue’. Whenever user press any
button the corresponding color should be seen as
background color in the window
31 Write a Java program in Java to implement the
concept of ‘synchronization’ using
thread
32 Create a simple JDBC program that creates a table,
stores data into it, retrieves &
prints the data
33 Write a Java program in Java to create database
table using Java
34 Write a Java program in Java to insert, update,
delete & select records
35 Write Java program to read input from java console

36 Write a Java program to implement file


handling(both reading & writing to a file)
37 Write a Java program on anonymous classes
16.Write a Java program to implement vector.
[use:addelement(),elementat().removeelement(),size().]

sol. import java.util.Vector;


public class VectorExample {
public static void main(String[] args) {
Vector<String> fruits = new Vector<>();
fruits.addElement("Apple");
fruits.addElement("Banana");
fruits.addElement("Mango");

System.out.println("Elements in Vector: " + fruits);

String secondFruit = fruits.elementAt(1);


System.out.println("Element at index 1: " + secondFruit);

fruits.removeElement("Banana");
System.out.println("After removing 'Banana': " + fruits);

int size = fruits.size();


System.out.println("Size of Vector: " + size);
}
}

output:
17.Create a user defined exception named
“nomatchexception” that is fired when the string
entered by the user is not “india”.

Sol. import java.util.Scanner;

class NoMatchException extends Exception {


NoMatchException(String message) {
super(message);
}
}

public class MatchCheck {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = sc.nextLine();

try {
if (!input.equals("india")) {
throw new NoMatchException("Input does not match
'india'.");
} else {
System.out.println("Input matches 'india'.");
}
} catch (NoMatchException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}

output:
18.Write a Java program to show even & odd numbers by thread.

Sol. class EvenThread extends Thread {


public void run() {
for (int i = 0; i <= 10; i += 2) {
System.out.println("Even: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
}

class OddThread extends Thread {


public void run() {
for (int i = 1; i <= 10; i += 2) {
System.out.println("Odd: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
}

public class EvenOddThreads {


public static void main(String[] args) {
EvenThread even = new EvenThread();
OddThread odd = new OddThread();

even.start();

odd.start();
}
}
Output:

19.Write a Java program that draws different color


shapes on an swing program .set the foreground &
background color as red & blue.

Sol. import javax.swing.*;


import java.awt.*;

public class ColorShapes extends JFrame {


ColorShapes() {
setTitle("Colorful Shapes");
setSize(400, 400);
setBackground(Color.BLUE);
setForeground(Color.RED);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void paint(Graphics g) {


setBackground(Color.BLUE);
setForeground(Color.RED);

g.setColor(Color.RED);
g.fillRect(50, 50, 100, 100); // Red square

g.setColor(Color.GREEN);
g.fillOval(200, 50, 100, 100); // Green circle

g.setColor(Color.YELLOW);
g.fillRoundRect(100, 200, 150, 100, 30, 30); //
Yellow rounded rectangle
}

public static void main(String[] args) {


new ColorShapes();
}
}
Out
put:
20.Write a Java program to show moving banner by
swing.

Sol. import javax.swing.*;


import java.awt.*;

public class MovingBanner extends JFrame implements


Runnable {
String text = " Welcome to Java Practical! ";
int x = 50, y = 100;

MovingBanner() {
setTitle("Moving Banner");
setSize(500, 300);
setBackground(Color.BLACK);
setForeground(Color.WHITE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Thread t = new Thread(this);
t.start();
}

public void paint(Graphics g) {


setBackground(Color.BLACK);
setForeground(Color.WHITE);
g.setColor(Color.RED);
g.drawString(text, x, y);
}

public void run() {


while (true) {
x += 5;
if (x > getWidth()) {
x = -200;
}
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}

public static void main(String[] args) {


new MovingBanner();
}
}
Output:
21.Write a Java program to demonstrate the use of
equals(), trim() ,length() , substring(), compareto() of
string class

Sol. public class StringMethodsExample {


public static void main(String[] args) {
String str1 = " Hello World ";
String str2 = "Hello World";
String str3 = "Java";

System.out.println("Original str1: '" + str1 + "'");


System.out.println("Original str2: '" + str2 + "'");

String trimmedStr = str1.trim();


System.out.println("After trim() on str1: '" +
trimmedStr + "'");

boolean isEqual = trimmedStr.equals(str2);


System.out.println("After equals() check between
trimmedStr and str2: " + isEqual);

System.out.println("Length of str3: " + str3.length());


String subStr = str2.substring(0, 5);
System.out.println("Substring of str2 (0-5): " +
subStr);

int compareResult = str3.compareTo(str2);


System.out.println("compareTo() result between str3
and str2: " + compareResult);
}
}

Output:

22.Wri
te a
Java program to demonstrate the use of equals() and ==
in Java.

Sol.public class EqualsVsDoubleEquals {


public static void main(String[] args) {
String str1 = new String("Java");
String str2 = new String("Java");
String str3 = "Java";
String str4 = "Java";

System.out.println(str1 == str2);
System.out.println(str1.equals(str2));
System.out.println(str3 == str4);
System.out.println(str3.equals(str4));
}
}

Output.
23.Write a Java program to implement all mouse events
and mouse motion events.
Sol. import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseEventsExample extends JFrame


implements MouseListener, MouseMotionListener {
JLabel label;

MouseEventsExample() {
label = new JLabel();
label.setBounds(20, 50, 300, 20);
add(label);

addMouseListener(this);
addMouseMotionListener(this);

setSize(400, 400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void mouseClicked(MouseEvent e) {


label.setText("Mouse Clicked");
}

public void mousePressed(MouseEvent e) {


label.setText("Mouse Pressed");
}

public void mouseReleased(MouseEvent e) {


label.setText("Mouse Released");
}

public void mouseEntered(MouseEvent e) {


label.setText("Mouse Entered");
}

public void mouseExited(MouseEvent e) {


label.setText("Mouse Exited");
}

public void mouseDragged(MouseEvent e) {


label.setText("Mouse Dragged at (" + e.getX() + ", " +
e.getY() + ")");
}

public void mouseMoved(MouseEvent e) {


label.setText("Mouse Moved at (" + e.getX() + ", " +
e.getY() + ")");
}

public static void main(String[] args) {


new MouseEventsExample();
}
}

Output:
24.Write a Java program to implement keyboard events.
Sol. import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class KeyboardEventsExample extends JFrame


implements KeyListener {
JLabel label;

KeyboardEventsExample() {
label = new JLabel();
label.setBounds(20, 50, 300, 20);
add(label);

addKeyListener(this);

setSize(400, 400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setFocusable(true);
}
public void keyTyped(KeyEvent e) {
label.setText("Key Typed: " + e.getKeyChar());
}

public void keyPressed(KeyEvent e) {


label.setText("Key Pressed: " + e.getKeyChar());
}

public void keyReleased(KeyEvent e) {


label.setText("Key Released: " + e.getKeyChar());
}

public static void main(String[] args) {


new KeyboardEventsExample();
}
}

Output:
25.Write a Java program using AWT to create a simple
calculator.
Sol. import java.awt.*;
import java.awt.event.*;

public class SimpleCalculator extends Frame implements


ActionListener {
TextField tf1, tf2, tf3;
Button add, sub, mul, div, clear;

SimpleCalculator() {
tf1 = new TextField();
tf1.setBounds(50, 50, 150, 20);

tf2 = new TextField();


tf2.setBounds(50, 100, 150, 20);

tf3 = new TextField();


tf3.setBounds(50, 150, 150, 20);
tf3.setEditable(false);

add = new Button("+");


add.setBounds(50, 200, 50, 50);
sub = new Button("-");
sub.setBounds(110, 200, 50, 50);
mul = new Button("*");
mul.setBounds(170, 200, 50, 50);
div = new Button("/");
div.setBounds(230, 200, 50, 50);
clear = new Button("C");
clear.setBounds(290, 200, 50, 50);

add(add);
add(sub);
add(mul);
add(div);
add(clear);
add(tf1);
add(tf2);
add(tf3);

add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
clear.addActionListener(this);

setSize(400, 400);
setLayout(null);
setVisible(true);
setTitle("Simple Calculator");
}
public void actionPerformed(ActionEvent e) {
try {
int n1 = Integer.parseInt(tf1.getText());
int n2 = Integer.parseInt(tf2.getText());
if (e.getSource() == add) {
tf3.setText(String.valueOf(n1 + n2));
} else if (e.getSource() == sub) {
tf3.setText(String.valueOf(n1 - n2));
} else if (e.getSource() == mul) {
tf3.setText(String.valueOf(n1 * n2));
} else if (e.getSource() == div) {
if (n2 != 0) {
tf3.setText(String.valueOf(n1 / n2));
} else {
tf3.setText("Divide by 0");
}
} else if (e.getSource() == clear) {
tf1.setText("");
tf2.setText("");
tf3.setText("");
}
} catch (Exception ex) {
tf3.setText("Invalid");
}
}

public static void main(String[] args) {


new SimpleCalculator();
}
}
Output:
26.Create a login form using AWT controls like labels,
buttons, textboxes, checkboxes, list, checkboxgroup. The
selected checkbox item names should be displayed.

Sol. import java.awt.*;


import java.awt.event.*;

public class LoginFormAWT extends Frame implements


ActionListener {
Label userLabel, passLabel, hobbiesLabel, genderLabel,
selectedHobbies;
TextField userText, passText;
Button loginButton;
Checkbox hobby1, hobby2, hobby3;
CheckboxGroup genderGroup;
Checkbox male, female;

LoginFormAWT() {
userLabel = new Label("Username:");
userLabel.setBounds(50, 50, 80, 20);
userText = new TextField();
userText.setBounds(150, 50, 150, 20);

passLabel = new Label("Password:");


passLabel.setBounds(50, 90, 80, 20);
passText = new TextField();
passText.setBounds(150, 90, 150, 20);
passText.setEchoChar('*');

hobbiesLabel = new Label("Hobbies:");


hobbiesLabel.setBounds(50, 130, 80, 20);
hobby1 = new Checkbox("Reading");
hobby1.setBounds(150, 130, 100, 20);
hobby2 = new Checkbox("Music");
hobby2.setBounds(150, 160, 100, 20);
hobby3 = new Checkbox("Sports");
hobby3.setBounds(150, 190, 100, 20);

genderLabel = new Label("Gender:");


genderLabel.setBounds(50, 230, 80, 20);
genderGroup = new CheckboxGroup();
male = new Checkbox("Male", genderGroup, false);
male.setBounds(150, 230, 60, 20);
female = new Checkbox("Female", genderGroup, false);
female.setBounds(220, 230, 70, 20);

loginButton = new Button("Login");


loginButton.setBounds(150, 270, 80, 30);
loginButton.addActionListener(this);
selectedHobbies = new Label();
selectedHobbies.setBounds(50, 320, 300, 20);

add(userLabel);
add(userText);
add(passLabel);
add(passText);
add(hobbiesLabel);
add(hobby1);
add(hobby2);
add(hobby3);
add(genderLabel);
add(male);
add(female);
add(loginButton);
add(selectedHobbies);

setSize(400, 400);
setLayout(null);
setVisible(true);
setTitle("Login Form");
}

public void actionPerformed(ActionEvent e) {


String hobbies = "";
if (hobby1.getState()) {
hobbies += "Reading ";
}
if (hobby2.getState()) {
hobbies += "Music ";
}
if (hobby3.getState()) {
hobbies += "Sports ";
}
selectedHobbies.setText("Selected Hobbies: " + hobbies);
}

public static void main(String[] args) {


new LoginFormAWT();
}
}
Output.
27.Create a login form using Swing controls like Jlabels,
Jbuttons, Jtextboxes, Jcheckboxes.

Sol. import javax.swing.*;


import java.awt.event.*;

public class SwingLoginForm extends JFrame implements


ActionListener {
JLabel userLabel, passLabel, hobbiesLabel, selectedHobbies;
JTextField userText;
JPasswordField passText;
JCheckBox hobby1, hobby2, hobby3;
JButton loginButton;

SwingLoginForm() {
userLabel = new JLabel("Username:");
userLabel.setBounds(50, 50, 80, 20);
userText = new JTextField();
userText.setBounds(150, 50, 150, 20);

passLabel = new JLabel("Password:");


passLabel.setBounds(50, 90, 80, 20);
passText = new JPasswordField();
passText.setBounds(150, 90, 150, 20);
hobbiesLabel = new JLabel("Hobbies:");
hobbiesLabel.setBounds(50, 130, 80, 20);
hobby1 = new JCheckBox("Reading");
hobby1.setBounds(150, 130, 100, 20);
hobby2 = new JCheckBox("Music");
hobby2.setBounds(150, 160, 100, 20);
hobby3 = new JCheckBox("Sports");
hobby3.setBounds(150, 190, 100, 20);

loginButton = new JButton("Login");


loginButton.setBounds(150, 230, 80, 30);
loginButton.addActionListener(this);

selectedHobbies = new JLabel();


selectedHobbies.setBounds(50, 280, 300, 20);

add(userLabel);
add(userText);
add(passLabel);
add(passText);
add(hobbiesLabel);
add(hobby1);
add(hobby2);
add(hobby3);
add(loginButton);
add(selectedHobbies);

setSize(400, 400);
setLayout(null);
setVisible(true);
setTitle("Swing Login Form");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e) {


String hobbies = "";
if (hobby1.isSelected()) {
hobbies += "Reading ";
}
if (hobby2.isSelected()) {
hobbies += "Music ";
}
if (hobby3.isSelected()) {
hobbies += "Sports ";
}
selectedHobbies.setText("Selected Hobbies: " + hobbies);
}

public static void main(String[] args) {


new SwingLoginForm();
}
}

Output:
28.Write a Java program to show all layout managers. (4
layout
managers).

Sol. import javax.swing.*;


import java.awt.*;

public class LayoutManagersDemo extends JFrame {


LayoutManagersDemo() {
// Set up the JFrame
setTitle("Layout Managers Demo");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// BorderLayout (Top, Center, etc.)


JButton button1 = new JButton("BorderLayout North");
JButton button2 = new JButton("BorderLayout South");
JButton button3 = new JButton("BorderLayout East");
JButton button4 = new JButton("BorderLayout West");
JButton button5 = new JButton("BorderLayout Center");

add(button1, BorderLayout.NORTH);
add(button2, BorderLayout.SOUTH);
add(button3, BorderLayout.EAST);
add(button4, BorderLayout.WEST);
add(button5, BorderLayout.CENTER);

// FlowLayout
JPanel flowPanel = new JPanel(new FlowLayout());
flowPanel.add(new JButton("FlowLayout 1"));
flowPanel.add(new JButton("FlowLayout 2"));
flowPanel.add(new JButton("FlowLayout 3"));
flowPanel.add(new JButton("FlowLayout 4"));

// GridLayout
JPanel gridPanel = new JPanel(new GridLayout(2, 2));
gridPanel.add(new JButton("GridLayout 1"));
gridPanel.add(new JButton("GridLayout 2"));
gridPanel.add(new JButton("GridLayout 3"));
gridPanel.add(new JButton("GridLayout 4"));

// GridBagLayout
JPanel gridBagPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();

gbc.gridx = 0;
gbc.gridy = 0;
gridBagPanel.add(new JButton("GridBag 1"), gbc);

gbc.gridx = 1;
gbc.gridy = 0;
gridBagPanel.add(new JButton("GridBag 2"), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gridBagPanel.add(new JButton("GridBag 3"), gbc);

gbc.gridx = 1;
gbc.gridy = 1;
gridBagPanel.add(new JButton("GridBag 4"), gbc);

// Add panels to JFrame


add(flowPanel, BorderLayout.NORTH);
add(gridPanel, BorderLayout.CENTER);
add(gridBagPanel, BorderLayout.SOUTH);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
new LayoutManagersDemo().setVisible(true);
});
}
}
Output:
29.Create swing program with two buttons named ‘audio’ and
‘image’. When user will press button ‘audio’ then an audio file
should play in the program, and if user press button ‘image’
then an image should see in as output

Sol. import javax.swing.*;


import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.sound.sampled.*;

public class AudioImageApp extends JFrame implements


ActionListener {
JButton audioButton, imageButton;
JLabel imageLabel;

AudioImageApp() {
audioButton = new JButton("Audio");
imageButton = new JButton("Image");

audioButton.setBounds(50, 50, 100, 30);


imageButton.setBounds(200, 50, 100, 30);

audioButton.addActionListener(this);
imageButton.addActionListener(this);
imageLabel = new JLabel();
imageLabel.setBounds(50, 100, 300, 300);

add(audioButton);
add(imageButton);
add(imageLabel);

setTitle("Audio and Image App");


setSize(400, 500);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


if (e.getSource() == audioButton) {
playAudio("audiofile.wav"); // Make sure you have a
valid audio file in the same directory
} else if (e.getSource() == imageButton) {
showImage("imagefile.jpg"); // Make sure you have a
valid image file in the same directory
}
}

private void playAudio(String filePath) {


try {
File audioFile = new File(filePath);
AudioInputStream audioStream =
AudioSystem.getAudioInputStream(audioFile);
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
clip.start();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error playing
audio: " + e.getMessage());
}
}

private void showImage(String filePath) {


ImageIcon imageIcon = new ImageIcon(filePath);
imageLabel.setIcon(imageIcon);
}

public static void main(String[] args) {


new AudioImageApp();
}
}

Output.
30.Create a Java applet with three buttons ‘red’,’green’,’blue’.
Whenever user press any button the corresponding color
should be seen as background color in the window.

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

public class ColorSwingExample extends JFrame implements


ActionListener {
JButton redButton, greenButton, blueButton;

public ColorSwingExample() {
setTitle("Color Change App");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

redButton = new JButton("Red");


greenButton = new JButton("Green");
blueButton = new JButton("Blue");

redButton.addActionListener(this);
greenButton.addActionListener(this);
blueButton.addActionListener(this);

setLayout(new FlowLayout());
add(redButton);
add(greenButton);
add(blueButton);
}

public void actionPerformed(ActionEvent e) {


if (e.getSource() == redButton) {
getContentPane().setBackground(Color.RED);
} else if (e.getSource() == greenButton) {
getContentPane().setBackground(Color.GREEN);
} else if (e.getSource() == blueButton) {
getContentPane().setBackground(Color.BLUE);
}
}

public static void main(String[] args) {


ColorSwingExample frame = new ColorSwingExample();
frame.setVisible(true);
}
}

Output:
31.Write a Java program in Java to implement the concept
of ‘synchronization’ using thread.

Sol. class Counter {


private int count = 0;

public synchronized void increment() {


count++;
}

public int getCount() {


return count;
}
}

class CounterThread extends Thread {


Counter counter;

CounterThread(Counter counter) {
this.counter = counter;
}

@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}

public class SynchronizationExample {


public static void main(String[] args) {
Counter counter = new Counter();
CounterThread thread1 = new CounterThread(counter);
CounterThread thread2 = new CounterThread(counter);

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

try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Final counter value: " +


counter.getCount());
}
}
Output.
32.Create a simple JDBC program that creates a table, stores
data into it, retrieves & prints the data.

Sol.import java.sql.*;

public class SQLiteExample {


public static void main(String[] args) {
try {
Class.forName("org.sqlite.JDBC");
String url = "jdbc:sqlite:students.db";
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
String createTable = "CREATE TABLE IF NOT EXISTS
students (id INTEGER PRIMARY KEY, name TEXT)";
stmt.executeUpdate(createTable);
String insertData = "INSERT INTO students (id, name)
VALUES (1, 'Rahul'), (2, 'Sneha')";
stmt.executeUpdate(insertData);
String selectData = "SELECT * FROM students";
ResultSet rs = stmt.executeQuery(selectData);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + " " + name);
}
conn.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Output.
33.Write a Java program in Java to create database table
using Java.

Sol.
import java.sql.*;

public class CreateTable {


public static void main(String[] args) {
try {
Class.forName("org.sqlite.JDBC");
Connection conn =
DriverManager.getConnection("jdbc:sqlite:students.db");
Statement stmt = conn.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS
students (id INTEGER PRIMARY KEY, name TEXT)";
stmt.executeUpdate(sql);
conn.close();
System.out.println("Table created successfully.");
} catch (Exception e) {
System.out.println(e);
}
}
}

Output.
34.Write a Java program in Java to insert, update, delete & select
records.

Sol.
import java.sql.*;
import java.util.Scanner;

public class CRUDExample {


public static void main(String[] args) {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:students.db");
Statement stmt = conn.createStatement();
Scanner sc = new Scanner(System.in);

System.out.println("1. Insert");
System.out.println("2. Update");
System.out.println("3. Delete");
System.out.println("4. Select");
System.out.print("Choose option: ");
int choice = sc.nextInt();
sc.nextLine();

if (choice == 1) {
System.out.print("Enter id: ");
int id = sc.nextInt();
sc.nextLine();
System.out.print("Enter name: ");
String name = sc.nextLine();
String sql = "INSERT INTO students (id, name) VALUES (" + id + ", '" +
name + "')";
stmt.executeUpdate(sql);
System.out.println("Record inserted.");
} else if (choice == 2) {
System.out.print("Enter id to update: ");
int id = sc.nextInt();
sc.nextLine();
System.out.print("Enter new name: ");
String name = sc.nextLine();
String sql = "UPDATE students SET name = '" + name + "' WHERE id = "
+ id;
stmt.executeUpdate(sql);
System.out.println("Record updated.");
} else if (choice == 3) {
System.out.print("Enter id to delete: ");
int id = sc.nextInt();
String sql = "DELETE FROM students WHERE id = " + id;
stmt.executeUpdate(sql);
System.out.println("Record deleted.");
} else if (choice == 4) {
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + " " + name);
}
} else {
System.out.println("Invalid option.");
}

conn.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Output.
35.Write Java program to read input from java console.
Sol.
import java.util.Scanner;

public class ConsoleInput {


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

System.out.print("Enter your name: ");


String name = sc.nextLine();

System.out.print("Enter your age: ");


int age = sc.nextInt();

System.out.println("Hello " + name + ", you are " + age + " years
old.");
}
}
Output.
36.Write a Java program to implement file handling(both
reading & writing to a file.

Sol.
import java.io.*;

public class FileHandlingExample {


public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt");
BufferedWriter bw = new BufferedWriter(writer);
bw.write("Hello, this is a test file.");
bw.newLine();
bw.write("This file is used for file handling example.");
bw.close();

FileReader reader = new FileReader("example.txt");


BufferedReader br = new BufferedReader(reader);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
}
}

Output.
37.Write a Java program on anonymous classes.

Sol.
public class AnonymousClassExample {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
System.out.println("This is an anonymous class!");
}
};
Thread t = new Thread(r);
t.start();
}
}

Output.

You might also like