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

Java Practical Programs

Uploaded by

sujanak0203
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)
21 views

Java Practical Programs

Uploaded by

sujanak0203
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/ 13

1

1 . Write a Java program to print Fibonacci series using for loop. int[][] matrix1 = {
Source code: {1, 2, 3},
class FibonacciSeries { {4, 5, 6}
public static void main(String[] args) { };
int n = 10; // Number of terms to print
int firstTerm = 0; int[][] matrix2 = {
int secondTerm = 1; {7, 8},
System.out.println("Fibonacci Series up to " + n + " terms:"); {9, 10},
for (int i = 1; i <= n; ++i) { {11, 12}
System.out.print(firstTerm + " "); };
// Compute the next term
int nextTerm = firstTerm + secondTerm; // Calculate the product of the matrices
firstTerm = secondTerm; int[][] product = multiplyMatrices(matrix1, matrix2);
secondTerm = nextTerm;
} // Print the resulting product matrix
} System.out.println("Product of the matrices:");
} printMatrix(product);
Explanation }
1. Variables Initialization:
o n: The number of terms in the Fibonacci series to print. // Method to multiply two matrices
o firstTerm: Initialized to 0, the first term in the Fibonacci series. public static int[][] multiplyMatrices(int[][] firstMatrix, int[][] secondMatrix) {
o secondTerm: Initialized to 1, the second term in the Fibonacci int rows1 = firstMatrix.length;
series. int cols1 = firstMatrix[0].length;
2. For Loop: int cols2 = secondMatrix[0].length;
o Loop runs from 1 to n.
o Prints the current firstTerm. // Initialize the product matrix
o Computes the next term in the series by adding the current int[][] product = new int[rows1][cols2];
firstTerm and secondTerm.
o Updates firstTerm to the current secondTerm and secondTerm to // Perform matrix multiplication
the computed next term. for (int i = 0; i < rows1; i++) {
Sample Output: for (int j = 0; j < cols2; j++) {
Compile: javac FibonacciSeries.java for (int k = 0; k < cols1; k++) {
Run: java FibonacciSeries product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
Fibonacci Series up to 10 terms: }
0 1 1 2 3 5 8 13 21 34 }
2 . Write a Java program to calculate multiplication of 2 matrices. }
Source code:
class MatrixMultiplication { return product;
public static void main(String[] args) { }
// Define two matrices
// Method to print a matrix

K.G.Mahendra Reddy MCA


Lec in Computer Science
2

public static void printMatrix(int[][] matrix) {


for (int[] row : matrix) { // Constructor
for (int element : row) { public Rectangle() {
System.out.print(element + " "); this.length = 0;
} this.width = 0;
System.out.println(); }
}
} // Method to read attributes from the user
} public void readAttributes() {
Explanation Scanner scanner = new Scanner(System.in);
1. Matrices Definition: System.out.print("Enter the length of the rectangle: ");
o matrix1 and matrix2 are the two matrices to be multiplied. this.length = scanner.nextDouble();
2. Multiplication Method: System.out.print("Enter the width of the rectangle: ");
o The multiplyMatrices method performs the matrix multiplication. this.width = scanner.nextDouble();
It takes two matrices as input and returns their product. }
o The product matrix is initialized with dimensions based on the
number of rows of the first matrix and the number of columns of // Method to calculate the perimeter
the second matrix. public double calculatePerimeter() {
o Nested loops iterate through the rows of the first matrix, columns return 2 * (length + width);
of the second matrix, and columns of the first matrix (which }
equals the number of rows of the second matrix).
o The multiplication of corresponding elements and summation are // Method to calculate the area
performed to fill the product matrix. public double calculateArea() {
3. Printing the Matrix: return length * width;
o The printMatrix method prints the resulting product matrix row by }
row.
Sample Output: // Method to display the rectangle's properties
Compile: javac MatrixMultiplication java public void displayProperties() {
Run: java MatrixMultiplication System.out.println("Length: " + length);
Product of the matrices: System.out.println("Width: " + width);
58 64 System.out.println("Perimeter: " + calculatePerimeter());
139 154 System.out.println("Area: " + calculateArea());
3 . Create a class Rectangle. The class has attributes length and width. It }
should have methods that calculate the perimeter and area of the rectangle. It
should have read Attributes method to read length and width from user. public static void main(String[] args) {
Source code: Rectangle rectangle = new Rectangle();
import java.util.Scanner; rectangle.readAttributes();
class Rectangle { rectangle.displayProperties();
private double length; }
private double width; }
Explanation

K.G.Mahendra Reddy MCA


Lec in Computer Science
3

1. Attributes: // Overloaded method to add three integers


o length and width: These are private attributes of the Rectangle public int add(int a, int b, int c) {
class. return a + b + c;
2. Constructor: }
o Initializes length and width to 0.
3. Method readAttributes: // Overloaded method to add two double values
o Uses a Scanner object to read length and width from the user public double add(double a, double b) {
input. return a + b;
4. Method calculatePerimeter: }
o Calculates the perimeter of the rectangle using the formula 2 *
(length + width). // Overloaded method to add three double values
5. Method calculateArea: public double add(double a, double b, double c) {
o Calculates the area of the rectangle using the formula length * return a + b + c;
width. }
6. Method displayProperties:
o Prints the length, width, perimeter, and area of the rectangle. public static void main(String[] args) {
7. Main Method: MethodOverloadingExample example = new MethodOverloadingExample();
o Creates an instance of Rectangle.
o Calls the readAttributes method to get user input for length and // Calling overloaded methods
width. System.out.println("Sum of 2 integers (10 + 20): " + example.add(10, 20));
o Calls the displayProperties method to display the rectangle's System.out.println("Sum of 3 integers (10 + 20 + 30): " + example.add(10,
properties. 20, 30));
Sample Output: System.out.println("Sum of 2 doubles (10.5 + 20.5): " + example.add(10.5,
Compile: javac Rectangle. java 20.5));
Run: java Rectangle System.out.println("Sum of 3 doubles (10.5 + 20.5 + 30.5): " +
Enter the length of the rectangle: 5 example.add(10.5, 20.5, 30.5));
Enter the width of the rectangle: 3 }
Length: 5.0 }
Width: 3.0 Explanation
Perimeter: 16.0 1. Method Overloading:
o First Method: public int add(int a, int b)
Area: 15.0
4 . Write a Java program that implements method overloading.  Takes two integers and returns their sum.
Source code: o Second Method: public int add(int a, int b, int c)
class MethodOverloadingExample {  Takes three integers and returns their sum.
o Third Method: public double add(double a, double b)
// Method to add two integers  Takes two double values and returns their sum.
public int add(int a, int b) { o Fourth Method: public double add(double a, double b, double c)
return a + b;  Takes three double values and returns their sum.
} 2. Main Method:
o Creates an instance of MethodOverloadingExample.

K.G.Mahendra Reddy MCA


Lec in Computer Science
4

o Calls the overloaded add methods with different parameters. Explanation


o Prints the results. 1. Import Statements:
3. Sample Output: o import java.util.Arrays;: Imports the Arrays class which contains
Sample Output: the sort method.
Compile: javac MethodOverloadingExample. java o import java.util.Scanner;: Imports the Scanner class for reading
Run: java MethodOverloadingExample user input.
Sum of 2 integers (10 + 20): 30 2. Main Method:
Sum of 3 integers (10 + 20 + 30): 60 o Creates a Scanner object to read input from the user.
Sum of 2 doubles (10.5 + 20.5): 31.0 o Reads the number of names from the user.
Sum of 3 doubles (10.5 + 20.5 + 30.5): 61.5 o Initializes an array of String to store the names.
5 . Write a Java program for sorting a given list of names in ascending order. o Uses a loop to read each name and store it in the array.
Source code: o Sorts the array of names using Arrays.sort.
import java.util.Arrays; o Prints the sorted names.
import java.util.Scanner; Sample Output:
Compile: javac SortNames. java
class SortNames { Run: java SortNames
public static void main(String[] args) { Enter the number of names: 5
Scanner scanner = new Scanner(System.in); Enter the names:
John
// Read the number of names Alice
System.out.print("Enter the number of names: "); Bob
int numberOfNames = scanner.nextInt(); Eve
scanner.nextLine(); // Consume newline Charlie
// Read the names Names in ascending order:
String[] names = new String[numberOfNames]; Alice
System.out.println("Enter the names:"); Bob
for (int i = 0; i < numberOfNames; i++) { Charlie
names[i] = scanner.nextLine(); Eve
} John
6 . Write a Java program that displays the number of characters, lines and
// Sort the names
Arrays.sort(names); words in a text file.
Source code:
// Display the sorted names import java.io.BufferedReader;
System.out.println("Names in ascending order:"); import java.io.FileReader;
for (String name : names) { import java.io.IOException;
System.out.println(name);
} class FileStatistics {
} public static void main(String[] args) {
} // Specify the file path

K.G.Mahendra Reddy MCA


Lec in Computer Science
5

String filePath = "example.txt"; o The program reads each line of the file using reader.readLine().
o For each line, the lineCount is incremented.
// Variables to hold counts o The charCount is incremented by the length of the line.
int lineCount = 0; o The line is split into words using line.split("\\s+"), which splits the
int wordCount = 0; line based on whitespace. The number of words in the line is
int charCount = 0; added to wordCount.
5. Exception Handling:
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) o The try-with-resources statement ensures that the BufferedReader
{ is closed automatically after the block is executed.
String line; o If an IOException occurs, an error message is printed.
6. Displaying the Counts:
// Read the file line by line
o The counts of lines, words, and characters are displayed using
while ((line = reader.readLine()) != null) {
System.out.println.
lineCount++;
Example:
charCount += line.length();
Suppose example.txt contains the following text:
// Split the line into words based on whitespace Hello world!
String[] words = line.split("\\s+"); This is a test file.
wordCount += words.length; It contains multiple lines.
} Sample Output:
} catch (IOException e) { Compile: javac FileStatistics. java
System.out.println("An error occurred while reading the file: " + Run: java FileStatistics
e.getMessage()); Number of lines: 3
} Number of words: 9
Number of characters: 55
// Display the counts 7 . Write a Java program to implement various types of inheritance
System.out.println("Number of lines: " + lineCount); i. Single
System.out.println("Number of words: " + wordCount); ii. Multi-Level
System.out.println("Number of characters: " + charCount); iii. Hierarchical
} iv. Hybrid
} i. Single Inheritance
Explanation In Single Inheritance, a class inherits from one parent class.
1. File Path: Source code:
o String filePath = "example.txt";: Specifies the path to the text file. // Parent class
You can change this to the path of your text file. class Animal {
2. Counts Initialization: void eat() {
o lineCount, wordCount, and charCount are initialized to 0. System.out.println("This animal eats food.");
3. BufferedReader: }
o A BufferedReader wrapped around a FileReader is used to read }
the file line by line.
4. Reading the File: // Child class

K.G.Mahendra Reddy MCA


Lec in Computer Science
6

class Dog extends Animal { puppy.eat();


void bark() { puppy.bark();
System.out.println("The dog barks."); puppy.play();
} }
} }
iii. Hierarchical Inheritance
class SingleInheritance { In Hierarchical Inheritance, multiple classes inherit from a single parent class.
public static void main(String[] args) { Source code:
Dog dog = new Dog(); // Parent class
dog.eat(); class Animal {
dog.bark(); void eat() {
} System.out.println("This animal eats food.");
} }
ii. Multi-Level Inheritance }
In Multi-Level Inheritance, a class is derived from another class which is also
derived from another class. // Child class 1
Source code: class Dog extends Animal {
// Grandparent class void bark() {
class Animal { System.out.println("The dog barks.");
void eat() { }
System.out.println("This animal eats food."); }
}
} // Child class 2
class Cat extends Animal {
// Parent class void meow() {
class Dog extends Animal { System.out.println("The cat meows.");
void bark() { }
System.out.println("The dog barks."); }
}
} class HierarchicalInheritance {
public static void main(String[] args) {
// Child class Dog dog = new Dog();
class Puppy extends Dog { dog.eat();
void play() { dog.bark();
System.out.println("The puppy plays.");
} Cat cat = new Cat();
} cat.eat();
cat.meow();
class MultiLevelInheritance { }
public static void main(String[] args) { }
Puppy puppy = new Puppy(); iv. Hybrid Inheritance

K.G.Mahendra Reddy MCA


Lec in Computer Science
7

Hybrid Inheritance is a combination of two or more types of inheritance. However, Explanation


Java does not support multiple inheritance directly to avoid complexity and 1. Single Inheritance:
simplify the language. But we can achieve Hybrid Inheritance using interfaces. o Animal is the parent class.
Source code: o Dog is the child class that inherits from Animal.
// Interface 2. Multi-Level Inheritance:
interface CanFly { o Animal is the grandparent class.
void fly(); o Dog is the parent class that inherits from Animal.
} o Puppy is the child class that inherits from Dog.
3. Hierarchical Inheritance:
// Base class o Animal is the parent class.
class Animal { o Dog and Cat are child classes that inherit from Animal.
void eat() { 4. Hybrid Inheritance:
System.out.println("This animal eats food."); o Animal is the base class.
} o CanFly is an interface.
} o Bird inherits from Animal and implements the CanFly interface.
o Dog inherits from Animal.
// Derived class 1
8 . Write a java program to implement runtime polymorphism.
class Bird extends Animal implements CanFly {
Source code:
public void fly() {
// Parent class
System.out.println("The bird flies.");
Class Animal {
}
void sound() {
}
System.out.println("Animal makes a sound");
}
// Derived class 2
}
class Dog extends Animal {
void bark() {
// Child class 1
System.out.println("The dog barks.");
class Dog extends Animal {
}
@Override
}
void sound() {
System.out.println("Dog barks");
class HybridInheritance {
}
public static void main(String[] args) {
}
Bird bird = new Bird();
bird.eat();
// Child class 2
bird.fly();
class Cat extends Animal {
@Override
Dog dog = new Dog();
void sound() {
dog.eat();
System.out.println("Cat meows");
dog.bark();
}
}
}
}

K.G.Mahendra Reddy MCA


Lec in Computer Science
8

public void run() {


public class RuntimePolymorphism { try {
public static void main(String[] args) { while (true) {
// Parent reference, child object System.out.println("Good Morning");
Animal myAnimal; Thread.sleep(1000); // Sleep for 1 second
}
// Dog object } catch (InterruptedException e) {
myAnimal = new Dog(); System.out.println(e);
myAnimal.sound(); // Calls Dog's sound method }
}
// Cat object }
myAnimal = new Cat();
myAnimal.sound(); // Calls Cat's sound method // Thread to display "Hello" every 2 seconds
} class HelloThread extends Thread {
} public void run() {
Explanation try {
1. Parent Class: while (true) {
o Animal class has a method sound which prints a generic sound. System.out.println("Hello");
2. Child Classes: Thread.sleep(2000); // Sleep for 2 seconds
o Dog class overrides the sound method to print "Dog barks". }
o Cat class overrides the sound method to print "Cat meows". } catch (InterruptedException e) {
3. Main Method: System.out.println(e);
o An Animal reference is created. }
o The Animal reference is assigned to a Dog object and the sound }
method is called. This demonstrates runtime polymorphism as the }
Dog class's sound method is executed.
o The Animal reference is then assigned to a Cat object and the // Thread to display "Welcome" every 3 seconds
sound method is called. This demonstrates runtime polymorphism class WelcomeThread extends Thread {
as the Cat class's sound method is executed. public void run() {
Sample Output: try {
Compile: javac Animal. java while (true) {
Run: java Animal System.out.println("Welcome");
Dog barks Thread.sleep(3000); // Sleep for 3 seconds
Cat meows }
9 . Write a Java program to create three threads and that displays “good } catch (InterruptedException e) {
morning”, for every one second, “hello” for every 2 seconds and “welcome” System.out.println(e);
for every 3 seconds by using extending Thread class. }
Source code: }
// Thread to display "Good Morning" every 1 second }
class GoodMorningThread extends Thread {
class MultiThreadExample {

K.G.Mahendra Reddy MCA


Lec in Computer Science
9

public static void main(String[] args) { 10 . Implement a Java program for handling mouse events when the mouse
// Create thread instances entered, exited, clicked, pressed, released, dragged and moved in the client
GoodMorningThread goodMorningThread = new GoodMorningThread(); area.
HelloThread helloThread = new HelloThread(); Source code:
WelcomeThread welcomeThread = new WelcomeThread(); import javax.swing.*;
import java.awt.event.*;
// Start the threads
goodMorningThread.start(); public class MouseEventExample extends JFrame implements MouseListener,
helloThread.start(); MouseMotionListener {
welcomeThread.start();
} private JTextArea textArea;
}
Explanation public MouseEventExample() {
1. Thread Classes: setTitle("Mouse Event Example");
o GoodMorningThread: This thread prints "Good Morning" every setSize(400, 300);
1 second. It uses Thread.sleep(1000) to wait for 1 second between setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
prints. setLocationRelativeTo(null);
o HelloThread: This thread prints "Hello" every 2 seconds. It uses
Thread.sleep(2000) to wait for 2 seconds between prints. textArea = new JTextArea();
o WelcomeThread: This thread prints "Welcome" every 3 seconds. textArea.setEditable(false);
It uses Thread.sleep(3000) to wait for 3 seconds between prints. textArea.addMouseListener(this);
2. Main Method: textArea.addMouseMotionListener(this);
o Creates instances of each thread class.
o Starts each thread using the start() method. This invokes the run() add(new JScrollPane(textArea));
method of each thread, which contains the logic for printing the }
messages at specified intervals.
Sample Output: // MouseListener methods
Compile: javac MultiThreadExample java @Override
Run: java MultiThreadExample public void mouseClicked(MouseEvent e) {
Good Morning textArea.append("Mouse Clicked at (" + e.getX() + ", " + e.getY() + ")\n");
Hello }
Welcome
Good Morning @Override
Hello public void mousePressed(MouseEvent e) {
Good Morning textArea.append("Mouse Pressed at (" + e.getX() + ", " + e.getY() + ")\n");
Hello }
Welcome
Good Morning @Override
public void mouseReleased(MouseEvent e) {
textArea.append("Mouse Released at (" + e.getX() + ", " + e.getY() + ")\n");
}

K.G.Mahendra Reddy MCA


Lec in Computer Science
10

o mouseClicked(MouseEvent e): Handles mouse click events.


@Override o mousePressed(MouseEvent e): Handles mouse press events.
public void mouseEntered(MouseEvent e) { o mouseReleased(MouseEvent e): Handles mouse release events.
textArea.append("Mouse Entered the client area\n"); o mouseEntered(MouseEvent e): Handles when the mouse enters the
} client area.
o mouseExited(MouseEvent e): Handles when the mouse exits the
@Override client area.
public void mouseExited(MouseEvent e) { 4. MouseMotionListener Methods:
textArea.append("Mouse Exited the client area\n"); o mouseDragged(MouseEvent e): Handles mouse drag events.
} o mouseMoved(MouseEvent e): Handles mouse move events.
5. Main Method:
// MouseMotionListener methods o Uses SwingUtilities.invokeLater to ensure the GUI is created and
@Override updated on the Event Dispatch Thread (EDT).
public void mouseDragged(MouseEvent e) { Running the Program
textArea.append("Mouse Dragged at (" + e.getX() + ", " + e.getY() + ")\n"); When you run this program, a window will appear with a text area. As you interact
} with the text area using the mouse, different messages will be appended to the text
area based on the mouse events.
@Override This program provides a practical demonstration of handling various mouse events
public void mouseMoved(MouseEvent e) { and updates the user interface accordingly.
textArea.append("Mouse Moved at (" + e.getX() + ", " + e.getY() + ")\n"); 11 . Write a Java program to design student registration form using Swing
} Controls. The form which having the following fields and button SAVE
Here's a Java Swing program that creates a student registration form with the
public static void main(String[] args) { following fields and a "Save" button:
SwingUtilities.invokeLater(() -> {  Name
MouseEventExample frame = new MouseEventExample();  Age
frame.setVisible(true);  Gender (using radio buttons)
});  Address
}  Email
}  Phone Number
Explanation The form will have a "Save" button that, when clicked, prints the collected data to
1. Class Definition: the console.
o MouseEventExample extends JFrame and implements Source code:
MouseListener and MouseMotionListener. import javax.swing.*;
2. Constructor: import java.awt.*;
o Sets up the frame, including the title, size, default close operation, import java.awt.event.ActionEvent;
and layout. import java.awt.event.ActionListener;
o Initializes a JTextArea to display mouse events and adds it to a
JScrollPane. public class StudentRegistrationForm extends JFrame implements ActionListener
o Registers the frame to listen to mouse events using {
addMouseListener and addMouseMotionListener.
3. MouseListener Methods:
K.G.Mahendra Reddy MCA
Lec in Computer Science
11

// Define form components


private JTextField nameField; JLabel phoneLabel = new JLabel("Phone Number:");
private JTextField ageField; phoneField = new JTextField(20);
private JRadioButton maleRadioButton;
private JRadioButton femaleRadioButton; saveButton = new JButton("Save");
private JTextArea addressArea; saveButton.addActionListener(this);
private JTextField emailField;
private JTextField phoneField; // Add components to the frame
private JButton saveButton; gbc.gridx = 0;
gbc.gridy = 0;
public StudentRegistrationForm() { add(nameLabel, gbc);
// Set up the frame
setTitle("Student Registration Form"); gbc.gridx = 1;
setSize(400, 300); add(nameField, gbc);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); gbc.gridx = 0;
setLayout(new GridBagLayout()); gbc.gridy = 1;
GridBagConstraints gbc = new GridBagConstraints(); add(ageLabel, gbc);
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridx = 1;
// Initialize form components add(ageField, gbc);
JLabel nameLabel = new JLabel("Name:");
nameField = new JTextField(20); gbc.gridx = 0;
gbc.gridy = 2;
JLabel ageLabel = new JLabel("Age:"); add(genderLabel, gbc);
ageField = new JTextField(20);
gbc.gridx = 1;
JLabel genderLabel = new JLabel("Gender:"); gbc.gridwidth = 2;
maleRadioButton = new JRadioButton("Male"); add(maleRadioButton, gbc);
femaleRadioButton = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup(); gbc.gridx = 2;
genderGroup.add(maleRadioButton); add(femaleRadioButton, gbc);
genderGroup.add(femaleRadioButton);
gbc.gridx = 0;
JLabel addressLabel = new JLabel("Address:"); gbc.gridy = 3;
addressArea = new JTextArea(3, 20); add(addressLabel, gbc);
addressArea.setLineWrap(true);
addressArea.setWrapStyleWord(true); gbc.gridx = 1;
gbc.gridwidth = 2;
JLabel emailLabel = new JLabel("Email:"); add(new JScrollPane(addressArea), gbc);
emailField = new JTextField(20);

K.G.Mahendra Reddy MCA


Lec in Computer Science
12

gbc.gridx = 0; JOptionPane.showMessageDialog(this, "Registration details saved


gbc.gridy = 4; successfully!");
add(emailLabel, gbc); }
}
gbc.gridx = 1;
add(emailField, gbc); public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
gbc.gridx = 0; StudentRegistrationForm form = new StudentRegistrationForm();
gbc.gridy = 5; form.setVisible(true);
add(phoneLabel, gbc); });
}
gbc.gridx = 1; }
add(phoneField, gbc); Explanation
1. Class Definition:
gbc.gridx = 1; o StudentRegistrationForm extends JFrame and implements
gbc.gridy = 6; ActionListener to handle button clicks.
gbc.gridwidth = 2; 2. Constructor:
add(saveButton, gbc); o Sets up the frame properties (title, size, layout).
} o Initializes and configures all form components (labels, text fields,
radio buttons, text area, button).
@Override o Adds components to the frame using GridBagLayout for better
public void actionPerformed(ActionEvent e) { control of component positioning.
if (e.getSource() == saveButton) { 3. ActionListener:
// Collect data from form fields o Implements actionPerformed method to handle the "Save" button
String name = nameField.getText(); click event.
String age = ageField.getText(); o Collects data from the form fields and prints it to the console.
String gender = maleRadioButton.isSelected() ? "Male" : "Female"; o Shows a confirmation dialog using JOptionPane.
String address = addressArea.getText(); 4. Main Method:
String email = emailField.getText(); o Uses SwingUtilities.invokeLater to ensure the GUI is created and
String phone = phoneField.getText(); updated on the Event Dispatch Thread (EDT).
Running the Program
// Print data to the console When you run this program, a registration form window will appear. After filling
System.out.println("Name: " + name); in the form and clicking the "Save" button, the entered data will be printed to the
System.out.println("Age: " + age); console, and a confirmation message will be shown.
System.out.println("Gender: " + gender); This program provides a basic example of how to create and manage a form with
System.out.println("Address: " + address); Swing controls in Java.
System.out.println("Email: " + email);
System.out.println("Phone Number: " + phone);

// Show a confirmation message

K.G.Mahendra Reddy MCA


Lec in Computer Science
13

K.G.Mahendra Reddy MCA


Lec in Computer Science

You might also like