0% found this document useful (0 votes)
14 views40 pages

Java With Coding

The document contains multiple Java programming exercises, each with algorithms and code implementations. It covers topics such as variable assignment, user input, class inheritance, method overloading, interfaces, exception handling, and thread synchronization. Each exercise includes sample outputs demonstrating the functionality of the code.

Uploaded by

Aravind
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)
14 views40 pages

Java With Coding

The document contains multiple Java programming exercises, each with algorithms and code implementations. It covers topics such as variable assignment, user input, class inheritance, method overloading, interfaces, exception handling, and thread synchronization. Each exercise includes sample outputs demonstrating the functionality of the code.

Uploaded by

Aravind
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/ 40

1. Write a java program to assign a value of 100.235 to a variable and then convert it to integer?

Algorithm:

1. Declare the Variables:


o Declare a variable of type double to store the value 100.235.
o Declare a variable of type int to store the converted integer value.
2. Assign the Value:
o Assign the value 100.235 to the double variable.
3. Convert the Value:
o Use type casting to convert the double value to an int.
4. Print the Results:
o Print the original double value and the converted int value.

public class DoubleToIntConversion {


public static void main(String[] args) {
// Step 1: Declare and assign the value
double doubleValue = 100.235;

// Step 2: Convert the double value to an integer using type casting


int intValue = (int) doubleValue;

// Step 3: Print the results


System.out.println("Original double value: " + doubleValue);
System.out.println("Converted integer value: " + intValue);
}
}

Output:

Original double value: 100.235


Converted integer value: 100

2. Write a Java program to get a number from the user and print whether it is positive or
negative?

Algorithm:

1. Start
2. Initialize Scanner object: Create a Scanner object to read input from the user.
3. Prompt for user input: Display a message asking the user to enter a number.
4. Read the number: Get the number input by the user using the Scanner object (use
nextDouble() for decimal numbers or nextInt() for integers).
5. Check the number:
o If the number is greater than 0, it is positive. Print "The number is positive."
o If the number is less than 0, it is negative. Print "The number is negative."
o If the number is equal to 0, it is neither positive nor negative. Print "The number
is zero."
6. End

import java.util.Scanner;

public class PositiveNegativeCheck {


public static void main(String[] args) {
// Create a Scanner object to get input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a number
System.out.print("Enter a number: ");

// Read the number input by the user


double number = scanner.nextDouble();

// Check if the number is positive, negative, or zero


if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}

// Close the scanner object


scanner.close();
}
}

Example Output:
Enter a number: -5
The number is negative.

3. Write a java program which contains


Class A {int i,j, void showij()}
Class B {int k, void showk(), void sum()}
(i) Display i,j values using showij()
(ii) Display k value using showk()
(iii) Display sum of i,j,k using sum()

Algorithm

1. Define Class A:
o Declare two integer variables i and j as data members.
o Define a method showij() to display the values of i and j.
2. Define Class B (Inherits from Class A):
o Extend Class A.
o Declare an integer variable k as a data member.
o Define a method showk() to display the value of k.
o Define a method sum() to calculate and display the sum of i, j, and k.
3. Main Method:
o Create an object of Class B.
o Assign values to i, j, and k through the object.
o Call the methods showij(), showk(), and sum() to display the required outputs.

Java Program
// Class A
class A {
int i, j; // Declare variables i and j

// Method to display values of i and j


void showij() {
System.out.println("i = " + i);
System.out.println("j = " + j);
}
}

// Class B (inherits from Class A)


class B extends A {
int k; // Declare variable k

// Method to display the value of k


void showk() {
System.out.println("k = " + k);
}

// Method to display the sum of i, j, and k


void sum() {
System.out.println("Sum of i, j, and k = " + (i + j + k));
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Create an object of class B
B obj = new B();

// Assign values to i, j, and k


obj.i = 10; // Value for i
obj.j = 20; // Value for j
obj.k = 30; // Value for k

// Call methods to display values and their sum


obj.showij(); // Display i and j
obj.showk(); // Display k
obj.sum(); // Display the sum of i, j, and k
}
}

Sample Output:

i = 10
j = 20
k = 30
Sum of i, j, and k = 60

4. Write a Java program which contains


Class A {int i,j, A(int a, int b), show()}
Class B{int k, B(int a, int b, int c), show()} derived from class A Create an object of class B and
call method show()

Algorithm

1. Define Class A:
o Declare two integer variables i and j.
o Define a constructor A(int a, int b) to initialize the variables i and j.
o Define a method show() to display the values of i and j.
2. Define Class B (Derived from Class A):
o Extend Class A using the extends keyword.
o Declare an integer variable k.
o Define a constructor B(int a, int b, int c):
 Call the superclass constructor A(a, b) to initialize i and j.
 Initialize the variable k.
o Override the show() method to:
 Call the superclass show() method to display i and j.
 Display the value of k.
3. Main Method:
o Create an object of class B using its constructor.
o Call the show() method of the object to display all the values.

Java Program
// Class A
class A {
int i, j; // Declare variables i and j

// Constructor to initialize i and j


A(int a, int b) {
i = a;
j = b;
}

// Method to display i and j


void show() {
System.out.println("i = " + i);
System.out.println("j = " + j);
}
}

// Class B (derived from Class A)


class B extends A {
int k; // Declare variable k

// Constructor to initialize i, j, and k


B(int a, int b, int c) {
super(a, b); // Call superclass constructor
k = c; // Initialize k
}

// Override the show method


@Override
void show() {
super.show(); // Call superclass show() to display i and j
System.out.println("k = " + k); // Display k
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Create an object of class B
B obj = new B(10, 20, 30);

// Call the show() method


obj.show();
}
}
Output:
i = 10
j = 20
k = 30

5. Write a Java program


Class overloaddemo{ void test(), void test(int a), void test(int a , int
b)} Classs overload{double result}
(i) Create an object of class overloaddemo and display test(), test(10), test(10,10)

Algorithm:

1. Define the overloaddemo class:


o Create three test methods with the following signatures:
 void test() - Prints a default message.
 void test(int a) - Prints the value of a.
 void test(int a, int b) - Prints the values of a and b.
2. Define another class overload:
o Declare a double variable named result.
o No specific methods are mentioned for this class, but it's included as a
placeholder.
3. Main method:
o Create an object of the overloaddemo class.
o Call the test methods using the object with different arguments:
 Call test() with no arguments.
 Call test(10) with one argument.
 Call test(10, 10) with two arguments.
4. Display the results:
o The output will showcase the method overloading in action.

Java Code:
class overloaddemo {
// Method with no parameters
void test() {
System.out.println("test() called - No parameters");
}

// Method with one parameter


void test(int a) {
System.out.println("test(int a) called - Parameter: " + a);
}

// Method with two parameters


void test(int a, int b) {
System.out.println("test(int a, int b) called - Parameters: " + a + ",
" + b);
}
}

class overload {
double result; // Placeholder class as per the description
}

public class Main {


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

// Call the test methods


obj.test(); // No arguments
obj.test(10); // Single argument
obj.test(10, 10); // Two arguments
}
}

Output:
test() called - No parameters
test(int a) called - Parameter: 10
test(int a, int b) called - Parameters: 10, 10

6.Write a java program Interface A{void meth1(), void meth2()} Interface B{void meth3()} extends
interface A Class myclass{void meth1(), void meth2(), void meth3()}
(i) Create an object of myclass and display meth1(), meth2(), meth3() (interface)

Algorithm

1. Define the Interface A:


o Declare two abstract methods: void meth1() and void meth2().
2. Define the Interface B:
o Extend interface A.
o Declare an additional abstract method: void meth3().
3. Define the class myclass:
o Implement interface B.
o Provide concrete definitions for the methods:
 meth1()
 meth2()
 meth3()
4. Main method:
o Create an object of the myclass class.
o Use the object to call and display the outputs of:
 meth1()
 meth2()
 meth3()

Java Code
// Define Interface A
interface A {
void meth1();
void meth2();
}

// Define Interface B, extending Interface A


interface B extends A {
void meth3();
}

// Define the myclass class that implements Interface B


class myclass implements B {
// Implement meth1
public void meth1() {
System.out.println("meth1() - Implementation in myclass");
}

// Implement meth2
public void meth2() {
System.out.println("meth2() - Implementation in myclass");
}

// Implement meth3
public void meth3() {
System.out.println("meth3() - Implementation in myclass");
}
}

// Main class to test the program


public class Main {
public static void main(String[] args) {
// Create an object of myclass
myclass obj = new myclass();

// Call and display the methods


obj.meth1();
obj.meth2();
obj.meth3();
}
}

Output
meth1() - Implementation in myclass
meth2() - Implementation in myclass
meth3() - Implementation in myclass

7.Write a Java program

Class exc2 {int a , d=0}

(i)Assign a value to variable a and then divide by variable d and display how division by zero is
handled

Algorithm

1. Define the class exc2:


o Declare two integer variables:
 a: Variable to hold an assigned value.
 d: Initialize to 0 to simulate a division-by-zero scenario.
2. Main method:
o Create an object of the exc2 class.
o Assign a value to the variable a.
o Use a try-catch block to handle the division by zero:
 In the try block, perform the division (a / d).
 In the catch block, catch the ArithmeticException and display a
message indicating that division by zero is not allowed.
3. Display the result:
o If division is successful, print the result.
o If division by zero occurs, print the error message.

Java Code
class exc2 {
int a; // Variable to hold the numerator
int d = 0; // Initialize denominator to 0

public static void main(String[] args) {


// Create an object of the exc2 class
exc2 obj = new exc2();

// Assign a value to variable 'a'


obj.a = 10;

// Handle division by zero using a try-catch block


try {
// Attempt to divide a by d
int result = obj.a / obj.d;
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
// Handle division by zero exception
System.out.println("Error: Division by zero is not allowed.");
}
}
}

Output
Error: Division by zero is not allowed.

8. Write a Java program


Class currentthreaddemo ( Thread t)

(i) Print the numbers 1 to 5 with thread sleep time of 1000 milliseconds

Algorithm

1. Define the currentthreaddemo class:


o Extend the Thread class.
o Define a constructor that initializes the thread (Thread t).
2. Override the run() method:
o Use a loop to iterate from 1 to 5.
o Print the current number.
o Pause the thread for 1000 milliseconds using Thread.sleep(1000).
3. Handle exceptions:
o Use a try-catch block around the Thread.sleep() method to handle the
InterruptedException.
4. Main method:
o Create an object of the currentthreaddemo class.
o Start the thread using the start() method.
Java Code
class currentthreaddemo extends Thread {
Thread t;

// Constructor to initialize the thread


public currentthreaddemo() {
t = new Thread(this, "Demo Thread");
System.out.println("Thread created: " + t);
}

// Override the run() method


public void run() {
try {
for (int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
// Sleep for 1000 milliseconds
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + e);
}
System.out.println("Thread exiting.");
}
}

public class Main {


public static void main(String[] args) {
// Create and start the thread
currentthreaddemo obj = new currentthreaddemo();
obj.start();
}
}

Output
Thread created: Thread[Demo Thread,5,main]

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Thread exiting.

9. Write a Java program Class callme{ void call( String msg)} Class caller{ String msg, callme obj, Thread
t, public caller(callme obj, String s), void run()} Class synch{object of caller class, Thread object}

(i) Synchronize the threads which is created by caller class with the callme class

Algorithm

1. Define the callme class:


o Implement a method void call(String msg) to display the message.
o Use the synchronized keyword on the call() method to ensure only one thread
can access it at a time.
2. Define the caller class:
o Declare variables:
 callme obj: An object of the callme class.
 String msg: A message to be passed to the call() method.
 Thread t: A thread object.
o Define a constructor caller(callme obj, String s):
 Initialize the callme object and the message.
 Start a new thread to invoke the run() method.
o Implement the run() method:
 Call the call() method of the callme class, passing the message.
3. Define the synch class:
o In the main() method:
 Create an object of the callme class.
 Create multiple caller objects, each with a separate thread, and pass the
callme object.
 Synchronize the threads using the synchronized block.
4. Run the Program:
o Ensure thread synchronization is achieved by allowing one thread to access the
call() method at a time.

Java Code
// Class callme
class callme {
// Synchronized call method
synchronized void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000); // Simulate delay
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}

// Class caller implementing Runnable


class caller implements Runnable {
String msg;
callme obj;
Thread t;

// Constructor
public caller(callme obj, String s) {
this.obj = obj;
this.msg = s;
t = new Thread(this);
t.start(); // Start the thread
}

// Run method
public void run() {
obj.call(msg); // Call the synchronized method
}
}

// Class synch (main class)


public class synch {
public static void main(String[] args) {
callme obj = new callme(); // Shared callme object

// Create multiple caller threads


caller obj1 = new caller(obj, "Hello");
caller obj2 = new caller(obj, "Synchronized");
caller obj3 = new caller(obj, "World");

// Wait for threads to finish


try {
obj1.t.join();
obj2.t.join();
obj3.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
System.out.println("All threads finished.");
}
}

Output
[Hello]
[Synchronized]
[World]
All threads finished.

10. Write a Java program


Class iteratordemo{ object of Arraylist}
(i) Add elements A,B,C,D,E,F to object of Arraylist
(ii) Iterate through all elements of Arraylist and display elements

Algorithm

1. Import required packages:


o Import java.util.ArrayList and java.util.Iterator to use the ArrayList
and its iterator.
2. Define the iteratordemo class:
o Declare an ArrayList object to hold the elements.
o Add elements A, B, C, D, E, and F to the ArrayList.
3. Iterate through the elements:
o Use an Iterator object to traverse the ArrayList.
o Use a while loop with the condition iterator.hasNext() to check if there are
more elements.
o Display each element using iterator.next().
4. Main method:
o Create an object of the iteratordemo class.
o Call the method to add elements and iterate through them.

Java Code
import java.util.ArrayList;
import java.util.Iterator;

class iteratordemo {
// Object of ArrayList
ArrayList<String> list;

// Constructor to initialize the ArrayList


public iteratordemo() {
list = new ArrayList<>();
}

// Method to add elements to the ArrayList


public void addElements() {
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
}

// Method to iterate through the elements and display them


public void displayElements() {
Iterator<String> iterator = list.iterator();
System.out.println("Elements in the ArrayList:");
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}

public class Main {


public static void main(String[] args) {
// Create an object of iteratordemo
iteratordemo demo = new iteratordemo();

// Add elements to the ArrayList


demo.addElements();

// Iterate and display elements


demo.displayElements();
}
}

Output
Elements in the ArrayList:
A
B
C
D
E
F

11. Write a Java program to get the element in a tree set and find less than or equal to the given
element of treeset
Treeset elements={12, 23,56,65,34,44}
Algorithm

1. Import the required package:


o Import java.util.TreeSet to use the TreeSet class.

2. Define the TreeSetDemo class:


o Create a TreeSet object to hold the elements.

3. Add elements to the TreeSet:


o Add the elements {12, 23, 56, 65, 34, 44} to the TreeSet.
o Note that TreeSet will automatically sort the elements in ascending order.

4. Find the element less than or equal to the given value:


o Use the floor() method of TreeSet to find the greatest element less than or equal to
the given value.

5. Main method:
o Create an object of the TreeSetDemo class.
o Add elements to the TreeSet.
o Take a user-defined value or test with a fixed value.
o Display the element less than or equal to the given value.

Java Code
import java.util.TreeSet;

public class TreeSetDemo {


public static void main(String[] args) {
// Create a TreeSet and add elements
TreeSet<Integer> treeSet = new TreeSet<>();
treeSet.add(12);
treeSet.add(23);
treeSet.add(56);
treeSet.add(65);
treeSet.add(34);
treeSet.add(44);

// Display the TreeSet


System.out.println("TreeSet elements: " + treeSet);

// Test value to find less than or equal


int testValue = 50; // You can change this value for testing

// Find and display the greatest element less than or equal to the
test value
Integer result = treeSet.floor(testValue);
if (result != null) {
System.out.println("Element less than or equal to " + testValue +
": " + result);
} else {
System.out.println("No element less than or equal to " + testValue
+ " found.");
}
}
}
Output

Example 1: For testValue = 50:

TreeSet elements: [12, 23, 34, 44, 56, 65]


Element less than or equal to 50: 44

Example 2: For testValue = 10:


TreeSet elements: [12, 23, 34, 44, 56, 65]
No element less than or equal to 10 found.

12. Write a Java Program


Class STdemo{static String}
(i) Assign String “my college name is matrusri” to static String
(ii) Display the tokens of String

Algorithm

1. Import Required Package:


o Import java.util.StringTokenizer to use the StringTokenizer class.
2. Define the STdemo class:
o Declare a static String variable.
o Assign the value "my college name is matrusri" to the static String.
3. Tokenize the String:
o Use the StringTokenizer class to split the string into tokens.
o Specify the delimiter as a space (" ") to split words.
4. Iterate Through Tokens:
o Use a while loop with the condition tokenizer.hasMoreTokens() to check for
remaining tokens.
o Print each token using tokenizer.nextToken().
5. Main Method:
o Call the tokenization logic and display the tokens.

Java Code
import java.util.StringTokenizer;

class STdemo {
// Static string
static String sentence = "my college name is matrusri";

public static void main(String[] args) {


// Display the original string
System.out.println("Original String: " + sentence);

// Tokenize the string using StringTokenizer


StringTokenizer tokenizer = new StringTokenizer(sentence, " ");

// Display the tokens


System.out.println("Tokens:");
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
}
}

Output
Original String: my college name is matrusri
Tokens:
my
college
name
is
matrusri

13. Write a Java program calculate the first and last day of each week of current month
Class Datedemo(date method)

(i) Display the first and last day of each week of current month

Algorithm

1. Import Required Packages:


o Import java.time.LocalDate, java.time.temporal.TemporalAdjusters, and
java.time.DayOfWeek.
2. Define the Datedemo Class:
o Create a method dateMethod() to handle the date calculations.
3. Get the Current Month:
o Use LocalDate.now() to get the current date.
o Extract the year and month.
4. Iterate Over the Weeks:
o Find the first day of the current month using LocalDate.withDayOfMonth(1).
o Use a loop to calculate each week’s first and last day:
 Start from the first day of the current month.
 Add 7 days in each iteration to move to the next week.
5. Adjust for Week Boundaries:
o Calculate the first day of the week using with(DayOfWeek.MONDAY).
o Calculate the last day of the week using with(DayOfWeek.SUNDAY).
6. Stop the Loop:
o Stop when the first day of the week moves past the last day of the month.
7. Display Results:
o Print the first and last day of each week.
8. Main Method:
o Call the dateMethod() to display the results.

Java Code
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;

class Datedemo {
public void dateMethod() {
// Get the current date and the first day of the month
LocalDate now = LocalDate.now();
LocalDate firstDayOfMonth = now.withDayOfMonth(1);
LocalDate lastDayOfMonth =
now.with(TemporalAdjusters.lastDayOfMonth());

System.out.println("Current Month: " + now.getMonth());


System.out.println("Weeks:");

// Start iterating from the first day of the month


LocalDate current = firstDayOfMonth;

while (!current.isAfter(lastDayOfMonth)) {
// Calculate the first day of the week
LocalDate startOfWeek = current.with(DayOfWeek.MONDAY);
// Calculate the last day of the week
LocalDate endOfWeek = current.with(DayOfWeek.SUNDAY);

// Ensure the start and end dates are within the month
if (startOfWeek.isBefore(firstDayOfMonth)) {
startOfWeek = firstDayOfMonth;
}
if (endOfWeek.isAfter(lastDayOfMonth)) {
endOfWeek = lastDayOfMonth;
}

// Display the week range


System.out.println("Week: " + startOfWeek + " to " + endOfWeek);

// Move to the next week


current = current.plusDays(7);
}
}

public static void main(String[] args) {


Datedemo demo = new Datedemo();
demo.dateMethod();
}
}

Output

For February 2025 (assuming today's date is in February 2025):

Current Month: FEBRUARY


Weeks:
Week: 2025-02-01 to 2025-02-02
Week: 2025-02-03 to 2025-02-09
Week: 2025-02-10 to 2025-02-16
Week: 2025-02-17 to 2025-02-23
Week: 2025-02-24 to 2025-02-29

14. Write a Java program to sort given list of strings in alphabetical order, ascending and
descending order for Arrays.asList("Red", "Green", "Blue", "Pink", "Brown")

Algorithm

1. Import Required Package:


o Import java.util.Arrays and java.util.Collections to handle sorting
operations.
2. Define the SortStringsDemo Class:
o Create a method sortStrings() to perform sorting.

3. Initialize the List:


o Use Arrays.asList() to initialize the list of strings with the values "Red", "Green",
"Blue", "Pink", and "Brown".

4. Sort in Ascending Order:


o Use the Collections.sort() method to sort the list in ascending (default) order.

5. Sort in Descending Order:


o Use the Collections.sort() method with Collections.reverseOrder() to sort
the list in descending order.

6. Display the Results:


o Print the list after sorting in ascending and descending order.

7. Main Method:
o Call the sortStrings() method to execute the logic.

Java Code
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SortStringsDemo {


public static void sortStrings() {
// Initialize the list of strings
List<String> colors = Arrays.asList("Red", "Green", "Blue", "Pink",
"Brown");

// Display the original list


System.out.println("Original List: " + colors);

// Sort in ascending order


Collections.sort(colors);
System.out.println("Sorted in Ascending Order: " + colors);

// Sort in descending order


Collections.sort(colors, Collections.reverseOrder());
System.out.println("Sorted in Descending Order: " + colors);
}

public static void main(String[] args) {


sortStrings();
}
}

Output

Before Sorting:
Original List: [Red, Green, Blue, Pink, Brown]
After Sorting in Ascending Order:
Sorted in Ascending Order: [Blue, Brown, Green, Pink, Red]

After Sorting in Descending Order:


Sorted in Descending Order: [Red, Pink, Green, Brown, Blue]

15. Write a Java program that reads a file name from the user, and then displays information
about whether the file exists, whether the file is readable, whether the file is writable, the type of
file and the length of the file in bytes.

Algorithm

1. Import Required Package:


o Import java.io.File to handle file operations.

2. Define the FileInfo Class:


o Create a method checkFile() to perform file checks.

3. Get File Name from the User:


o Use Scanner to read the file name from the user.

4. Create a File Object:


o Use the File class to create an object representing the file.

5. Check File Properties:


o Check if the file exists using the exists() method.
o Check if the file is readable using the canRead() method.
o Check if the file is writable using the canWrite() method.
o Determine the type of file by checking the file extension (substring of the file name).
o Get the length of the file in bytes using the length() method.

6. Display File Information:


o Print the results of the checks and properties.

7. Main Method:
o Call the checkFile() method to execute the logic.

Java Code
import java.io.File;
import java.util.Scanner;

public class FileInfo {


public static void checkFile() {
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a file name


System.out.print("Enter the file name with path: ");
String fileName = scanner.nextLine();
// Create a File object
File file = new File(fileName);

// Display file information


if (file.exists()) {
System.out.println("File exists: Yes");
System.out.println("Readable: " + (file.canRead() ? "Yes" :
"No"));
System.out.println("Writable: " + (file.canWrite() ? "Yes" :
"No"));

// Get file type (extension)


String fileType = fileName.contains(".")
? fileName.substring(fileName.lastIndexOf(".") + 1)
: "Unknown";
System.out.println("File type: " + fileType);

// Get file length


System.out.println("File length (bytes): " + file.length());
} else {
System.out.println("File does not exist.");
}

scanner.close();
}

public static void main(String[] args) {


checkFile();
}
}

Output

Case 1: File Exists


Enter the file name with path: test.txt
File exists: Yes
Readable: Yes
Writable: Yes
File type: txt
File length (bytes): 123

Case 2: File Does Not Exist


Enter the file name with path: non_existing_file.txt
File does not exist.

16. Write a java program


Class myclass(string s, int I , myclass constructor, tostring()) Class serializedemo{ myclass obj,
FileInputStream obj, ObjectOutputStream obj}
(i) Serialize the objects of file input stream and object output stream

Algorithm

1. Import Required Packages:


o Import java.io.* to handle serialization and deserialization.

2. Define the myclass Class:


o Implement Serializable interface to make the class serializable.
o Define properties: String s and int i.
o Create a constructor to initialize the properties.
o Override the toString() method to display object information.

3. Define the serializedemo Class:


o Create an object of myclass.
o Serialize the object to a file using FileOutputStream and ObjectOutputStream.
o Deserialize the object from the file using FileInputStream and
ObjectInputStream.

4. Serialize the Object:


o Use ObjectOutputStream to write the object to a file.

5. Deserialize the Object:


o Use ObjectInputStream to read the object from the file.

6. Main Method:
o Call the serialization and deserialization logic, and display the results.

Java Code
import java.io.*;

// Define the myclass class


class myclass implements Serializable {
private String s;
private int i;

// Constructor
public myclass(String s, int i) {
this.s = s;
this.i = i;
}

// Override toString method


@Override
public String toString() {
return "myclass [s=" + s + ", i=" + i + "]";
}
}

// Define the serializedemo class


public class serializedemo {
public static void main(String[] args) {
// Create an object of myclass
myclass obj = new myclass("Hello, World!", 42);

// File to store serialized data


String filename = "myclass.ser";

// Serialization
try (FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
// Serialize the object
oos.writeObject(obj);
System.out.println("Object has been serialized: " + obj);
} catch (IOException e) {
e.printStackTrace();
}
// Deserialization
try (FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis)) {
// Deserialize the object
myclass deserializedObj = (myclass) ois.readObject();
System.out.println("Object has been deserialized: " +
deserializedObj);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}

Output

Serialization Phase:
Object has been serialized: myclass [s=Hello, World!, i=42]

Deserialization Phase:
Object has been deserialized: myclass [s=Hello, World!, i=42]

17. Write a Java program to print as shown below(menu handling, awt)

Algorithm

1. Set Up the Frame


o Import the required AWT and event-handling packages.
o Create a Frame to serve as the main application window.
2. Create the Menu Bar
o Create a MenuBar object to hold the menus.
o Set this menu bar on the Frame.
3. Create the Menus
o Create a Menu object for the main menu.
o Add menu items (MenuItem) to the main menu.
o Create a sub-menu (Menu) and add it as a menu item to the main menu.
4. Add Items to the Sub-Menu
o Add additional menu items to the sub-menu.
5. Add Action Listeners
o Attach ActionListener objects to the menu items to handle user actions (e.g.,
clicks).
6. Display the Frame
o Set the frame size and make it visible.
(Key Notes

1. Packages Used:
o java.awt for GUI components.
o java.awt.event for event handling.
2. Event Handling:
o ActionListener is used for handling menu item clicks.
o WindowAdapter is used for handling the close button event.
3. Customization:
o You can add additional styles and functionality as needed.)

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

public class MenuExample {


public static void main(String[] args) {
// Create a Frame
Frame frame = new Frame("Menu and MenuItem Example");

// Create a MenuBar
MenuBar menuBar = new MenuBar();

// Create the main menu


Menu menu = new Menu("Menu");

// Create menu items for the main menu


MenuItem item1 = new MenuItem("Item 1");
MenuItem item2 = new MenuItem("Item 2");
MenuItem item3 = new MenuItem("Item 3");

// Add menu items to the main menu


menu.add(item1);
menu.add(item2);
menu.add(item3);

// Create a sub-menu
Menu subMenu = new Menu("Sub Menu");

// Create menu items for the sub-menu


MenuItem subItem1 = new MenuItem("Item 4");
MenuItem subItem2 = new MenuItem("Item 5");

// Add menu items to the sub-menu


subMenu.add(subItem1);
subMenu.add(subItem2);

// Add the sub-menu to the main menu


menu.add(subMenu);

// Add the main menu to the menu bar


menuBar.add(menu);

// Set the menu bar to the frame


frame.setMenuBar(menuBar);

// Add action listeners to menu items


item1.addActionListener(e -> System.out.println("Item 1 clicked"));
item2.addActionListener(e -> System.out.println("Item 2 clicked"));
item3.addActionListener(e -> System.out.println("Item 3 clicked"));
subItem1.addActionListener(e -> System.out.println("Item 4 clicked"));
subItem2.addActionListener(e -> System.out.println("Item 5 clicked"));
// Set frame size and make it visible
frame.setSize(400, 300);
frame.setVisible(true);

// Add window listener to close the frame


frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
frame.dispose();
}
});
}
}

Ouput:

18. Write a Java program


Class ellipses{ graphics obj } Create an applet with name elipses Draw filled circle with graphics

Algorithm

1. Import Necessary Packages


o Import the java.applet.* and java.awt.* packages for creating applets and
drawing graphics.
2. Create the Class
o Define a public class named Ellipses that extends Applet.
3. Override the paint Method
o Inside the Ellipses class, override the paint(Graphics g) method.
o Use the Graphics object (g) to draw shapes.
4. Draw a Filled Circle
o Use the fillOval method of the Graphics object to draw a filled circle.
o Ensure that the width and height of the oval are equal to make it a circle.
5. Set Applet Size
o Set the size of the applet window using the setSize method.
6. Compile and Run
o Compile the program and use an HTML file to run the applet.

(Key Points

1. Graphics Methods:
o fillOval(int x, int y, int width, int height): Draws a filled oval
bounded by a rectangle. If width == height, the oval becomes a circle.
2. Colors:
o Use g.setColor(Color.<color_name>) to set the color before drawing.
3. Applets:
Applets are deprecated in newer versions of Java. If you are using a modern
o
environment, consider using Swing with JApplet or JPanel.
4. Compile and Run:
o Compile the Ellipses.java file and place the .class file in the same directory
as the HTML file.
o Open the HTML file in a browser that supports Java Applets or use an applet
viewer (like appletviewer).)

(HTML File to Run the Applet


Create an HTML file with the following code to embed and run the applet:
html
CopyEdit
<!DOCTYPE html>
<html>
<head>
<title>Ellipses Applet</title>
</head>
<body>
<applet code="Ellipses.class" width="400" height="400"></applet>
</body>
</html>)

import java.applet.Applet;
import java.awt.*;

public class Ellipses extends Applet {

// Set up the applet window


public void init() {
setSize(400, 400); // Set the size of the applet window
}

// Override the paint method


public void paint(Graphics g) {
// Set the color for the filled circle
g.setColor(Color.PINK);

// Draw a filled circle (fillOval with equal width and height)


g.fillOval(100, 100, 200, 200); // x, y, width, height
}
}
19.Write a Java program Class simplekey { String msg, void init(), keyPressed(), keyReleased(),
keyTyped() } i. Implement KeyListener interface with KeyEvent (event handling)

Algorithm

1. Import Necessary Packages


o Import java.awt.* for GUI components.
o Import java.awt.event.* for event handling (KeyEvent and KeyListener).
2. Create the Class
o Create a class named SimpleKey that extends Frame and implements the
KeyListener interface.
3. Define Variables
o Declare a String variable msg to display key event information.
4. Set Up the Frame
o In the init() method:
 Initialize the Frame by setting its size, layout, and visibility.
 Register the KeyListener for the frame by using
addKeyListener(this).
5. Override KeyListener Methods
o Implement the methods from the KeyListener interface:
 keyPressed(KeyEvent e): Called when a key is pressed.
 keyReleased(KeyEvent e): Called when a key is released.
 keyTyped(KeyEvent e): Called when a key is typed.
6. Handle Events
o Update the msg variable with appropriate event details in each method.
o Use repaint() to refresh the frame and display the updated message.
7. Override the paint Method
o Use the Graphics object to display the msg string.
8. Set Up Main Method
o Create an instance of the SimpleKey class and call the init() method.
9. Handle Frame Closing
o Add a WindowListener to close the frame when the user clicks the close button.

Keypoints:

1. KeyListener Methods:
o keyPressed(KeyEvent e): Handles the event when a key is pressed.
o keyReleased(KeyEvent e): Handles the event when a key is released.
o keyTyped(KeyEvent e): Handles the event when a key is typed (produces
a
Unicode character).
2. Repainting:
o Use repaint() to call the paint() method and refresh the GUI with updated
messages.
3. Frame and Event Handling:
o The Frame acts as the main window.
o Use addKeyListener() to register the KeyListener.
4. Window Closing:
o Use a WindowListener to close the frame gracefully.
Sample Code

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

public class SimpleKey extends Frame implements KeyListener {


String msg = ""; // Message to display key events

// Initialize the frame


public void init() {
setSize(400, 300); // Set frame size
setLayout(null); // Use no layout manager
setVisible(true); // Make frame visible
addKeyListener(this); // Register KeyListener
}

// Key pressed event handler


@Override
public void keyPressed(KeyEvent e) {
msg = "Key Pressed: " + e.getKeyChar();
repaint(); // Refresh the frame
}

// Key released event handler


@Override
public void keyReleased(KeyEvent e) {
msg = "Key Released: " + e.getKeyChar();
repaint(); // Refresh the frame
}

// Key typed event handler


@Override
public void keyTyped(KeyEvent e) {
msg = "Key Typed: " + e.getKeyChar();
repaint(); // Refresh the frame
}

// Override paint to display messages


@Override
public void paint(Graphics g) {
g.drawString(msg, 50, 150); // Draw the message on the frame
}

// Main method
public static void main(String[] args) {
SimpleKey keyApp = new SimpleKey();
keyApp.init();

// Handle window closing


keyApp.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}

Output:
Key Pressed: t

Key Released: t
Key Typed: t

20. Write a Java program that works as a simple calculator. Use a grid to arrange buttons for the
digits and for the+,-,*,% operations. Add a TextField to display the result shown below(layout
manager)

Algorithm for Calculator Program

1. Initialize the Application Window


o Create a JFrame with a suitable title (e.g., "Simple Calculator").
o Set its size and default close operation.

2. Add a Display Field


o Create a JTextField to display the current input and results.
o Set properties like alignment, font, and make it non-editable.

3. Create Buttons for Calculator


o Define an array of strings containing button labels: digits (0–9) and operations (+, -, *, /,
%, =, C).
o Use a JPanel with a GridLayout to organize these buttons.

4. Add Buttons to the Panel


o For each label in the array, create a JButton with that text.
o Add each button to the grid panel.

5. Add Action Listeners to Buttons


o Implement logic for different types of buttons:
 Digits (0–9): Append to the text in the JTextField.
 *Operations (+, -, , /, %): Store the current number and selected operation.
 Equals (=): Perform the calculation using the stored operator and operands.
 Clear (C): Reset the JTextField and clear all variables.

6. Add Components to the Frame


o Use a BorderLayout for the JFrame.
o Place the JTextField in the NORTH region.
o Place the button panel in the CENTER region.

7. Handle Arithmetic Logic


o Parse the inputs from the JTextField for operations.
o Perform calculations based on the operator stored.

8. Display the Result


o Update the JTextField with the result of the calculation.

9. Test the Program


o Compile and run the program. Ensure buttons and operations work as expected.

Key Java Concepts Used

1. Swing Components
o JFrame, JPanel, JButton, JTextField.

2. Layout Managers
o GridLayout for buttons, BorderLayout for the overall layout.

3. Event Handling
o Add ActionListener to handle button clicks.

4. Arithmetic Operations
o Handle addition, subtraction, multiplication, division, and modulus operations.

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

public class Calculator {


public static void main(String[] args) {
JFrame frame = new JFrame("Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 500);

// Create a text field to display the result


JTextField textField = new JTextField();
textField.setHorizontalAlignment(JTextField.RIGHT);
textField.setEditable(false);
textField.setFont(new Font("Arial", Font.BOLD, 24));

// Create a panel for buttons with GridLayout


JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 5, 5));

// Add buttons for digits and operations


String[] buttons = {
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"C", "0", "=", "/"
};

for (String text : buttons) {


JButton button = new JButton(text);
button.setFont(new Font("Arial", Font.BOLD, 20));
buttonPanel.add(button);

// Add action listeners


button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
handleButtonClick(command, textField);
}
});
}

// Add text field and button panel to frame


frame.setLayout(new BorderLayout(5, 5));
frame.add(textField, BorderLayout.NORTH);
frame.add(buttonPanel, BorderLayout.CENTER);

frame.setVisible(true);
}

private static void handleButtonClick(String command, JTextField


textField) {
static String operator = "";
static String operand1 = "";
static boolean reset = false;

if (reset) {
textField.setText("");
reset = false;
}

if ("0123456789".contains(command)) {
textField.setText(textField.getText() + command);
} else if ("+-*/".contains(command)) {
operator = command;
operand1 = textField.getText();
textField.setText("");
} else if ("=".equals(command)) {

Output:

21. Write a java program


Class adapterdemo{ void init(), add MouseListener} Class mymouse adapter{ mymouseadapter,
adappterdemo obj}
i)Implement MouseListerner Interface(adapter class)

Algorithm

Step 1: Define the Main Class (AdapterDemo)

1. Create the class AdapterDemo.


o Add necessary imports (java.awt.*, javax.swing.*, and java.awt.event.*).

2. Initialize the GUI Components:


o Define a method void init() that:
 Creates a JFrame.
 Sets size, title, and layout.
 Adds a JPanel or similar component as the GUI container.

3. Add MouseListener to the Component:


o Create an instance of MyMouseAdapter, passing the AdapterDemo object (if needed).
o Attach the MouseAdapter instance to a component using addMouseListener().

Step 2: Define the Mouse Adapter Class (MyMouseAdapter)

1. Create a class MyMouseAdapter.


o Extend the MouseAdapter class (an adapter for the MouseListener interface).

2. Constructor of MyMouseAdapter:
o Accept an AdapterDemo object as a parameter and store it in an instance variable (if
needed for context).

3. Override Relevant Methods:


o Override one or more methods from MouseAdapter (e.g., mouseClicked,
mouseEntered, mouseExited, mousePressed, mouseReleased).

Step 3: Implement Event Handling Logic

1. In MyMouseAdapter, implement event-specific logic:


o For example, when mouseClicked is triggered, print a message or update a GUI
component.
2. In AdapterDemo, handle initialization and launch the GUI.

Step 4: Test the Program

1. Compile and run the program.


2. Verify that the MouseListener triggers the overridden methods in MyMouseAdapter.

Key Components

1. MouseListener Interface
o Contains methods for mouse events: mouseClicked, mouseEntered, mouseExited,
mousePressed, and mouseReleased.

2. MouseAdapter Class
o An abstract class with default (empty) implementations of MouseListener methods.
Allows overriding only necessary methods.

3. Swing Components
o JFrame, JPanel, and addMouseListener().
1. AdapterDemo Class:
o Creates the main GUI using JFrame and JPanel.
o Initializes a JLabel to display messages based on mouse events.
o Adds a MouseListener to the panel using the MyMouseAdapter class.

2. MyMouseAdapter Class:
o Extends MouseAdapter to override only the necessary methods (mouseClicked,
mouseEntered, mouseExited, etc.).
o Updates the label in the GUI to display messages when mouse actions are performed.

3. Event Handling:
o The MouseAdapter class simplifies implementing the MouseListener interface by
allowing you to override only the methods you need.

Working Mechanism of the Program

1. When you run the program, a window (JFrame) is displayed with a panel and a label.
2. The label updates with messages when you:
o Click: Displays the click position.
o Enter: Indicates the mouse entered the panel.
o Exit: Indicates the mouse exited the panel.
o Press: Displays the press position.

Release: Displays the release position

Output: (Note: Color may Vary based on program specification)

Java Program

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

// Main class to initialize GUI


public class AdapterDemo {
public static void main(String[] args) {
// Create an instance of AdapterDemo
new AdapterDemo().init();
}

// Method to initialize the GUI


public void init() {
// Create a JFrame
JFrame frame = new JFrame("AdapterDemo - MouseListener Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a JPanel
JPanel panel = new JPanel();
panel.setBackground(Color.LIGHT_GRAY);
// Add a label to show messages
JLabel label = new JLabel("Perform mouse actions on the panel",
JLabel.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 14));
label.setForeground(Color.BLACK);
panel.add(label);

// Add MouseListener using MyMouseAdapter


MyMouseAdapter mouseAdapter = new MyMouseAdapter(this, label);
panel.addMouseListener(mouseAdapter);

// Add panel to the frame


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

// Adapter class to handle MouseListener events


class MyMouseAdapter extends MouseAdapter {
private AdapterDemo adapterDemo; // Reference to the main class (if
needed)
private JLabel label; // Label to update messages

// Constructor
public MyMouseAdapter(AdapterDemo adapterDemo, JLabel label) {
this.adapterDemo = adapterDemo;
this.label = label;
}

// Override mouseClicked method


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

// Override mouseEntered method


@Override
public void mouseEntered(MouseEvent e) {
label.setText("Mouse entered the panel!");
}

// Override mouseExited method


@Override
public void mouseExited(MouseEvent e) {
label.setText("Mouse exited the panel!");
}

// Override mousePressed method


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

// Override mouseReleased method


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

22.Write a java program


Class Jlabledemo{ void init(), object of Jlabel } (i)Create label for initiated component

Algorithm

Step 1: Define the Main Class (JLabelDemo)

1. Import Necessary Packages:


o Import javax.swing.* for Swing components.
o Import java.awt.* if additional layout or styling is required.

2. Define the JLabelDemo Class:


o Create a public class named JLabelDemo.

3. Create the init() Method:


o Define a void init() method to set up the GUI.

Step 2: Initialize the GUI

1. Create a JFrame:
o Instantiate a JFrame object with a suitable title.
o Set the frame size and default close operation.

2. Create a JPanel (Optional):


o Use a JPanel to hold the components.
o Set the layout of the panel (e.g., FlowLayout or BorderLayout).

3. Create a JLabel:
o Instantiate a JLabel object to display a string, an image, or both.
o Use the JLabel constructor to specify:
 Text (e.g., "Hello, World!")
 An image icon (optional).

4. Customize the JLabel:


o Set font, alignment, foreground color, background color, etc., for the label (optional).

5. Add the JLabel to the Frame or Panel:


o Add the label to the JPanel or directly to the JFrame.

Step 3: Display the Frame

1. Set the Frame Visible:


o Call frame.setVisible(true) to make the GUI appear on the screen.

Step 4: Test the Program

1. Compile and run the program.


2. Verify that the JLabel appears with the specified text or image.

Key Swing Components

1. JLabel: Displays static text, images, or both.


o Constructor:
 JLabel(String text)
 JLabel(Icon icon)
 JLabel(String text, Icon icon, int alignment)

2. JFrame: The main application window.


3. JPanel: A container for organizing components.

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

public class JLabelDemo {


public static void main(String[] args) {
// Create an instance of JLabelDemo
new JLabelDemo().init();
}

// Method to initialize the GUI


public void init() {
// Create a JFrame
JFrame frame = new JFrame("JLabel Demo");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a JPanel
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout()); // Use FlowLayout for alignment

// Create a JLabel with text


JLabel textLabel = new JLabel("Hello, welcome to JLabel Demo!");
textLabel.setFont(new Font("Arial", Font.BOLD, 16)); // Set font
textLabel.setForeground(Color.BLUE); // Set text color

// Create a JLabel with an image


ImageIcon icon = new ImageIcon("path_to_your_image_file.jpg"); //
Provide the path to an image
JLabel imageLabel = new JLabel(icon);

// Create a JLabel with both text and image


JLabel combinedLabel = new JLabel("JLabel with text and image", icon,
JLabel.CENTER);
combinedLabel.setFont(new Font("Arial", Font.PLAIN, 14)); // Set font
combinedLabel.setHorizontalTextPosition(SwingConstants.CENTER); //
Text below the image
combinedLabel.setVerticalTextPosition(SwingConstants.BOTTOM);

// Add the labels to the panel


panel.add(textLabel);
panel.add(imageLabel);
panel.add(combinedLabel);

// Add the panel to the frame


frame.add(panel);

// Make the frame visible


frame.setVisible(true);
}
}

Explanation

1. JLabelDemo Class:
o Contains the init() method to set up the GUI.
o The main() method creates an instance of the class and invokes init().

2. JFrame:
o The main application window with a title "JLabel Demo".
o Contains a JPanel to organize components.

3. JLabel:
o Text Label: Displays the message "Hello, welcome to JLabel Demo!" with customized
font and color.
o Image Label: Displays an image loaded from the file path.
o Combined Label: Displays text and an image together, with the text positioned below
the image.

4. Layout:
o The FlowLayout organizes components in a flow, aligned horizontally.

5. Customization:
o Font, text color, text position, and alignment are set for labels.

Steps to Run the Program

1. Save the program as JLabelDemo.java.


2. Replace "path_to_your_image_file.jpg" with the actual path to an image file on your
system.
3. Compile the program using:

javac JLabelDemo.java

4. Run the program using:

java JLabelDemo

Expected Output

1. A window with the title "JLabel Demo" opens.


2. It contains:
o A label with blue text saying "Hello, welcome to JLabel Demo!"
o An image displayed as a label.
o A label combining text and the same image.

23. Write a Java program to implement CURD operations for student database with
attributes create table student(Id int, Name VARCHAR(33), class VARCHAR (12), age int)
a. Insert record into database
b. Select record from database
c. Update record from database
d. Delete a record from database

Algorithm to Write a Java Program for CRUD Operations on Student Database

To create a Java program that performs CRUD (Create, Read, Update, Delete) operations on a
student database table with attributes:
 Id (int)
 Name (VARCHAR(33))
 Class (VARCHAR(12))
 Age (int)

Step 1: Import Required Packages

1. Import java.sql.* for database connectivity.


2. Import java.util.Scanner to accept input from the user.

Step 2: Establish a Database Connection

1. Load the JDBC driver using Class.forName().


2. Establish a connection to the database using DriverManager.getConnection().

Step 3: Create the Student Table (if not already exists)

1. Execute an SQL query to create the student table:

CREATE TABLE student(


Id INT PRIMARY KEY,
Name VARCHAR(33),
Class VARCHAR(12),
Age INT
);

Step 4: Perform CRUD Operations

a. Insert a Record into the Database

1. Use a PreparedStatement with an SQL INSERT query:

INSERT INTO student (Id, Name, Class, Age) VALUES (?, ?, ?, ?);

2. Accept user input for Id, Name, Class, and Age.

b. Select a Record from the Database

1. Use an SQL SELECT query to fetch all or specific student records:

SELECT * FROM student WHERE Id = ?;

c. Update a Record in the Database

1. Use a PreparedStatement with an SQL UPDATE query:

UPDATE student SET Name = ?, Class = ?, Age = ? WHERE Id = ?;

2. Accept user input for the fields to be updated.

d. Delete a Record from the Database

1. Use a PreparedStatement with an SQL DELETE query:

DELETE FROM student WHERE Id = ?;


Step 5: Display a Menu for CRUD Operations

1. Create a menu using a while loop to allow users to choose between:


o Insert
o Select
o Update
o Delete
o Exit
2. Call the appropriate methods for each operation.

Step 6: Close Resources

1. Close the Connection, PreparedStatement, and ResultSet objects after use.

Java Program
import java.sql.*;
import java.util.Scanner;

public class StudentCRUD {

// Database connection details


static final String DB_URL =
"jdbc:mysql://localhost:3306/your_database_name"; // Replace with your DB URL
static final String USER = "your_username"; // Replace with your DB
username
static final String PASS = "your_password"; // Replace with your DB
password

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

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


PASS)) {
// Create table if it does not exist
createTableIfNotExists(conn);

boolean exit = false;

while (!exit) {
// Display menu
System.out.println("\n==== Student Database Menu ====");
System.out.println("1. Insert Record");
System.out.println("2. Select Record");
System.out.println("3. Update Record");
System.out.println("4. Delete Record");
System.out.println("5. Exit");
System.out.print("Choose an option: ");

int choice = scanner.nextInt();

switch (choice) {
case 1:
insertRecord(conn, scanner);
break;
case 2:
selectRecord(conn, scanner);
break;
case 3:
updateRecord(conn, scanner);
break;
case 4:
deleteRecord(conn, scanner);
break;
case 5:
exit = true;
break;
default:
System.out.println("Invalid option! Please choose
again.");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}

// Method to create the student table if it does not exist


private static void createTableIfNotExists(Connection conn) throws
SQLException {
String createTableSQL = "CREATE TABLE IF NOT EXISTS student (" +
"Id INT PRIMARY KEY, " +
"Name VARCHAR(33), " +
"Class VARCHAR(12), " +
"Age INT)";
try (Statement stmt = conn.createStatement()) {
stmt.execute(createTableSQL);
}
}

// Method to insert a record into the database


private static void insertRecord(Connection conn, Scanner scanner) throws
SQLException {
System.out.print("Enter Student ID: ");
int id = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter Student Name: ");
String name = scanner.nextLine();
System.out.print("Enter Student Class: ");
String studentClass = scanner.nextLine();
System.out.print("Enter Student Age: ");
int age = scanner.nextInt();

String insertSQL = "INSERT INTO student (Id, Name, Class, Age) VALUES
(?, ?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(insertSQL)) {
pstmt.setInt(1, id);
pstmt.setString(2, name);
pstmt.setString(3, studentClass);
pstmt.setInt(4, age);
pstmt.executeUpdate();
System.out.println("Record inserted successfully!");
}
}

// Method to select a record from the database


private static void selectRecord(Connection conn, Scanner scanner) throws
SQLException {
System.out.print("Enter Student ID to search (or 0 to display all
records): ");
int id = scanner.nextInt();

String selectSQL = (id == 0) ? "SELECT * FROM student" : "SELECT *


FROM student WHERE Id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(selectSQL)) {
if (id != 0) {
pstmt.setInt(1, id);
}
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("ID: " + rs.getInt("Id") +
", Name: " + rs.getString("Name") +
", Class: " + rs.getString("Class") +
", Age: " + rs.getInt("Age"));
}
}
}

// Method to update a record in the database


private static void updateRecord(Connection conn, Scanner scanner) throws
SQLException {
System.out.print("Enter Student ID to update: ");
int id = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter New Name: ");
String name = scanner.nextLine();
System.out.print("Enter New Class: ");
String studentClass = scanner.nextLine();
System.out.print("Enter New Age: ");
int age = scanner.nextInt();

String updateSQL = "UPDATE student SET Name = ?, Class = ?, Age = ?


WHERE Id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(updateSQL)) {
pstmt.setString(1, name);
pstmt.setString(2, studentClass);
pstmt.setInt(3, age);
pstmt.setInt(4, id);
int rowsUpdated = pstmt.executeUpdate();
if (rowsUpdated > 0) {
System.out.println("Record updated successfully!");
} else {
System.out.println("Record not found!");
}
}
}

// Method to delete a record from the database


private static void deleteRecord(Connection conn, Scanner scanner) throws
SQLException {
System.out.print("Enter Student ID to delete: ");
int id = scanner.nextInt();

String deleteSQL = "DELETE FROM student WHERE Id = ?";


try (PreparedStatement pstmt = conn.prepareStatement(deleteSQL)) {
pstmt.setInt(1, id);
int rowsDeleted = pstmt.executeUpdate();
if (rowsDeleted > 0) {
System.out.println("Record deleted successfully!");
} else {
System.out.println("Record not found!");
}
}
}
}

Steps to Run the Program

1. Replace:
o "your_database_name" with your database name.
o "your_username" with your database username.
o "your_password" with your database password.
2. Compile the program:

javac StudentCRUD.java

3. Run the program:

java StudentCRUD

Expected Output

 A menu will be displayed for performing CRUD operations.


 Each operation will prompt for necessary inputs and execute SQL queries.

You might also like