0% found this document useful (0 votes)
52 views18 pages

Oops Answer Key 27.05

Uploaded by

Darshan
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)
52 views18 pages

Oops Answer Key 27.05

Uploaded by

Darshan
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/ 18

EXCEL ENGINEERING COLLEGE, KOMARAPALAYAM

(Autonomous)
B.E/B.Tech. DEGREE SEMESTER EXAMINATION, APR/MAY 2024
Eighth Semester
B.Tech- Artificial Intelligence and Data Science
20AIE05 - NATURAL LANGUAGE PROCESSING
(Regulation 2020)
Time: Three Hours Maximum Marks : 100
Answer key
PART – A (10*2=20 Marks)
1. Define bytecode.
Byte Code can be defined as an intermediate code generated by the compiler after the
compilation of source code(JAVAProgram). This intermediate code makes Java a platform-
independent language.
2. Differentiate final,finalize and finally
Final: final is a keyword used in Java to restrict the modification of a variable, method, or class.
Finalize: finalize is a method in Java used to perform cleanup processing on an object before it is
garbage collected
Finally: finally is a block used in Java to ensure that a section of code is always executed, even if
an exception is thrown.

3.What is runtime polymorphism and compile time polymorphism?

Compile-time polymorphism is implemented through method overloading, which allows


multiple methods with the same name but different parameters and return types.
Run-time polymorphism is implemented through method overriding, where different
classes can have the same method with the same parameters.

4.What makes an abstract class different from other classes?

Abstract classes are classes which cannot be instantiated. In Object Oriented


Programming, a base class is one from which other classes inherit.

5. Define applet.

An applet is a Java program that can be embedded into a web page. It runs inside the web

browser and works at client side.

6. Differentiate byte stream and character stream

1
Byte stream: Byte streams are designed to deal with raw binary data, which includes all
kinds of data, including characters, pictues, audio, and video.

Character stream: Character streams are designed to address character based records,
which includes textual records inclusive of letters, digits, symbols, and other characters.

7.What are Deamon threads? List it properties.

A daemon thread is a thread that runs in the background and does not prevent the Java
Virtual Machine (JVM) from exiting when all non-daemon threads in Java have been completed.
These
threads are typically used to perform background tasks such as garbage collection, monitoring,
and other system-level operations.

8.Write the code snippet to set the priorities for threads.

public class ThreadPriorityExample {


public static void main(String[] args) {
Thread thread1 = new Thread(new Task(), "Thread-1");
Thread thread2 = new Thread(new Task(), "Thread-2");
thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);
thread1.start();
thread2.start();}}
class Task implements Runnable {@Override
public void run() {
for (int i = 0; i < 5; i++) {System.out.println(Thread.currentThread().getName() + " - " + i);}}}

9. Write the event delegation model?

The delegation event model, which defines standard and consistent mechanisms to
generate and process events. Its concept is quite simple: a source generates an event and
sends it to one or more listeners. In this scheme, the listener simply waits until it receives an
event.

10.What is the need for adapter classes in event handling?

With the help of the adapter class, developers can establish event listeners by
implementing only the methods that are needed for their application. This decreases the amount
of code needed to implement listener interfaces while also increasing code readability and
maintainability.

2
PART – B (5*16=80 Marks)
11) a) Elaborate on the intricate aspects of Java, highlighting its features and providing
detailed insights into its implementation

Features of java
Simple

Secure

Portable

Object-oriented

Robust

Multithreaded

Architecture-neutral

Interpreted

High performance

Distributed

Dynamic

(or)

b) Write java program to preform the following functions using classes, objects and
constructors where essential.
i. Get the input marks of 5 students in 5 subjects
ii. Calculate the total and average.
iii. Print the formatted result on the screen

import java.util.Scanner;
class Student{
private String name;
private int[] marks;
private int total;
private double average;
public Student(String name, int[] marks)
{this.name = name;
this.marks = marks;
calculateTotalAndAverage();}
private void calculateTotalAndAverage()

3
{total = 0;
for(int mark : marks){total += mark;}
average = total / (double) marks.length;}
public int getTotal()
{return total;}
public double getAverage()
{return average;}
public void printDetails() {
System.out.println("Student Name: " + name);
System.out.println("Marks: "); for (int mark : marks)
{System.out.print(mark + " ");}
System.out.println("\nTotal Marks: " + total);
System.out.println("Average Marks: " + average);}}
public class StudentMarks {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); Student[] students = new Student[5];
for (int i = 0; i < 5; i++) {
System.out.println("Enter the name of student " + (i + 1) + ": ");
String name = scanner.nextLine();
int[] marks = new int[5];
System.out.println("Enter the marks of 5 subjects for " + name + ": ");
for (int j = 0; j < 5; j++) {
marks[j] = scanner.nextInt();}
scanner.nextLine();
students[i] = new Student(name, marks);}
System.out.println("\nFormatted Results:"); for (Student student : students) {
student.printDetails(); System.out.println();}
int grandTotal = 0;
double grandAverage = 0;
for (Student student : students) { grandTotal += student.getTotal();
grandAverage += student.getAverage();}
grandAverage /= students.length;
System.out.println("Class Total Marks: " + grandTotal);
System.out.println("Class Average Marks: " + grandAverage);}}

4
12) a) Elucidate different types of Inheritance, delving into their implementation intricacies
with appropriate illustration.

Inheritance is the procedure in which one class inherits the attributes and methods of
another class. The class whose properties and methods are inherited is known as the Parent
class. And the class that inherits the properties from the parent class is the Child class.

Single Inheritance: When a Derived Class to inherit properties and behavior from a single
Base Class, it is called as single inheritance.

Example program:
class Animal{
void eat(){System.out.println("eating...");}}
class Dog extends Animal{
void bark(){System.out.println("barking...");}}
class TestInheritance{
public static void main(String args[]){ Dog d=new Dog();
d.bark();
d.eat();}}

Output: barking... eating...

Multiple Inheritance: Multiple inheritances allow programmers to create classes that


combine aspects of multiple classes and their corresponding hierarchies.

Example program:
interface Drawable{ void draw();}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}}
class TestInterface1{
public static void main(String args[]){ Drawable c=new circel();
c.draw();
Drawable r = new Rectangle(); r.draw();}}

Output:
drawing circle
drawing rectangle

Multi-level Inheritance: A derived class is created from another derived class is called Multi
Level Inheritance
Example program
class Animal{
void eat(){System.out.println("eating...");}}
class Dog extends Animal{
void bark(){System.out.println("barking...");}}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}}

5
class TestInheritance2{
public static void main(String args[]){ BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();}}

Output: weeping... barking... eating...

Hierarchical Inheritance: More than one derived classes are created from a single base
class, is called Hierarchical Inheritance.
Example program
class Animal{
void eat(){System.out.println("eating...");}}
class Dog extends Animal{
void bark(){System.out.println("barking...");}}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}}
class TestInheritance3{
public static void main(String args[]){ Cat c=new Cat();
c.meow();
c.eat();}}

Output: meowing... eating...

(or)

b) Illustrate what is meant by package? How does the predefined and user defined
packages are created and implemented in java?

A java package is a group of similar types of classes, interfaces and sub-packages.


Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package:

1) Java package is used to categorize the classes and interfaces so that they can be easily

maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

The package keyword is used to create a package in java.

package mypack; public class Simple{

public static void main(String args[]){ System.out.println("Welcome to package");}}

6
How to compile java package:

If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename For example
javac -d . Simple.java
javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).

How to run java package program:

You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple

Output:Welcome to package

13) a) How does the Exception are handled in java, and give an example to explain the built-
in exception and user defined exception?

A Java exception is an object that finds an exceptional condition occurs from a piece
of code. An exception object is created and thrown to the method from the code where an
exception is found.

There are two types of exceptions:

Predefined Exceptions: The Exceptions which are predefined are calledpredefined exceptions

Userdefined Exceptions: The Exceptions which are defined by the userare called userdefined
exceptions

Purpose of exception handling:

The main purpose of exception handling mechanism is used to detect and report an
“exceptional circumstance” so that necessary action can be taken. It performs the following
tasks

Find the problem(Hit the exception):

Inform that an error occurred(throw the exception), Receive the error information(Catch the
exception), Take corrective actions(Handle the exception)

Java exception handling is managed via five keywords, catch throw throws and finally

try block: Program statements that need to be monitored for exceptions areplaced within a try
block.

7
catch block: If an exception occurs within a try block, it is thrown to the catch block. This
block can catch this exception and handle it.

throw: Some exceptions are automatically thrown by the Java run time system. To throw the
exceptions manually, we can use the keyword throw.

throws: Any exception that is thrown out of a method is specified as such by a throws clause.

finally: finally blocks contains any code that need to be executed after a try block completes .

This is the general form of an exception-handling block:

try

{// block of code to monitor for errors}

catch (ExceptionType1 exOb){// exception handler for ExceptionType1}

catch (ExceptionType2 exOb){// exception handler for ExceptionType2}

// ... finally{

// block of code to be executed after try block ends}

Excetption Type is the type of exception that has occurred. exOb is anexception object.

Bulid-in exception example program:

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

// ArithmeticException example int a = 10;

int b = 0; try {

int c = a / b; // This will cause an ArithmeticException

System.out.println("Result: " + c);

}catch (ArithmeticException e) {

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

// ArrayIndexOutOfBoundsException example int[] numbers = {1, 2, 3, 4, 5};

try {

int value = numbers[6]; // This will cause an ArrayIndexOutOfBoundsException

System.out.println("Value: " + value);

} catch (ArrayIndexOutOfBoundsException e)

{ System.out.println("Error: " + e.getMessage());}}}

Output:

Error: / by zero

Error: Index 6 out of bounds for length 5

User defined exception example program:

8
import java.lang.Exception;

class MyownException extends Exception{

MyownException(String mes){

super(mes);}}

class TestException{

public static void main(String args[]){

int a=5,b=1000;try{

float c=(float)a/(float)b;if(c<0.01){

throw new MyownException("number is too small");}}

catch (MyownException e){

System.out.println("caught my exception"); System.out.println(e.getMessage());}

finally{

System.out.println("This is a finally block");}}}

Output: caught my exceptionnumber is too small This is a finally block

b) Write a java program to store the student information of roll number, name, address,
department, year and section in a file and retrieve the same and display the details in a
neat format.

import java.io.*;
import java.util.Scanner;
class Student {
private int rollNumber; private String name; private String address;
private String department; private int year;
private char section;
public Student(int rollNumber, String name, String address, String department, int year,
char section) {
this.rollNumber = rollNumber; this.name = name;
this.address = address;
this.department = department; this.year = year;
this.section = section;}
public String toString() {
return "Roll Number: " + rollNumber + "\nName: " + name + "\nAddress: " + address + "\
nDepartment: " + department + "\nYear: " + year + "\nSection: " + section + "\n";}}
public class StudentRecordManager { public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int numStudents = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
Student[] students = new Student[numStudents];
// Store student information in the file try {

9
FileWriter writer = new FileWriter("students.txt");
for (int i = 0; i < numStudents; i++) {
System.out.println("Enter details for student " + (i + 1) + ":");
System.out.print("Roll Number: "); int rollNumber = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
System.out.print("Name: "); String name = scanner.nextLine();
System.out.print("Address: "); String address = scanner.nextLine();
System.out.print("Department: ");
String department = scanner.nextLine(); System.out.print("Year: ");
int year = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
System.out.print("Section: ");
char section = scanner.nextLine().charAt(0);
Student student = new Student(rollNumber, name, address, department, year, section);
students[i] = student; writer.write(student.toString());}
writer.close();
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();}
try {
FileReader reader = new FileReader("students.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);}
reader.close();
} catch (IOException e) {
System.out.println("An error occurred while reading from the file.");
e.printStackTrace();}}}

14) a) What is a thread? Illustrate the various ways of creating threads to print the numbers
from 1 to 10.
A thread is defined as a subprocess with lightweight and has separate path of
execution. A program can be divided into number of subprograms and each subprogram can
execute parallel. Generally, all the programs have atleast one thread, known as main thread,
that is provided by the JVM or Java Virtual Machine at the starting of the program's execution.
Extending the thread class:
class PrintNumbers extends Thread { public void run() {
for (int i = 1; i <= 10; i++) { System.out.println(i); try {
Thread.sleep(1000); // Delay for 1 second
} catch (InterruptedException e) { e.printStackTrace();}}}}
public class ThreadExample {
public static void main(String[] args) {
PrintNumbers thread = new PrintNumbers();

10
thread.start();}}
Implements the runnable interface:
class PrintNumbers implements Runnable { public void run() {
for (int i = 1; i <= 10; i++) { System.out.println(i); try {
Thread.sleep(1000); // Delay for 1 second
} catch (InterruptedException e) { e.printStackTrace();}}}}
public class ThreadExample {
public static void main(String[] args) {
PrintNumbers runnable = new PrintNumbers(); Thread thread = new
Thread(runnable);
thread.start();}}
Using anonymous class:
public class ThreadExample {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() { public void run() {
for (int i = 1; i <= 10; i++) { System.out.println(i); try {
Thread.sleep(1000); // Delay for 1 second
} catch (InterruptedException e) { e.printStackTrace();}}}});
thread.start();}}
(or)
b) Elucidate generic classes and methods, explore their functionality, application and
implementation intricacies?
Generics in Java provide a way to write code that can work with various data types
while maintaining type safety and eliminating the need for explicit type casting. They allow
you to define classes, interfaces, and methods that can operate on objects of different types
without compromising type safety. Generics were introduced in Java 5 to address the
limitations of previous approaches, such as using Object types or extensive type casting.
Functionality: The primary functionality of generics is to allow the programmer to
define a single class, interface, or method that can work with multiple types without
compromising type safety. This is achieved by using type parameters, which act as
placeholders for actual types that will be specified when creating instances or calling methods.
Application: Generics have a wide range of applications in Java programming. Some
common use cases include:
1.Generic Collections: The Java Collections Framework widely uses generics to ensure
type safety when working with collections like List, Set, and Map.
2.Generic Classes: Developers can create their own generic classes that can work with
different data types.

11
3.Generic Methods: Methods can be defined to accept and return generic types, enabling
code reusability across different data types.
4.Generic Interfaces: Interfaces can be defined using generics, allowing for more flexible
an reusable code.
Implementation Intricacies: While generics provide a powerful mechanism for writing
reusable and type-safe code, there are some implementation intricacies to be aware of:

1.Type Erasure: Generics in Java are implemented using type erasure. During compilation,
the Java compiler erases all type parameters and replaces them with their corresponding
upper bounds (typically `Object`). This process ensures backward compatibility with
earlier Java versions but also imposes certain limitations, such as the inability to create
generic arrays or perform certain operations that rely on the actual type information at
runtime.
2.Bounded Type Parameters: Generics allow you to place constraints on the types that can
be used as type arguments. This is achieved through bounded type parameters, which
restrict the types to those that extend a specific class or implement a particular interface.
3.Wildcard Types: Wildcard types (`?`) are used to represent unknown types in generic
code. They provide flexibility when working with generic types, allowing methods to
accept a wider range of types while maintaining type safety.
4.Generic Type Inference: Java's compiler can automatically infer the type arguments for
generic classes and methods in many cases, reducing the need for explicit type
specifications. This feature, known as type inference, improves code readability and
reduces redundancy.
5.Generic Methods and Type Inference: When defining generic methods, the type
parameters must be explicitly declared before the return type. Additionally, type
inference for generic methods works differently than for generic classes, requiring
special handling in certain cases.
// Generic class class Box<T> {
private T item;
public void set(T item) { this.item = item;}
public T get() { return item;}}
public class GenericExample {
public static void main(String[] args) {
// Using a generic class Box<Integer> intBox = new Box<>();
intBox.set(42);
System.out.println(intBox.get()); // Output: 42
Box<String> stringBox = new Box<>(); stringBox.set("Hello, World!");

12
System.out.println(stringBox.get()); // Output: Hello, World!
// Using a generic method Integer[] intArray = { 1, 2, 3, 4, 5 };
String[] stringArray = { "Hello", "World" };
printArray(intArray); printArray(stringArray);}
// Generic method
private static <T> void printArray(T[] array) {
for (T element : array) { System.out.print(element + " ");}
System.out.println();}}
15) a) What is meant by event handling? Analyze and create a simple calculator using
mouse events that restrict only addition, subtraction, multiplication and division.
Event handling in Java refers to the mechanism of responding to events that occur
within a program. An event can be anything from a user interaction (such as clicking a button
or pressing a key) to system-generated occurrences (like a timer or network activity). Java
provides an event-driven programming model, where events are handled by specialized code
called event handlers or listeners. In the context of GUI (Graphical User Interface)
programming, event handling plays a crucial role in making the application responsive to user
interactions. For example, when a user clicks a button, the application needs to respond by
executing the appropriate code associated with that button click event.
To create a simple calculator using mouse events, we can use the `MouseListener`
interface provided by Java's AWT (Abstract Window Toolkit) or Swing libraries. The
`MouseListener` interface defines several methods that are called when specific mouse events
occur, such as mouseClicked(), mouseEntered(), mouseExited(), mousePressed(), and
mouseReleased().
Here's an example of a simple calculator that uses mouse events to perform addition,
subtraction, multiplication, and division operations:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseCalculator extends JFrame implements MouseListener {
private JTextField display; private double operand1 = 0.0;
private double operand2 = 0.0; private char operation = ' ';
public MouseCalculator() { setTitle("Mouse Calculator"); setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
display = new JTextField(); display.setEditable(false);
add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();

13
buttonPanel.setLayout(new GridLayout(4, 4)); buttonPanel.addMouseListener(this);
String[] buttons = { "7", "8", "9", "/","4", "5", "6", "*","1", "2", "3", "-","0", ".", "=",
"+"};
for (String buttonText : buttons) {
JButton button = new JButton(buttonText);
button.addMouseListener(this); buttonPanel.add(button);}
add(buttonPanel, BorderLayout.CENTER); setVisible(true);}
public void mouseClicked(MouseEvent e) {
String buttonText = ((JButton) e.getSource()).getText();
if (buttonText.matches("[0-9]|\\.|=")) { if (buttonText.equals("=")) {
performOperation();
} else {
updateDisplay(buttonText);}}
else { operand1 = Double.parseDouble(display.getText());
operation = buttonText.charAt(0); display.setText("");}}
private void performOperation() {
operand2 =Double.parseDouble(display.getText()); double result = 0.0;
switch (operation) { case '+': result = operand1 + operand2; break;
case '-':
result = operand1 - operand2; break;
case '*':
result = operand1 * operand2; break;
case '/':
if (operand2 != 0.0) {
result = operand1 / operand2;
} else {
display.setText("Error: Division by zero"); return;}
break;}
display.setText(String.valueOf(result)); operand1 = result;}
private void updateDisplay(String text) { display.setText(display.getText() + text); }
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public static void main(String[] args) { new MouseCalculator();}}
(or)

14
b)Describe the types of layout management in detail with an example.
In Java Swing GUI programming, layout managers are responsible for arranging and
positioning components (such as buttons, labels, text fields, etc.) within a container (like a
window or panel). Java provides several built-in layout managers to help developers create
user interfaces with consistent and attractive layouts. Here are the main types of layout
managers in Java, along with examples:
1.FlowLayout:
The `FlowLayout` arranges components in a row, left to right, and wraps to the next
line when there is no more space in the current line. It's the default layout manager for
`JPanel`.
Example:
import javax.swing.*;
public class FlowLayoutExample { public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_ CLOSE);
frame.setSize(300, 200);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout()); // Default FlowLayout
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
panel.add(new JButton("Button 4"));
panel.add(new JButton("Button 5"));
frame.add(panel);
frame.setVisible(true);}}
2.BorderLayout:
The `BorderLayout` divides the container into five regions: North, South, East, West,
and Center. It's the default layout manager for `JFrame`.
Example:
java
import javax.swing.*;
public class BorderLayoutExample { public static void main(String[] args) {
JFrame frame = new JFrame("BorderLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_ CLOSE);
frame.setSize(300, 200);
JPanel panel = new JPanel(new BorderLayout());

15
panel.add(new JButton("North"), BorderLayout.NORTH);
panel.add(new JButton("South"), BorderLayout.SOUTH);
panel.add(new JButton("East"), BorderLayout.EAST);
panel.add(new JButton("West"), BorderLayout.WEST);
panel.add(new JButton("Center"), BorderLayout.CENTER);
frame.add(panel);
frame.setVisible(true);}}
3.GridLayout:
The `GridLayout` arranges components in a grid of equal-sized cells, with a specified
number of rows and columns.
Example:
import javax.swing.*;
public class GridLayoutExample { public static void main(String[] args) {
JFrame frame = new JFrame("GridLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_ CLOSE);
frame.setSize(300, 200);
JPanel panel = new JPanel(new GridLayout(3, 2)); // 3 rows, 2 columns
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
panel.add(new JButton("Button 4"));
panel.add(new JButton("Button 5"));
panel.add(new JButton("Button 6"));
frame.add(panel);
frame.setVisible(true);}}
4.BoxLayout:
The BoxLayout arranges components in a single row or column, with configurable
spacing between them. It can be used to create complex nested layouts.
Example:
import javax.swing.*; import java.awt.*;
public class BoxLayoutExample { public static void main(String[] args) {
JFrame frame = new JFrame("BoxLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_ CLOSE);
frame.setSize(300, 200);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel,
BoxLayout.Y_AXIS)); // Vertical layout

16
panel.add(new JButton("Button 1"));
panel.add(Box.createVerticalStrut(10)); // Add vertical spacing
panel.add(new JButton("Button 2"));
panel.add(Box.createVerticalStrut(10));
panel.add(new JButton("Button 3"));
frame.add(panel);
frame.setVisible(true);}}

5.CardLayout:
The `CardLayout` allows you to display one component at a time from a set of
components. It's useful for creating tab-like interfaces or wizard-style applications.
Example:
import javax.swing.*; import java.awt.*; import java.awt.event.*;
public class CardLayoutExample { public static void main(String[] args) {
JFrame frame = new JFrame("CardLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_ CLOSE);
frame.setSize(300, 200);
JPanel cardPanel = new JPanel(new CardLayout());
JPanel buttonPanel = new JPanel();
JButton button1 = new JButton("Panel 1"); JButton button2 = new JButton("Panel
2"); JButton button3 = new JButton("Panel 3");
buttonPanel.add(button1); buttonPanel.add(button2); buttonPanel.add(button3);
JPanel panel1 = new JPanel();
panel1.add(new JLabel("This is Panel 1")); JPanel panel2 = new JPanel();
panel2.add(new JLabel("This is Panel 2")); JPanel panel3 = new JPanel();
panel3.add(new JLabel("This is Panel 3"));
cardPanel.add(panel1, "Panel 1");
cardPanel.add(panel2, "Panel 2");
cardPanel.add(panel3, "Panel 3");
CardLayout cardLayout = (CardLayout) cardPanel.getLayout();
button1.addActionListener(e ->
cardLayout.show(cardPanel, "Panel 1"));
button2.addActionListener(e ->
cardLayout.show(cardPanel, "Panel 2"));
button3.addActionListener(e ->
cardLayout.show(cardPanel, "Panel 3"));
frame.add(buttonPanel, BorderLayout.NORTH);

17
frame.add(cardPanel, BorderLayout.CENTER); frame.setVisible(true);}}

18

You might also like