Dec 2020
PART-C
20. Explain the various control statements in JAVA.(R)(DEC 2023)
Decision-making in programming is similar to decision-making in real life. In programming, we
also face situations where we want a certain block of code to be executed when some condition is
fulfilled.
A programming language uses control statements to control the flow of execution of a program
based on certain conditions.. Java provides several control statements to manage program flow,
including:
• Conditional Statements: if, if-else, nested-if, if-else-if
• Switch-Case: For multiple fixed-value checks
• Jump Statements: break, continue, return
1. Java if Statement
The if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e. if a certain condition is true then
a block of statements is executed otherwise not.
the condition after evaluation will be either true or false. if statement accepts boolean values - if the
value is true then it will execute the block of statements under it. If we don't use curly braces( {} ),
only the next line after the if is considered as part of the if block For example,
• If the condition is True statement1 executes.
• statement2 runs no matter what because it's not a part of the if block
2. Java if-else Statement
The if statement alone tells us that if a condition is true it will execute a block of statements and if
the condition is false it won't. But what if we want to do something else if the condition is false?
Here, comes the "else" statement. We can use the else statement with the if statement to execute a
block of code when the condition is false.
Syntax:
3. Java nested-if Statement
A nested if is an if statement that is the target of another if or else. Nested if statements mean an if
statement inside an if statement. Yes, java allows us to nest if statements within if statements. i.e,
we can place an if statement inside another if statement.
4. Java if-else-if ladder
a user can decide among multiple [Link] if statements are executed from the top down. As
soon as one of the conditions controlling the if is true, the statement associated with that 'if' is
executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed. There can be as many as 'else if' blocks associated with one 'if' block
but only one 'else' block is allowed with one 'if' block.
5. Java Switch Case
The switch statement is a multiway branch statement. It provides an easy way to dispatch execution
to different parts of code based on the value of the expression.
• The expression can be of type byte, short, int char, or an enumeration. Beginning with JDK7,
the expression can also be of type String.
• Duplicate case values are not allowed.
• The default statement is optional.
• The break statement is used inside the switch to terminate a statement sequence.
• The break statements are necessary without the break keyword, statements in switch blocks fall
through.
• If the break keyword is omitted, execution will continue to the next case.
6. jump Statements
Java supports three jump statements: break, continue and return. These three statements transfer
control to another part of the program.
• Break: In Java, a break is majorly used for:
o Terminate a sequence in a switch statement (discussed above).
o To exit a loop.
o Used as a "civilized" form of goto.
• Continue: Sometimes it is useful to force an early iteration of a loop. That is, you might want
to continue running the loop but stop processing the remainder of the code in its body for this
particular iteration. This is, in effect, a goto just past the body of the loop, to the loop's end. The
continue statement performs such an action.
import [Link].*;
class Geeks {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
// If the number is even, skip and continue
if (i % 2 == 0)
continue;
// If number is odd, print it
[Link](i + " ");
}
}
}
Return Statement
The return statement is used to explicitly return from a method. That is, it causes program control to
transfer back to the caller of the method.
Example: The below Java program demonstrates how the return statements stop a method and
skips the rest of the code.
import [Link].*;
public class Geeks {
public static void main(String args[])
{
boolean t = true;
[Link]("Before the return.");
if (t)
return;
// Compiler will bypass every statement return
[Link]("This won't execute.");
}
21. Write about the wrapper classes for primitive data types.
Wrapper Classes for Primitive Data Types
In Java, wrapper classes are special classes provided in the [Link] package that allow
primitive data types to be treated as objects. Each primitive type has a corresponding wrapper class.
1. Purpose of Wrapper Classes
• Object Representation: Java collections (like ArrayList, HashMap) store only objects, not
primitives. Wrapper classes allow primitives to be stored as objects.
• Utility Methods: They provide useful methods for type conversions, parsing strings, and
comparing values.
• Autoboxing & Unboxing: Java automatically converts between primitives and wrapper
objects.
2. Wrapper Classes List
3. Examples:
int num = 10;
Integer obj = [Link](num); // wrapping (boxing)
int val = [Link](); // unwrapping (unboxing)
// Autoboxing & unboxing
Integer autoObj = num; // autoboxing
int autoVal = autoObj; // unboxing
4. Advantages
• Enables use of primitives in collections.
• Provides constants (e.g., Integer.MAX_VALUE).
• Offers conversion methods (e.g., [Link]("123")).
Conclusion: Wrapper classes bridge the gap between primitives and objects in Java, making them
essential for object-oriented programming, data structures, and utility operations.
22. Develop an Interface with Jcheckbox JTextarea and JButton. R(DEC 2020,JUN 2024)
JCheckBox is a part of Java Swing package . JCheckBox can be selected or deselected . It displays
it state to the user . JCheckBox is an implementation to checkbox . JCheckBox inherits
JToggleButton class. Constructor of the class are :
1. JCheckBox() : creates a new checkbox with no text or icon
2. JCheckBox(Icon i) : creates a new checkbox with the icon specified
3. JCheckBox(Icon icon, boolean s) : creates a new checkbox with the icon specified and the
boolean value specifies whether it is selected or not.
4. JCheckBox(String t) :creates a new checkbox with the string specified
5. JCheckBox(String text, boolean selected) :creates a new checkbox with the string specified
and the boolean value specifies whether it is selected or not.
6. JCheckBox(String text, Icon icon) :creates a new checkbox with the string and the icon
specified.
7. JCheckBox(String text, Icon icon, boolean selected): creates a new checkbox with the string
and the icon specified and the boolean value specifies whether it is selected or not.
Methods to add Item Listener to checkbox.
1. addActionListener(ItemListener l): adds item listener to the component
2. itemStateChanged(ItemEvent e) : abstract function invoked when the state of the item to
which listener is applied changes
3. getItem() : Returns the component-specific object associated with the item whose state changed
4. getStateChange() : Returns the new state of the item. The ItemEvent class defines two states:
SELECTED and DESELECTED.
5. getSource() : Returns the component that fired the item event.
Commonly used methods:
1. setIcon(Icon i) : sets the icon of the checkbox to the given icon
2. setText(String s) :sets the text of the checkbox to the given text
3. setSelected(boolean b) : sets the checkbox to selected if boolean value passed is true or vice
versa
4. getIcon() : returns the image of the checkbox
5. getText() : returns the text of the checkbox
6. updateUI() : resets the UI property with a value from the current look and feel.
7. getUI() : returns the look and feel object that renders this component.
8. paramString() : returns a string representation of this JCheckBox.
9. getUIClassID() : returns the name of the Look and feel class that renders this component.
10. getAccessibleContext() : gets the AccessibleContext associated with this JCheckBox.
11. isBorderPaintedFlat() : gets the value of the borderPaintedFlat property.
12. setBorderPaintedFlat(boolean b) : sets the borderPaintedFlat property.
Example:
import [Link].*;
import [Link].*;
import [Link].*;
public class CheckBoxTextAreaDemo extends JFrame implements ActionListener {
JCheckBox checkBox;
JTextArea textArea;
JButton button;
public CheckBoxTextAreaDemo() {
Frame title
setTitle("Interface Example");
setSize(400, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Components
checkBox = new JCheckBox("I agree");
textArea = new JTextArea(5, 25);
button = new JButton("Submit");
// Add action listener
[Link](this);
// Add components to frame
add(checkBox);
add(new JScrollPane(textArea));
add(button);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if ([Link]()) {
[Link](this,
"Submitted: " + [Link]());
} else {
[Link](this,
"Please check the box before submitting!");
}
}
public static void main(String[] args) {
new CheckBoxTextAreaDemo();
}
}
🔎 How it works:
• JCheckBox → lets user confirm (e.g., "I agree").
• JTextArea → allows user to type text (multi-line).
• JButton → on click, checks if the box is selected; if yes, it displays the text in a dialog,
otherwise shows a warning.
23. Develop an application to store the particulars of employee in a file. And display them on
screen by sequentially retrieving the records.
Java Program: Employee File Storage & Retrieval
import [Link].*;
import [Link].*;
public class EmployeeFileApp {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String fileName = "[Link]";
// Step 1: Write employee details into a file
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
[Link]("Enter number of employees: ");
int n = [Link]();
[Link](); // consume newline
for (int i = 0; i < n; i++) {
[Link]("\nEnter details of Employee " + (i + 1));
[Link]("ID: ");
int id = [Link]();
[Link]();
[Link]("Name: ");
String name = [Link]();
[Link]("Salary: ");
double salary = [Link]();
[Link]();
// Write record in file (comma-separated)
[Link](id + "," + name + "," + salary);
[Link]();
}
[Link]("\nEmployee details stored successfully!");
} catch (IOException e) {
[Link]("Error writing file: " + [Link]());
}
// Step 2: Read and display employee details sequentially
[Link]("\n--- Employee Records ---");
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = [Link]()) != null) {
String[] data = [Link](",");
int id = [Link](data[0]);
String name = data[1];
double salary = [Link](data[2]);
[Link]("ID: " + id + ", Name: " + name + ", Salary: " + salary);
}
} catch (IOException e) {
[Link]("Error reading file: " + [Link]());
}
}
}
🔎 How It Works
• Writing Phase:
o User enters employee details (ID, Name, Salary).
o Each record is stored in [Link] as:
o 101,John,50000
o 102,Alice,60000
• Reading Phase:
o File is read line by line.
o Each line is split into fields (id, name, salary) and displayed sequentially.
💻 Sample Run
Enter number of employees: 2
Enter details of Employee 1
ID: 101
Name: John
Salary: 50000
Enter details of Employee 2
ID: 102
Name: Alice
Salary: 60000
Employee details stored successfully!
--- Employee Records ---
ID: 101, Name: John, Salary: 50000.0
ID: 102, Name: Alice, Salary: 60000.0
24. Write a short note on (a) Socket Programming (b) Working with Fonts.
(a) Socket Programming R(DEC 2020,JUN 2021,JUN 2024)
(a) Socket Programming
1. Definition: Socket programming allows two-way communication between two systems
(client and server) over a network.
2. Socket: An endpoint of communication, represented by an IP address + port number.
3. Types of Communication:
o TCP (Transmission Control Protocol) → connection-oriented, reliable (uses Socket
& ServerSocket).
o UDP (User Datagram Protocol) → connectionless, faster but less reliable (uses
DatagramSocket).
4. Important Classes ([Link]):
o Socket → client-side connection.
o ServerSocket → server-side listener.
o DatagramSocket, DatagramPacket → for UDP communication.
5. Basic Steps (TCP):
o Server creates ServerSocket and waits for connection.
o Client creates Socket and requests connection.
o Input/Output streams are used to send and receive data.
o Connection closes after communication ends.
6. Streams Used:
o InputStream / BufferedReader → to read data.
o OutputStream / PrintWriter → to send data.
7. Advantages:
o Enables distributed applications.
o Provides reliable communication (with TCP).
o Allows both local and internet-based communication.
8. Applications:
o Chat systems, multiplayer games.
o File sharing apps.
o Remote login, messaging services.
o Web servers & client applications.
(b) Working with Fonts (DEC – [Link]-2024)
1. Definition: In Java GUI (AWT/Swing), fonts control the appearance of text in components.
2. Font Class ([Link]): Used to define font style, size, and name.
3. Constructor:
Font f = new Font("Serif", [Link], 18);
4. Parameters:
o Font Name → "Serif", "SansSerif", "Monospaced".
o Style → [Link], [Link], [Link].
o Size → font size in points (e.g., 12, 18).
5. Methods:
o getName() → returns font name.
o getStyle() → returns style.
o getSize() → returns size.
6. Usage in Graphics:
public void paint(Graphics g) {
Font f = new Font("SansSerif", [Link], 20);
[Link](f);
[Link]("Hello, World!", 50, 100);
}
7. Usage in Components: Fonts can be set in GUI components like JLabel, JTextArea, JButton
using setFont().
8. Advantages:
o Improves readability of applications.
o Allows customization of look and feel.
o Enhances user interface design.
9. Default Fonts: Java provides logical fonts (Serif, SansSerif, Monospaced, Dialog,
DialogInput) that map to system fonts.
DEC 2021
PART-C
20. Discuss in detail the features of JAVA. .(R)(MAY 2022)(DEC 2022[5])
1. Simple
❖ Java was designed to be easy to learn and use.
❖ Its syntax is clean and similar to C/C++, but without complex features like pointers, operator
overloading, or multiple inheritance (it uses interfaces instead).
❖ Automatic memory management (garbage collection) makes it easier for developers.
2. Object-Oriented
❖ Everything in Java is treated as an object (except primitive data types, though they have
wrapper classes).
❖ Supports concepts like encapsulation, inheritance, polymorphism, and abstraction.
❖ Helps in modular programming and reusability of code.
3. Platform Independent (Portable)
❖ Java source code is compiled into bytecode, which runs on the Java Virtual Machine (JVM).
❖ This makes Java platform-independent, i.e., the same code can run on Windows, Mac, Linux,
etc., without modification.
❖ This is the core of the WORA principle.
4. Secure
❖ Java has strong security features:
❖ No explicit pointers (reduces memory access vulnerabilities).
❖ Bytecode verification before execution.
❖ Sandbox security model for running programs in a restricted environment.
❖ Security APIs for cryptography, authentication, and secure communication.
5. Robust
❖ Java emphasizes reliability:
❖ Strong type-checking at compile-time and runtime.
❖ Exception handling to manage runtime errors.
❖ Automatic garbage collection prevents memory leaks.
❖ Eliminates many error-prone features (like manual memory management).
6. Multithreaded
❖ Java provides built-in support for multithreading, allowing programs to perform multiple
tasks simultaneously.
❖ It has classes like Thread and interfaces like Runnable for easy thread management.
❖ This is useful in applications like gaming, multimedia, and web servers.
7. Distributed
❖ Java supports distributed computing:
❖ Through Remote Method Invocation (RMI) and CORBA, objects can communicate across a
network.
❖ Java also integrates well with web technologies, making it suitable for cloud-based
applications.
8. High Performance
❖ Although Java is slower than C/C++ because it is interpreted by JVM, its performance is
boosted by:
❖ Just-In-Time (JIT) Compiler: Converts bytecode to native machine code at runtime.
❖ Modern JVMs with adaptive optimization.
❖ This makes Java fast enough for enterprise and large-scale applications.
9. Dynamic and Extensible
❖ Java programs can load classes dynamically at runtime.
❖ Supports dynamic linking of libraries.
❖ Reflection API allows inspection and modification of program behavior at runtime.
10. Architecture Neutral
❖ Java bytecode is independent of processor architecture.
❖ Unlike C/C++, it doesn’t depend on machine-specific instructions.
❖ This makes Java suitable for heterogeneous network environments.
11. Interpreted and Compiled
❖ Java is both compiled and interpreted:
❖ Source code → compiled to bytecode.
❖ JVM interprets bytecode into machine code.
❖ This combination makes Java more flexible.
12. Automatic Memory Management
❖ Java uses Garbage Collection (GC) to automatically reclaim unused memory.
❖ Developers don’t need to manually allocate and deallocate memory, reducing bugs like
memory leaks and dangling pointers
21. Explain the concept of method overloading with examples.
✅ Definition:
Method Overloading in Java is a feature that allows a class to have multiple methods with the
same name but different parameter lists (different number of parameters or different data types of
parameters).
👉 The return type alone cannot differentiate overloaded methods.
👉 It is an example of Compile-Time Polymorphism (also called Static Polymorphism).
🔹 Rules for Method Overloading
1. Methods must have the same name.
2. Methods must differ by:
o Number of parameters
o Type of parameters
o Order of parameters
3. Return type does not matter (overloading cannot be achieved by changing only return type).
🔹 Examples in Java
1. Overloading by Changing Number of Parameters
class MathOperations {
// Method with 2 parameters
int add(int a, int b) {
return a + b;
}
// Overloaded method with 3 parameters
int add(int a, int b, int c) {
return a + b + c;
}
}
public class TestOverloading {
public static void main(String[] args) {
MathOperations obj = new MathOperations();
[Link]("Sum of 2 numbers: " + [Link](10, 20));
[Link]("Sum of 3 numbers: " + [Link](10, 20, 30));
}
}
Output:
Sum of 2 numbers: 30
Sum of 3 numbers: 60
2. Overloading by Changing Data Types of Parameters
class Display {
void show(int a) {
[Link]("Integer: " + a);
}
void show(String s) {
[Link]("String: " + s);
}
}
public class TestOverloading2 {
public static void main(String[] args) {
Display d = new Display();
[Link](100); // Calls method with int parameter
[Link]("Hello"); // Calls method with String parameter
}
}
Output:
Integer: 100
String: Hello
3. Overloading by Changing Order of Parameters
class PrintData {
void print(int a, String b) {
[Link]("Integer: " + a + ", String: " + b);
}
void print(String b, int a) {
[Link]("String: " + b + ", Integer: " + a);
}
}
public class TestOverloading3 {
public static void main(String[] args) {
PrintData p = new PrintData();
[Link](10, "Java"); // Calls first method
[Link]("Hello", 20); // Calls second method
}
}
Output:
Integer: 10, String: Java
String: Hello, Integer: 20
🔹 Key Points
• Overloading is resolved at compile-time (static binding).
• Helps in code readability (same method name for similar operations).
• Return type alone cannot be used to overload.
22. Describe the common GUI event types and Listener interfaces in detail.
.🔹 Event Handling in Java (AWT & Swing)
Java follows the Delegation Event Model (DEM) for GUI event handling.
• Event Source → The component that generates an event (e.g., Button, TextField, Window).
• Event Object → Encapsulates details of the event (e.g., ActionEvent, KeyEvent).
• Event Listener → An interface that must be implemented to handle events.
👉 Flow:
Source (e.g., Button) → Event Object (e.g., ActionEvent) → Listener (ActionListener)
🔹 Common GUI Event Types and Listener Interfaces
1. ActionEvent
• Generated by:
o Button clicks (JButton, Button)
o Menu selections (MenuItem)
o Text field Enter key (JTextField)
• Listener Interface: ActionListener
• Method:
• void actionPerformed(ActionEvent e);
Example:
import [Link].*;
import [Link].*;
public class ActionEventExample {
public static void main(String[] args) {
Frame f = new Frame("ActionEvent Demo");
Button b = new Button("Click Me");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button Clicked!");
}
});
[Link](b);
[Link](300, 200);
[Link](new FlowLayout());
[Link](true);
}
}
2. ItemEvent
• Generated by:
o Checkboxes (Checkbox, JCheckBox)
o Radio buttons (JRadioButton)
o List/Choice components (Choice, JComboBox)
• Listener Interface: ItemListener
Method:
• void itemStateChanged(ItemEvent e);
3. KeyEvent
Generated by: Keyboard actions (press, release, type).
Listener Interface: KeyListener
Methods:
❖ void keyPressed(KeyEvent e);
❖ void keyReleased(KeyEvent e);
❖ void keyTyped(KeyEvent e);
4. MouseEvent
• Generated by: Mouse actions (click, press, release, enter, exit, move, drag).
• Listener Interfaces:
o MouseListener → handles click, press, release, enter, exit.
o MouseMotionListener → handles mouse movement and dragging.
• Methods:
• MouseListener
❖ void mouseClicked(MouseEvent e);
❖ void mousePressed(MouseEvent e);
❖ void mouseReleased(MouseEvent e);
❖ void mouseEntered(MouseEvent e);
❖ void mouseExited(MouseEvent e);
• // MouseMotionListener
• void mouseDragged(MouseEvent e);
• void mouseMoved(MouseEvent e);
5. WindowEvent
• Generated by: Window state changes (open, close, minimize, maximize).
• Listener Interface: WindowListener
• Methods:
❖ void windowOpened(WindowEvent e);
❖ void windowClosing(WindowEvent e);
❖ void windowClosed(WindowEvent e);
❖ void windowIconified(WindowEvent e);
❖ void windowDeiconified(WindowEvent e);
❖ void windowActivated(WindowEvent e);
❖ void windowDeactivated(WindowEvent e);
6. FocusEvent
Generated by: When a component gains or loses focus.
Listener Interface: FocusListener
Methods:
❖ void focusGained(FocusEvent e);
❖ void focusLost(FocusEvent e);
7. AdjustmentEvent
Generated by: Scrollbar adjustments.
Listener Interface: AdjustmentListener
Method:
• void adjustmentValueChanged(AdjustmentEvent e);
🔹 Summary Table
Event Type Listener Interface Common Source Components
ActionEvent ActionListener Button, TextField, MenuItem
ItemEvent ItemListener Checkbox, RadioButton, Choice
KeyEvent KeyListener Keyboard on any component
MouseEvent MouseListener, MouseMotionListener Mouse clicks, drags, moves
WindowEvent WindowListener Frame, Window
FocusEvent FocusListener Any focusable component
AdjustmentEvent AdjustmentListener Scrollbar
23. Discuss on the features of different Layout managers. .(R)(MAY 2021)(MAY 2022)(MAY
2023)
🔹 Layout Managers in Java
A Layout Manager is an object that controls the size, position, and alignment of components in a
container.
Java provides several built-in layout managers in the [Link] package.
1. FlowLayout
Default for: Panel (in AWT)
Features:
❖ Places components in a row, left to right (like text flow).
❖ When one row is filled, it moves to the next row.
❖ Alignment can be LEFT, CENTER (default), RIGHT.
❖ Gaps between components can be specified (horizontal & vertical).
✅ Example:
setLayout(new FlowLayout([Link], 20, 10));
2. BorderLayout
Default for: Frame (in AWT) and JFrame (in Swing).
Features:
❖ Divides container into 5 regions: NORTH, SOUTH, EAST, WEST, CENTER.
❖ Only one component per region.
❖ The CENTER expands to fill the remaining space.
❖ Useful for window-like applications.
✅ Example:
setLayout(new BorderLayout(10, 10));
add(new Button("North"), [Link]);
add(new Button("Center"), [Link]);
3. GridLayout
• Features:
❖ Divides the container into a grid of rows and columns.
❖ All cells are equal in size.
❖ Components are added row by row, left to right.
❖ Useful for calculators, forms, and tables.
Example:
setLayout(new GridLayout(2, 3, 10, 10)); // 2 rows, 3 columns
4. CardLayout
• Features:
❖ Allows only one component visible at a time (like a deck of cards).
❖ Other components remain hidden.
❖ Useful for wizards, tabbed panes, or step-by-step forms.
❖ Navigation is done using methods like next(), previous(), first(), last().
Example:
CardLayout cl = new CardLayout();
setLayout(cl);
[Link](container); // move to next card
5. GridBagLayout
• Features:
❖ Most flexible and complex layout manager.
❖ Divides space into a grid of rows and columns like GridLayout,
but cells can have different sizes and a component can span multiple cells.
❖ Controlled using GridBagConstraints (for weight, fill, anchor, padding, etc.).
❖ Used for complex professional UIs.
✅ Example:
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
6. BoxLayout
Part of: [Link] package (not AWT).
Features:
❖ Arranges components in a single row (X_AXIS) or single column (Y_AXIS).
❖ Useful for toolbars or vertically stacked components.
Example:
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
7. GroupLayout (Swing only)
• Introduced in: Java SE 6 (used in NetBeans GUI Builder).
• Features:
❖ Aligns components horizontally and vertically in groups.
❖ Useful for form designs (labels aligned with text fields).
❖ Complex but very powerful.
Comparison Table
Layout Manager Arrangement Style Key Features
FlowLayout Left to right, wraps Simple, aligns LEFT/CENTER/RIGHT
BorderLayout 5 regions (N, S, E, W, C) CENTER expands, one component per region
GridLayout Rows × Columns Equal cell sizes, row-wise placement
CardLayout One at a time Good for wizards, tab-like navigation
GridBagLayout Flexible grid Unequal cells, spanning, complex
BoxLayout X_AXIS or Y_AXIS Horizontal/Vertical stacking
GroupLayout Horizontal + Vertical groups Good for form-based GUIs
Summary:
❖ Use FlowLayout for simple row-based placement.
❖ Use BorderLayout for standard window structure.
❖ Use GridLayout for equal-sized grid components (like calculator).
❖ Use CardLayout for switching views.
❖ Use GridBagLayout for complex, fine-grained control.
❖ Use BoxLayout/GroupLayout (Swing) for modern UIs.
24. Explain the procedure for creating and importing packages in Java with examples.
.(R)(DEC 2022)(MAY 2022)
🔹 What is a Package in Java?
A package in Java is a mechanism to group related classes, interfaces, and sub-packages together.
It helps in:
• Organizing code (like folders in a file system).
• Avoiding name conflicts.
• Reusability of code.
• Access protection using access modifiers.
There are two types:
1. Built-in packages → e.g., [Link], [Link], [Link]
2. User-defined packages → created by programmers
🔹 Steps to Create and Use a Package
Step 1: Create a Package
• Use the package keyword at the top of your Java file.
• Save the file in a folder with the same package name.
Example: Creating a package
File: [Link]
// Step 1: Declare package name
package mypack;
public class MyPackageClass {
public void displayMessage() {
[Link]("Hello from mypack package!");
}
}
📌 Save this file inside a folder named mypack.
ProjectFolder
└── mypack
└── [Link]
✅ Step 2: Compile the Package
Use the -d option to tell the compiler where to create the package folder.
javac -d . [Link]
This creates the mypack folder (if not already present) and puts the compiled .class file inside it.
✅ Step 3: Import and Use the Package
Now, in another Java program, import the package and use the class.
File: [Link]
// Step 3: Import package
import [Link];
public class TestPackage {
public static void main(String[] args) {
MyPackageClass obj = new MyPackageClass();
[Link]();
}
}
Run the program:
javac [Link]
java TestPackage
✅ Output:
Hello from mypack package!
🔹 Different Ways to Import Packages
1. Import a single class
2. import [Link];
3. Import all classes in a package
4. import mypack.*;
5. Use fully qualified name (no import statement)
6. public class Test {
7. public static void main(String[] args) {
8. [Link] obj = new [Link]();
9. [Link]();
10. }
11. }
🔹 Sub-Packages
Packages can have sub-packages (like directories inside directories).
Example: package [Link];
File structure:
ProjectFolder
└── university
└── students
└── [Link]
Compile:
javac -d . [Link]
Import:
import [Link];
🔹 Key Points
• Package name must be lowercase (by convention).
• -d . ensures classes go into the correct folder structure.
• Default package = if you don’t specify a package, the class belongs to the default package.
✅ Summary:
1. Use package packagename; at the top of the file.
2. Compile with javac -d . [Link].
3. Import using import [Link]; or import packagename.*;.
DEC-2022
PART-C
20. Explain the data types in java? (R)
Java data types are categorized into two main groups: primitive data types and non-primitive (or
reference) data types.
Primitive Data Types in Java
Java has 8 primitive data types. They are the most basic data types and are not objects. They store
simple values directly in memory (stack) rather than references.
1. byte
• Size: 1 byte (8 bits)
• Range: -128 to 127
• Default Value: 0
• Usage: Useful when you need to save memory in large arrays or work with raw binary data.
Example:
public class ByteExample {
public static void main(String[] args) {
byte b = 100;
[Link]("Byte value: " + b);
}
}
2. short
• Size: 2 bytes (16 bits)
• Range: -32,768 to 32,767
• Default Value: 0
• Usage: Rarely used, but can be useful for large arrays where memory savings matter.
Example:
public class ShortExample {
public static void main(String[] args) {
short s = 32000;
[Link]("Short value: " + s);
}
}
3. int
• Size: 4 bytes (32 bits)
• Range: -2,147,483,648 to 2,147,483,647
• Default Value: 0
• Usage: Most commonly used for integers.
Example:
public class IntExample {
public static void main(String[] args) {
int i = 100000;
[Link]("Int value: " + i);
}
}
4. long
• Size: 8 bytes (64 bits)
• Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
• Default Value: 0L
• Usage: Used when int is not enough, e.g., big calculations, timestamps.
Example:
public class LongExample {
public static void main(String[] args) {
long l = 10000000000L; // Note the 'L' suffix
[Link]("Long value: " + l);
}
}
5. float
• Size: 4 bytes (32 bits)
• Range: Approx. 3.4e−038 to 3.4e+038
• Default Value: 0.0f
• Usage: For fractional values (single-precision). Less precise than double.
Example:
public class FloatExample {
public static void main(String[] args) {
float f = 10.5f; // Note the 'f' suffix
[Link]("Float value: " + f);
}
}
6. double
• Size: 8 bytes (64 bits)
• Range: Approx. 1.7e−308 to 1.7e+308
• Default Value: 0.0d
• Usage: Default type for decimal numbers (double-precision).
Example:
public class DoubleExample {
public static void main(String[] args) {
double d = 20.123456789;
[Link]("Double value: " + d);
}
}
7. boolean
• Size: Not precisely defined (depends on JVM, usually 1 bit is enough but stored as 1 byte)
• Values: true or false
• Default Value: false
• Usage: For logical values, conditions, flags.
Example:
public class BooleanExample {
public static void main(String[] args) {
boolean isJavaFun = true;
[Link]("Is Java fun? " + isJavaFun);
}
}
8. char
• Size: 2 bytes (16 bits, because Java uses Unicode)
• Range: 0 to 65,535 ('\u0000' to '\uffff')
• Default Value: '\u0000' (null character)
• Usage: For storing characters (supports Unicode → can store any language character).
Example:
public class CharExample {
public static void main(String[] args) {
char c1 = 'A';
char c2 = '\u0906'; // Unicode for 'आ' (Hindi character)
[Link]("Char 1: " + c1);
[Link]("Char 2: " + c2);
}
}
Data Type Default Value Default size Range
Byte 0 1 byte or 8 bits -128 to 127
Short 0 2 bytes or 16 bits -32,768 to 32,767
Int 0 4 bytes or 32 bits 2,147,483,648 to 2,147,483,647
Long 0 8 bytes or 64 bits 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Float 0.0f 4 bytes or 32 bits 1.4e-045 to 3.4e+038
Double 0.0d 8 bytes or 64 bits 4.9e-324 to 1.8e+308
Char ‘u0000’ 2 bytes or 16 bits 0 to 65536
Boolean FALSE 1 byte or 2 bytes 0 or 1
Key Notes:
• Primitive data types are not objects (unlike wrapper classes like Integer, Double, etc.).
• Stored directly in memory stack, making them fast.
• Java is strictly typed: you must declare the type before using a variable.
• Default values apply only for instance variables, not local variables.
Non-Primitive Data Types
➢ Also called reference types or object types.
➢ They do not store the actual value directly. Instead, they store the reference (address) of
the object in memory.
➢ Created by programmers (unlike primitive types which are built-in).
➢ They can be null (unlike primitives).
➢ They support methods to perform operations.
Example: String s = "Hello";
Here, s is a reference to a String object.
3. Types of Non-Primitive Data Types in Java
(a) String
• A sequence of characters, stored as an object of the String class.
public class StringExample {
public static void main(String[] args) {
String name = "Java"; // String literal
String lang = new String("Programming"); // using new keyword
[Link]([Link]()); // JAVA
[Link]([Link]()); // 11
}
}
(b) Arrays
1. A collection of similar data types, stored in contiguous memory.
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
[Link](numbers[2]); // 30
[Link]("Length: " + [Link]); // 4
}
}
(c) Classes
• A blueprint for objects.
• Contains fields (variables) and methods.
class Car {
String color;
int speed;
void drive() {
[Link]("Car is driving at " + speed + " km/h");
}
}
public class ClassExample {
public static void main(String[] args) {
Car c = new Car(); // object created
[Link] = "Red";
[Link] = 100;
[Link](); // Car is driving at 100 km/h
}
}
(d) Objects
• An instance of a class.
• Created using new keyword.
Car myCar = new Car();
(e) Interfaces
1. A special type used to achieve abstraction and multiple inheritance.
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
[Link]("Woof Woof");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Animal a = new Dog();
[Link](); // Woof Woof
}
}
Summary
Non-primitive data types in Java are reference types like String, Arrays, Classes, Objects,
Interfaces, etc. They allow object-oriented programming, provide more flexibility, and can hold
multiple values or methods, unlike primitives.
21. Explain the various abstract classes with example?
In Java, an abstract class is a class that is declared using the abstract keyword. It cannot be
instantiated directly, but it can be subclassed. Abstract classes are used when you want to provide
partial implementation that must be completed by child classes.
🔹 Key Points about Abstract Classes
• Declared with abstract keyword.
• abstract class Shape { ... }
• Can have abstract methods (without body) and concrete methods (with body).
• Cannot be instantiated directly:
• Shape s = new Shape(); // Error
• A subclass must provide implementation for all abstract methods (unless it is also abstract).
• Can have constructors, fields, static methods, final methods, etc.
• Supports inheritance (only one abstract parent since Java doesn’t support multiple
inheritance with classes).
🔹 Types of Abstract Classes (based on usage)
1. Pure Abstract Class (only abstract methods)
Behaves like an interface (before Java 8).
abstract class Animal {
abstract void sound();
}
class Dog extends Animal {
void sound() {
[Link]("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
[Link](); // Output: Woof!
}
}
2. Partially Implemented Abstract Class
Contains both abstract and concrete methods.
abstract class Vehicle {
abstract void start();
void stop() {
[Link]("Vehicle stopped");
}
}
class Car extends Vehicle {
void start() {
[Link]("Car started");
}
}
public class Main {
public static void main(String[] args) {
Vehicle v = new Car();
[Link](); // Output: Car started
[Link](); // Output: Vehicle stopped
}
}
3. Abstract Class with Constructors
Used to initialize fields that subclasses can use.
abstract class Person {
String name;
Person(String name) {
[Link] = name;
}
abstract void display();
}
class Student extends Person {
Student(String name) {
super(name);
}
void display() {
[Link]("Student name: " + name);
}
}
public class Main {
public static void main(String[] args) {
Person p = new Student("Alice");
[Link](); // Output: Student name: Alice
}
}
4. Abstract Class with Final & Static Methods
• final methods cannot be overridden.
• static methods belong to the class, not the object.
abstract class Bank {
abstract double rateOfInterest();
final void displayBank() {
[Link]("Welcome to the bank");
}
static void bankPolicy() {
[Link]("All banks follow RBI guidelines");
}
}
class SBI extends Bank {
double rateOfInterest() {
return 6.5;
}
}
public class Main {
public static void main(String[] args) {
Bank b = new SBI();
[Link](); // Output: Welcome to the bank
[Link]([Link]()); // Output: 6.5
[Link](); // Output: All banks follow RBI guidelines
}
}
5. Abstract Class Extending Another Abstract Class
You can have multiple levels of abstraction.
abstract class Shape {
abstract void draw();
}
abstract class Polygon extends Shape {
abstract int sides();
}
class Triangle extends Polygon {
void draw() {
[Link]("Drawing a Triangle");
}
int sides() {
return 3;
}
}
public class Main {
public static void main(String[] args) {
Polygon p = new Triangle();
[Link](); // Output: Drawing a Triangle
[Link]([Link]()); // Output: 3
}
}
In summary, abstract classes in Java can be:
• Pure abstract (only abstract methods).
• Partially implemented (mix of abstract + concrete methods).
• With constructors.
• With final & static methods.
• Hierarchical (abstract class extending another abstract class).
[Link] a detailed notes on java packages? (R)
Java Packages
1. Introduction
A package in Java is a collection of classes, interfaces, and sub-packages grouped together for
modularity, reusability, and maintainability.
It acts like a folder in a file system that stores related Java files.
2. Types of Packages
Java provides two types of packages:
(a) Built-in Packages (Predefined Packages)
• Already available in the Java API.
• Examples:
o [Link] → Core classes (String, Math, Object, etc.)
o [Link] → Utility classes (ArrayList, HashMap, Date, etc.)
o [Link] → Input/Output classes (File, BufferedReader, etc.)
o [Link] → Database connectivity.
o [Link] → GUI components.
Usage example:
import [Link];
class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("Java");
[Link]("Package");
[Link](list);
}
}
(b) User-defined Packages
• Created by programmers to organize code.
Steps to create:
• Create a package
// File: [Link]
package mypack;
public class MyClass {
public void display() {
[Link]("Hello from MyClass inside mypack!");
}
}
1. Compile with package
javac -d . [Link]
(-d . creates the package folder automatically)
• Use the package
import [Link];
class Test {
public static void main(String[] args) {
MyClass obj = new MyClass();
[Link]();
}
}
3. Advantages of Packages
Modularity → Organizes classes logically.
Reusability → Classes can be reused across projects.
Name conflict resolution → Two classes with the same name can exist in different packages.
Access control → Helps in setting visibility of classes/methods.
Maintainability → Easier to manage large projects.
✅ In summary:
• Package = Folder + Namespace.
• Helps organize, reuse, and secure Java code.
• Can be built-in (API) or user-defined.
[Link] the life cycle of applet program?
What is an Applet?
An applet is a Java program that runs inside a web browser or an applet viewer. It is a subclass of
[Link] (or [Link] for Swing). Unlike standalone Java applications (with
main()), an applet’s execution is controlled by the browser or JVM applet container
Applet Life Cycle Methods
1. init()
• Called once when the applet is first loaded.
• Used to initialize variables, load resources (images, fonts, colors, etc.), and set up the UI.
• Similar to a constructor in a normal Java program.
public void init() {
[Link]("Applet initialized.");
}
2. start()
• Called after init() or whenever the applet becomes active (e.g., when the user revisits the
page).
• Used to start animations, threads, or other activities that should run while the applet is
active.
public void start() {
[Link]("Applet started.");
}
3. paint(Graphics g)
• Called automatically whenever the applet needs to be redrawn (first display, resizing,
overlapping window cleared).
• Contains code for drawing text, shapes, or images on the applet window.
public void paint(Graphics g) {
[Link]("Hello, Applet!", 50, 50);
}
4. stop()
• Called when the applet is no longer visible or active (e.g., when the user moves to another
page).
• Used to pause animations or threads to save resources.
public void stop() {
[Link]("Applet stopped.");
}
5. destroy()
• Called only once, just before the applet is terminated/unloaded from memory.
• Used for cleanup activities such as releasing resources (closing files, network connections,
etc.).
public void destroy() {
[Link]("Applet destroyed.");
}
Order of Execution
The life cycle sequence is as follows:
• init() → (initialization)
• start() → (applet becomes active)
• paint() → (display output)
• stop() → (when applet is not visible)
• destroy() → (when applet is unloaded)
Diagram of Applet Life Cycle
Example Program
import [Link];
import [Link];
/* <applet code="AppletLifeCycle" width=300 height=200></applet> */
public class AppletLifeCycle extends Applet {
public void init() {
[Link]("init() called");
}
public void start() {
[Link]("start() called");
}
public void paint(Graphics g) {
[Link]("Applet Life Cycle Demo", 50, 100);
[Link]("paint() called");
}
public void stop() {
[Link]("stop() called");
}
public void destroy() {
[Link]("destroy() called");
}
}
Output (Console & Applet Window)
Console Output (sequence):
init() called
start() called
paint() called
(When window is minimized/restored or page changes)
stop() called
start() called
paint() called
(On closing the applet viewer/browser)
stop() called
destroy() called
Applet Window Output:
• Displays the text: “Applet Life Cycle Demo” at the specified coordinates.
In summary:
• Applets do not have a main() method.
• Their life cycle is controlled by init → start → paint → stop → destroy.
• Each method has a special role in initialization, execution, display, pausing, and cleanup.
[Link] explain the fundamentals of exception handling?
Exception Handling in Java – Fundamentals
Exception handling in Java is a mechanism to handle runtime errors so that the normal flow of the
program can be maintained. Instead of crashing the program when an error occurs, Java provides
structured ways to detect and manage these situations.
1. Need for Exception Handling
• Errors such as dividing by zero, invalid input, file not found, or array out of bounds can occur
at runtime.
• Without exception handling, such errors terminate the program abruptly.
• Exception handling ensures robustness and graceful recovery from such conditions.
2. Exception Hierarchy
• All exceptions and errors inherit from the Throwable class.
o Error → serious problems beyond programmer control (e.g., OutOfMemoryError),
usually not handled.
o Exception → conditions a program can handle.
▪ Checked Exceptions: Must be handled or declared using throws. Example:
IOException.
▪ Unchecked Exceptions: Subclasses of RuntimeException, occur due to
programming errors. Example: NullPointerException, ArithmeticException.
3. Key Keywords
• try → Defines a block where exceptions may occur.
• catch → Handles the exception thrown in the try block.
• finally → Always executes, used for cleanup operations (e.g., closing files).
• throw → Used to explicitly throw an exception.
• throws → Declares exceptions a method may throw.
4. Basic Example
class ExceptionDemo {
public static void main(String[] args) {
try {
int result = 10 / 0; // Risky code
} catch (ArithmeticException e) {
[Link]("Error: Division by zero!");
} finally {
[Link]("Program ends gracefully.");
}
}
}
Output:
Error: Division by zero!
Program ends gracefully.
5. Advantages
• Maintains program normal flow.
• Provides separation of error-handling code from normal logic.
• Supports multiple exception handling.
• Allows creation of custom exceptions for application-specific errors.
✅ In summary: Exception handling in Java provides a systematic way of handling runtime errors
using the try-catch-finally mechanism, improving program reliability, maintainability, and user
experience.
DEC-2023
PART-C
20. Explain the various control statement in JAVA (R)
1. Selection Statements (Decision making)
Used to choose one block of code among many.
If statement – Executes block only if condition is true.
Example
If (a > b) {
[Link](“a is greater”);
}
❖ If–else – Executes one block if true, another if false.
❖ If–else–if ladder – Multiple conditions.
❖ Switch statement – Selects one case among many.
Switch(day) {
Case 1: [Link](“Monday”); break;
Case 2: [Link](“Tuesday”); break;
Default: [Link](“Invalid day”);
}
2. Iteration Statements (Loops)
Used to repeat code multiple times.
• for loop – Executes block for fixed number of times.
• while loop – Executes block while condition is true.
• do–while loop – Executes at least once, then checks condition.
Example:
for(int i=1; i<=5; i++) {
[Link](i);
}
3. Jump Statements
Used to change the normal flow of execution.
• break – Exits from loop or switch.
• continue – Skips current iteration, goes to next.
• return – Exits from method and returns value.
Example:
for(int i=1; i<=5; i++) {
if(i==3) continue;
[Link](i);
}
21. Write a JAVA program to illustrate the use of Constructor.
Constructor in Java
❖ A constructor is a special method in Java used to initialize objects.
❖ It has the same name as the class and does not have a return type.
❖ It is called automatically when an object is created.
Types of Constructors
❖ Default Constructor – No parameters, provides default values.
❖ Parameterized Constructor – Accepts arguments to initialize objects.
Program to demonstrate Constructor
Class Student {
String name;
Int age;
Default Constructor
Student() {
Name = “Unknown”;
Age = 0;
}
Parameterized Constructor
Student(String n, int a) {
Name = n;
Age = a;
}
Void display() {
[Link](“Name: “ + name + “, Age: “ + age);
}
}
Public class Constructor
Example
{
Public static void main(String[] args) {
// Using default constructor
Student s1 = new Student();
// Using parameterized constructor
Student s2 = new Student(“Rahul”, 20);
// Displaying data
[Link]();
[Link]();
}
}
22. What is synchronization? Explain the Implementation of this concept in Java
with Examples?
What is Synchronization?
❖ Synchronization in Java is a technique that allows only one thread to access a shared resource
at a time.
❖ It Is used in multithreading to avoid data inconsistency and race conditions.
❖ Example: If two threads try to update the same variable at the same time, synchronization
ensures one thread completes before the other starts.
Implementation of Synchronization in Java
Synchronized Method
A method is declared with the keyword synchronized.
• Only one thread can execute it at a time
Class Table {
Synchronized void printTable(int n) {
For(int i=1; i<=5; i++) {
[Link](n * i);
Try { [Link](500); } catch(Exception e) {}
}
}
}
Class MyThread1 extends Thread {
Table t;
MyThread1(Table t) { this.t = t; }
Public void run() { [Link](5); }
}
Class MyThread2 extends Thread {
Table t;
MyThread2(Table t) { this.t = t; }
Public void run() { [Link](100); }
}
Public class SyncExample {
Public static void main(String[] args) {
Table obj = new Table();
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
[Link]();
[Link]();
}
}
23. Explain the occurrence of any three Exceptions. ( R)
What are Exceptions?
❖ An Exception in Java is an error condition that occurs during program execution.
❖ It disrupts the normal flow of the program.
❖ Java provides a mechanism called exception handling using try, catch, and throw.
Three Common Exceptions in Java
1. ArithmeticException
Occurs when an illegal arithmetic operation happens.
Example: Division by zero.
Public class Example1 {
Public static void main(String[] args) {
Int a = 10, b = 0;
Try {
Int c = a / b; // error here
} catch (ArithmeticException e) {
[Link](“Cannot divide by zero!”);
}
}
}
2. NullPointerException
• Occurs when we try to use a null object reference.
• Example: Calling a method on a null object.
public class Example2 {
public static void main(String[] args) {
String str = null;
try {
[Link]([Link]()); // error here
} catch (NullPointerException e) {
[Link]("Object is null!");
}
}
}
ArrayIndexOutOfBoundsException
• Cause: Accessing array element outside valid index.
• Example: arr[10]; when array size is 5.
Public class Example3 {
Public static void main(String[] args) {
Int arr[] = {1, 2, 3};
Try {
[Link](arr[5]); // invalid index
} catch (ArrayIndexOutOfBoundsException e) {
[Link](“Index out of range!”);
}
}
}
24. Write a Java program to illustrate the usage of Any two AWT controls IN JAVA
AWT (Abstract Window Toolkit) is used to create GUI (Graphical User Interface)
applications in Java.
Common controls: Label, Button, TextField, Checkbox, TextArea etc.
Program: Using Button and Label (two controls)
Import [Link].*;
Import [Link].*;
Public class AWTExample extends Frame implements ActionListener {
Label label;
Button button;
AWTExample() {
// Create Label
Label = new Label(“Click the button”);
[Link](50, 100, 200, 30);
// Create Button
Button = new Button(“Click Me”);
[Link](50, 150, 80, 30);
// Add ActionListener to button
[Link](this);
// Add controls to Frame
Add(label);
Add(button);
// Frame properties
setSize(300, 300);
setLayout(null);
setVisible(true);
}
// Action performed when button is clicked
Public void actionPerformed(ActionEvent e) {
[Link](“Button Clicked!”);
}
Public static void main(String[] args) {
New AWTExample();
}
}
JUN-2022
PART-C
[Link] the features of java in detail?(R)
Java is a high-level, object-oriented programming language. This language is very easy to
learn and widely used. It is known for its platform independence, reliability, and security. It follows
one principle, that is "Write Once, Run Anywhere" principle. It supports various features like
portability, robustness, simplicity, multithreading, and high performance, which makes it a popular
choice for beginners as well as for developers.
In this article, we are going to discuss the important features of Java programming language.
Features in Java
1. Simple Syntax
Java syntax is very straightforward and very easy to learn. Java removes complex features like
pointers and multiple inheritance, which makes it a good choice for beginners.
Example: Basic Java Program
// Java program to Demonstrate the Basic Syntax
import [Link].*;
class Geeks {
public static void main(String[] args)
{
[Link]("GeeksForGeeks!");
}
}
Output
GeeksForGeeks!
Explanation: In Java, the execution starts with the main method, which is the entry point of any Java
application. The [Link] statement prints "GeeksForGeeks!". The import
[Link].*; statement means we are putting input-output functionalities
2. Object Oriented
Java is a pure object-oriented language. It supports core OOP concepts like,
• Class
• Objects
• Inheritance
• Encapsulation
• Abstraction
• Polymorphism
Example: The below Java program demonstrates the basic concepts of OOPs.
// Java program to demonstrate the basic concepts of oops
// like class, object, Constructor and method
import [Link].*;
class Student {
int age;
String name;
public Student(int age, String name)
{
[Link] = age;
[Link] = name;
}
// This method display the details of the student
void display()
{
[Link]("Name is: " + name);
[Link]("Age is: " + age);
}
}
class Geeks {
public static void main(String[] args)
{
Student student = new Student(22, "GFG");
[Link]();
}
}
Output
Name is: GFG
Age is: 22
Explanation: In the above example, we have created a Student class and inside the class we have
declared two variables age and name. A constructor is used to initialize these variables when an object
of the Student class is created. In the main method we are creating an object of the student class and
then we are calling the display method which is prinitng the name and age on the console.
3. Platform Independent
Java is platform-independent because of Java Virtual Machine (JVM).
1. When we write Java code, it is first compiled by the compiler and then converted into bytecode
(which is platform-independent).
2. This byte code can run on any platform which has JVM installed.
4. Interpreted
Java code is not directly executed by the computer. It is first compiled into bytecode. This byte code
is then understand by the JVM. This enables Java to run on any platform without rewriting code.
5. Scalable
Java can handle both small and large-scale applications. Java provides features
like multithreading and distributed computing that allows developers to manage loads more easily.
6. Portable
When we write a Java program, the code first get converted into bytecode and this bytecode does not
depend on any operating system or any specific computer. We can simply execute this bytecode on
any platform with the help of JVM. Since JVMs are available on most devices and that's why we can
run the same Java program on different platform
7. Secured and Robust
Java is a reliable programming language because it can catch mistakes early while writing the code
and also keeps checking for errors when the program is running. It also has a feature called exception
handling that helps deal with unexpected problems smoothly.
8. Memory Management
Memory management in Java is automatically handled by the Java Virtual Machine (JVM).
• Java garbage collector reclaim memory from objects that are no longer needed.
• Memory for objects are allocated in the heap
• Method calls and local variables are stored in the stack.
9. High Performance
Java is faster than old interpreted languages. Java program is first converted into bytecode which is
faster than interpreted code. It is slower than fully compiled languages like C or C++ because of
interpretation and JIT compilation process. Java performance is improve with the help of Just-In-Time
(JIT) compilation, which makes it faster than many interpreted languages but not as fast as fully
compiled languages.
10. Multithreading
Multithreading in Java allows multiple threads to run at the same time.
• It improves CPU utilization and enhancing performance in applications that require concurrent
task execution.
• Multithreading is especially important for interactive and high-performance applications, such as
games and real-time systems.
• Java provides build in support for managing multiple threads. A thread is known as the smallest
unit of execution within a process.
Example: Basic Multithreadig in Java
// Java program to demonstrate multithreading
class MyThread extends Thread {
public void run() {
[Link]("Thread is running...");
}
}
public class Geeks {
public static void main(String[] args) {
MyThread thread = new MyThread();
// Starts the thread
[Link]();
}
}
Output
Thread is running...
Explanation: The MyThread class extends the Thread class and overrides the run method. In the
main method, an object of MyThread is created, and the start method is called to begin the execution
of the thread. The run method is executed in a separate thread, printing "Thread is running..." to the
console.
11. Rich Standard Library
Java provides various pre-built tools and libraries which is known as Java API. Java API is used to
cover tasks like file handling, networking, database connectivity (JDBC), security, etc. With the help
of these libraries developers save a lot of time and ready to use solutions and can also build a
powerful application.
12. Functional Programming Features
Since Java 8, the language has introduced functional programming features such as:
• lambda expression let us to write small block of code in a very easy way without creating full
methods.
• Stream API allows data to be processed easily, Instead of writing long loops we can just filter,
change, or combine data in a few lines.
• Functional interfaces are inteface that contains only one method. They work perfectly with
lambda expressions and help us write flexible and reusable code.
Example:
// Java program demonstrating lambda expressions
interface Lambda {
int operate(int a, int b);
}
public class Geeks {
public static void main(String[] args) {
// Lambda expression
Lambda add = (a, b) -> a + b;
[Link]("Addition: " + [Link](2, 3));
}
}
Output
Addition: 5
Explanation: A functional interface Lambda is defined with a single method operate. A lambda
expression (a, b) -> a + b is used to implement the operate method. The main method calls the operate
method using the lambda expression and prints the result.
13. Integration with Other Technologies
Java can easily work with many languages and tools as well. For example, Java can connect with C
and C++ with the help of Java Native Interface (JNI). Java is very popular for building websites
and webservices like RESTful & SOAP. In Java we can use JDBC for databse connectivity also
Java is the main language for android development. As we can see Java works so well with so many
different technologies that's the reason developer prefers Java more to create scalable and powerful
application.
14. Support for Mobile and Web Application
Java offers support for both web and mobile applications.
• For web development: Java offers technologies like JSP and Servlets, along with frameworks
like Spring and Springboot, which makes it easier to build web applications.
• For mobile development: Java is the main language for Android app development. The Android
SDK uses special version of Java and its various tools to build mobile apps for Android devices.
15. Documentation and Community Support
Java provide documentation which includes guides, API references, and tutorials for easy learning.
Java has a large and active global community contributing to open-source projects, and resources.
This community support helps developers solve problems and stay updated with new advancements.
[Link] on the features of string class.?
Overview of the String Class
• In Java, String is a class in [Link] package.
• It is immutable, meaning once a string object is created, it cannot be changed.
• Strings are widely used to represent text data.
• Java provides two ways to create a string:
o Using string literals
o String s1 = "Hello";
▪ Stored in the String Constant Pool (SCP) for memory efficiency.
o Using new keyword
o String s2 = new String("Hello");
▪ Stored in heap memory, outside SCP.
Key Features of String Class
1. Immutability
➢ Once a String object is created, its content cannot be changed.
➢ Any modification creates a new string object.
Example:
String s = "Java";
[Link](" Programming");
[Link](s); // Output: Java
• s still refers to "Java". A new object "Java Programming" is created but not referenced.
2. String Constant Pool (SCP)
• Java optimizes memory by storing string literals in SCP.
• If two strings have the same literal, they refer to the same object.
Example:
String s1 = "Hello";
String s2 = "Hello";
[Link](s1 == s2); // true (same reference in SCP)
3. Efficient Memory Management
• Because of SCP and immutability, strings are memory efficient.
• Instead of creating duplicate objects, Java reuses literals.
4. Final Class
• String is declared as final, so it cannot be inherited.
• Ensures immutability and security (important in passwords, URLs, network connections).
5. Implements Serializable, Comparable, and CharSequence Interfaces
• Serializable → String objects can be serialized.
• Comparable<String> → Strings can be compared lexicographically.
• CharSequence → Provides character sequence manipulation.
6. Overridden Methods
• toString() → returns the string value itself.
• equals() → compares content (not reference).
• hashCode() → overridden for correct hashing behavior.
Example:
String s1 = new String("Hello");
String s2 = new String("Hello");
[Link]([Link](s2)); // true (content comparison)
[Link](s1 == s2); // false (different objects in heap)
7. Rich Built-in Methods
The String class provides 50+ methods. Some important ones:
Length:
"Hello".length(); // 5
Substring:
"HelloWorld".substring(0,5); // "Hello"
Case conversion:
"java".toUpperCase(); // "JAVA"
Trim spaces:
" Hi ".trim(); // "Hi"
Search characters:
"Java".charAt(1); // 'a'
"Java".indexOf('v'); // 2
Replace:
"Java".replace("a","o"); // "Jovo"
Split:
"A,B,C".split(","); // ["A", "B", "C"]
8. String Concatenation
• Using + operator or concat() method.
• At compile-time, the + operator is replaced by [Link]() for efficiency.
Example:
String s1 = "Hello";
String s2 = "World";
String s3 = s1 + " " + s2; // Compiler converts to StringBuilder
[Link](s3); // "Hello World"
9. String Comparison
• equals() → compares content.
• == → compares references.
• compareTo() → lexicographical comparison.
Example:
String s1 = "abc";
String s2 = "xyz";
[Link]([Link](s2)); // negative (abc < xyz)
10. Immutable but Thread-Safe
• Since strings cannot be modified, they are thread-safe by nature.
No synchronization required.
11. Interning
• The intern() method forces a string into the SCP.
String s1 = new String("Hello");
String s2 = [Link]();
String s3 = "Hello";
[Link](s2 == s3); // true
Why String is Immutable in Java?
• Security → Strings are used in sensitive data (passwords, network connections).
• Caching in SCP → Allows reuse of literals.
• Thread-safety → Multiple threads can safely share strings.
• Hashing → Used in collections (e.g., HashMap), immutability ensures hash code
consistency.
✅ IIn short:
The String class in Java is immutable, final, memory-efficient, secure, thread-safe, and comes with
powerful built-in methods for text manipulation.
[Link] the method of defining and importing packages? (R)
PACKAGES IN JAVA:
A package in Java is like a folder that groups related classes, interfaces, and sub-packages
together.
It helps in:
• Organizing code.
• Avoiding naming conflicts.
• Providing access control.
• Reusability.
1. Defining a Package
To create a package, use the package keyword at the top of your Java file.
Syntax:
package packageName;
public class ClassName {
// code here
}
Example: Create a package
Suppose you want to create a package called myPackage:
// File: [Link]
package myPackage;
public class MyClass {
public void displayMessage() {
[Link]("Hello from MyClass in myPackage!");
}
}
Here:
package myPackage; tells Java that this class belongs to the package myPackage.
You must save this file inside a folder named myPackage (myPackage/[Link]).
Compiling the package:
javac -d . [Link]
-d . tells the compiler to put the .class file in the right package folder (creates
myPackage/[Link]).
2. Importing a Package
If you want to use MyClass from myPackage in another program, you need to import it.
Ways to Import a Package
a) Import a specific class
import [Link];
public class Test {
public static void main(String[] args) {
MyClass obj = new MyClass();
[Link]();
}
}
b) Import all classes from a package (wildcard *)
import myPackage.*;
public class Test {
public static void main(String[] args) {
MyClass obj = new MyClass();
[Link]();
}
}
* imports all classes but not sub-packages.
c) Fully Qualified Name (FQN) (No import)
public class Test {
public static void main(String[] args) {
[Link] obj = new [Link]();
[Link]();
}
}
3. Types of Packages
Built-in Packages → e.g., [Link], [Link], [Link], etc.
Example:
import [Link];
public class BuiltInPackageExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Hello, " + name);
}
}
User-defined Packages → packages you create (like myPackage).
4. Sub-packages
You can also have nested packages:
package [Link];
public class SubClass {
public void show() {
[Link]("Inside subPackage!");
}
}
Importing:
import [Link];
5. Static Import
If you want to use static members of a class without writing the class name:
import static [Link].*;
public class StaticImportExample {
public static void main(String[] args) {
[Link](sqrt(16)); // instead of [Link](16)
[Link](pow(2, 3)); // instead of [Link](2, 3)
}
}
[Link] of features of layout managers.? (R )
Layout Managers in Java
In Java Swing (and AWT), Layout Managers are objects that control the size and position of
components (like buttons, labels, text fields) inside a container (like JFrame, JPanel, etc.).
Without a layout manager, you would have to manually set the position and size of each component
using absolute positioning (setBounds()), which is not flexible and doesn’t adapt to different screen
sizes, fonts, or resolutions.
So, Layout Managers automate component arrangement and make GUIs more flexible and
platform-independent.
Features of Layout Managers
Automatic Component Arrangement
Components are arranged according to specific rules of the layout (row, column, grid, flow, etc.).
You don’t need to specify exact x-y coordinates.
Platform Independence
Layout managers adapt automatically to different screen resolutions, window resizing, and fonts.
Ensures GUI looks consistent across devices.
Resizing Support
When the container (like JFrame) is resized, layout managers rearrange components dynamically.
Prevents overlapping or hidden components.
Ease of Use
You just add components; the layout manager decides the best placement.
No need for manual pixel-perfect alignment.
Multiple Layout Options
Java provides different managers, each suitable for a different kind of arrangement:
FlowLayout → sequential flow (like words in a paragraph)
BorderLayout → divides into regions (North, South, East, West, Center)
GridLayout → table-like rows and columns
GridBagLayout → flexible grid with constraints
BoxLayout → arranges in a single row or column
GroupLayout → for advanced UI (used in NetBeans GUI Builder)
Combination Support
You can nest containers with different layout managers for complex GUIs.
Example: JFrame with BorderLayout → inside center panel uses GridLayout.
Consistency Across Look-and-Feel
Layout managers adjust when you change the UI theme (Metal, Nimbus, Windows look-and-feel,
etc.).
Common Layout Managers with Examples
1. FlowLayout (Default for JPanel)
Components placed left to right, wrapping like text.
import [Link].*;
import [Link].*;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");
[Link](new FlowLayout());
for(int i=1; i<=5; i++) {
[Link](new JButton("Button " + i));
}
[Link](300, 200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
2. BorderLayout (Default for JFrame)
Divides container into 5 regions: NORTH, SOUTH, EAST, WEST, CENTER.
[Link](new BorderLayout());
[Link](new JButton("North"), [Link]);
[Link](new JButton("South"), [Link]);
[Link](new JButton("East"), [Link]);
[Link](new JButton("West"), [Link]);
[Link](new JButton("Center"), [Link]);
3. GridLayout
Arranges components in rows and columns (like a table).
[Link](new GridLayout(2, 3)); // 2 rows, 3 columns
for(int i=1; i<=6; i++) {
[Link](new JButton("Btn " + i));
}
4. BoxLayout
Aligns components in single row (X_AXIS) or column (Y_AXIS).
JPanel panel = new JPanel();
[Link](new BoxLayout(panel, BoxLayout.Y_AXIS));
[Link](new JButton("One"));
[Link](new JButton("Two"));
[Link](new JButton("Three"));
5. GridBagLayout (Most Flexible)
Provides a grid-based system with constraints like cell span, alignment, and weight.
Useful for complex forms and professional GUIs.
Advantages of Using Layout Managers
No need to worry about exact positions.
Flexible and adaptive GUI.
Cross-platform and resolution-independent.
Easier to maintain than absolute positioning.
Disadvantages
Sometimes less control than absolute positioning.
Complex layouts (e.g., GridBagLayout) can be harder to configure.
Slightly more overhead compared to manually positioning.
[Link] on working with colors and fonts.?
Java provides rich support for Colors and Fonts mainly through the AWT (Abstract
Window Toolkit) and Swing libraries. These are essential for creating Graphical User Interfaces
(GUIs).
1. Working with Colors in Java
Java represents colors using the [Link] class.
Creating Colors
The Color class provides several ways to define colors:
(a) Predefined Colors
import [Link].*;
public class PredefinedColors {
public static void main(String[] args) {
Color c1 = [Link]; // predefined color constant
Color c2 = [Link]; // predefined color
Color c3 = [Link]; // predefined color
[Link]("Predefined color: " + c1);
}
}
Output:
Predefined color: [Link][r=255,g=0,b=0]
(b) RGB Values
Color customColor = new Color(100, 150, 200); // RGB (0–255)
(c) RGBA (with Transparency)
Color transparent = new Color(255, 0, 0, 128); // last param = alpha (0=transparent, 255=opaque)
(d) Using Hex Code
Color hexColor = [Link]("#FF5733"); // decode hex string
Getting Color Components
Color c = new Color(70, 130, 180); // SteelBlue
[Link]("Red: " + [Link]());
[Link]("Green: " + [Link]());
[Link]("Blue: " + [Link]());
[Link]("Alpha: " + [Link]());
Output:
Red: 70
Green: 130
Blue: 180
Alpha: 255
Example: Using Color in Swing
import [Link].*;
import [Link].*;
public class ColorExample extends JPanel {
public void paintComponent(Graphics g) {
[Link](g);
setBackground([Link]); // panel background
[Link]([Link]);
[Link](50, 50, 100, 100); // filled rectangle
[Link](new Color(0, 255, 0));
[Link](200, 50, 100, 100); // filled circle
[Link]([Link]);
[Link]("Hello Colors!", 150, 200); // text with color
}
public static void main(String[] args) {
JFrame frame = new JFrame("Color Example");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](400, 300);
[Link](new ColorExample());
[Link](true);
}
}
This program shows red square, green circle, and cyan text on a black background.
2. Working with Fonts in Java
Fonts in Java are handled using the [Link] class.
Creating Fonts
(a) Constructor
Font f = new Font("Serif", [Link], 20);
Parameters:
Name: "Serif", "SansSerif", "Monospaced", or system-installed fonts.
Style: [Link], [Link], [Link].
Size: in points (px-like units).
(b) Deriving New Fonts
Font f1 = new Font("SansSerif", [Link], 18);
Font f2 = [Link]([Link], 24f); // new bold 24-size font
(c) Getting Available Fonts
import [Link].*;
public class AvailableFonts {
public static void main(String[] args) {
GraphicsEnvironment ge = [Link]();
String[] fonts = [Link]();
for (String font : fonts) {
[Link](font);
}
}
}
This prints all fonts installed on your system.
Example: Using Font in Swing
import [Link].*;
import [Link].*;
public class FontExample extends JPanel {
public void paintComponent(Graphics g) {
[Link](g);
[Link]([Link]);
Font f1 = new Font("Serif", [Link], 20);
[Link](f1);
[Link]("Plain Serif 20", 50, 50);
Font f2 = new Font("SansSerif", [Link], 24);
[Link](f2);
[Link]("Bold SansSerif 24", 50, 100);
Font f3 = new Font("Monospaced", [Link], 28);
[Link](f3);
[Link]("Italic Monospaced 28", 50, 150);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Font Example");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](500, 300);
[Link](new FontExample());
[Link](true);
}
}
This displays different text in different fonts, sizes, and styles.
3. Combining Fonts and Colors
import [Link].*;
import [Link].*;
public class FontColorCombo extends JPanel {
public void paintComponent(Graphics g) {
[Link](g);
[Link](new Font("SansSerif", [Link], 22));
[Link]([Link]);
[Link]("Red Bold Text", 50, 50);
[Link](new Font("Serif", [Link], 26));
[Link](new Color(0, 128, 0));
[Link]("Green Italic Text", 50, 100);
[Link](new Font("Monospaced", [Link], 18));
[Link]([Link]);
[Link]("Blue Monospaced Text", 50, 150);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Font + Color Example");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](500, 250);
[Link](new FontColorCombo());
[Link](true);
}
}
4. Key Notes
Color handles RGB, RGBA, and predefined colors.
Font allows control over name, style, and size.
Graphics object is used to apply colors and fonts in Swing/AWT components.
Always override paintComponent(Graphics g) for custom painting in Swing.
Use Graphics2D for advanced features like anti-aliasing and transformations.
In short:
Colors enhance visual appeal (backgrounds, shapes, text).
Fonts control text style and readability.
Together, they make Java GUIs attractive and professional.
MAY 2021
PART-C
20. State the characteristics of JAVA. Explain.
Characteristics of Java
Simple
Java is designed to be easy to learn and use.
Its syntax is similar to C++ but simplified by removing complex features like pointers, operator
overloading, and multiple inheritance.
It provides an automatic garbage collector to handle memory management.
Object-Oriented
Everything in Java is treated as an object, which makes it easy to model real-world problems.
It follows principles of object-oriented programming (OOP) such as encapsulation, inheritance,
polymorphism, and abstraction.
Platform Independent
Java programs are compiled into bytecode, which can run on any machine with a Java Virtual
Machine (JVM).
This makes Java a “Write Once, Run Anywhere” (WORA) language.
Secure
Java provides strong security features:
No explicit use of pointers (avoids memory corruption).
Bytecode verification ensures safe code execution.
Built-in security APIs and the Java sandbox protect systems from malicious code.
Robust
Java emphasizes early error checking, strong memory management, and exception handling.
Automatic garbage collection reduces the risk of memory leaks and system crashes.
Distributed
Java supports distributed computing with technologies like RMI (Remote Method Invocation) and
CORBA.
The standard libraries make it easy to build applications across networks.
Multithreaded
Java has built-in support for multithreading, allowing multiple tasks to run concurrently.
This makes it suitable for interactive applications like games, animations, and real-time systems.
Portable
Java bytecode is platform-independent and does not rely on system-specific implementations.
Data types in Java have fixed sizes (unlike C/C++), ensuring consistent results across platforms.
High Performance (with JIT Compiler)
While interpreted languages are usually slow, Java uses a Just-In-Time (JIT) compiler that converts
bytecode into native machine code at runtime for faster execution.
Dynamic
Java supports dynamic linking (classes are loaded at runtime when needed).
It can adapt to evolving environments by loading new classes, libraries, and methods dynamically.
21. Write a program to display the customers electricity bills with overriding methods.
// Program to display Electricity Bills using Method Overriding
class Customer {
String name;
int units;
Customer(String name, int units) {
[Link] = name;
[Link] = units;
}
// Parent method (to be overridden)
double calculateBill() {
return 0; // Default implementation
}
void displayBill() {
[Link]("Customer: " + name);
[Link]("Units Consumed: " + units);
[Link]("Bill Amount: Rs." + calculateBill());
[Link]("-------------------------------");
}
}
// Domestic Customer
class DomesticCustomer extends Customer {
DomesticCustomer(String name, int units) {
super(name, units);
}
// Overriding calculateBill()
@Override
double calculateBill() {
return units * 5.0; // Domestic rate Rs. 5 per unit
}
}
// Commercial Customer
class CommercialCustomer extends Customer {
CommercialCustomer(String name, int units) {
super(name, units);
}
// Overriding calculateBill()
@Override
double calculateBill() {
return units * 8.0; // Commercial rate Rs. 8 per unit
}
}
// Main Class
public class ElectricityBill {
public static void main(String[] args) {
// Creating objects
Customer c1 = new DomesticCustomer("Ravi Kumar", 120);
Customer c2 = new CommercialCustomer("ABC Stores", 300);
// Display bills
[Link]();
[Link]();
}
}
RESULT:
Customer: Ravi Kumar
Units Consumed: 120
Bill Amount: Rs.600.0
-------------------------------
Customer: ABC Stores
Units Consumed: 300
Bill Amount: Rs.2400.0
[Link] Layout Managers with examples. (R)
In Java GUI programming (AWT/Swing), Layout Managers are used to arrange components
(buttons, labels, text fields, etc.) inside a container (like Frame, Panel, or JFrame).
Layout Managers in Java
1. FlowLayout
Default for Panel.
Places components in a row, left to right.
When no more space is left, moves components to the next line.
Alignment can be LEFT, RIGHT, CENTER (default).
Example:
import [Link].*;
import [Link].*;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame f = new JFrame("FlowLayout Example");
[Link](new FlowLayout());
[Link](new JButton("One"));
[Link](new JButton("Two"));
[Link](new JButton("Three"));
[Link](300, 100);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
2. BorderLayout
Default for Frame.
Divides the container into five regions:
NORTH, SOUTH, EAST, WEST, CENTER.
You must specify region when adding components.
Example:
import [Link].*;
import [Link].*;
public class BorderLayoutExample {
public static void main(String[] args) {
JFrame f = new JFrame("BorderLayout Example");
[Link](new BorderLayout());
[Link](new JButton("North"), [Link]);
[Link](new JButton("South"), [Link]);
[Link](new JButton("East"), [Link]);
[Link](new JButton("West"), [Link]);
[Link](new JButton("Center"), [Link]);
[Link](300, 200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
3. GridLayout
Arranges components in a grid (rows × columns).
All cells are of equal size.
Example:
import [Link].*;
import [Link].*;
public class GridLayoutExample {
public static void main(String[] args) {
JFrame f = new JFrame("GridLayout Example");
[Link](new GridLayout(2, 3)); // 2 rows, 3 columns
for (int i = 1; i <= 6; i++) {
[Link](new JButton("Button " + i));
}
[Link](300, 150);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
4. CardLayout
Treats each component as a card, only one card visible at a time.
Useful for wizards, tabbed forms, etc.
Example:
import [Link].*;
import [Link].*;
public class CardLayoutExample {
public static void main(String[] args) {
JFrame f = new JFrame("CardLayout Example");
CardLayout card = new CardLayout();
JPanel panel = new JPanel(card);
[Link](new JButton("Card 1"), "First");
[Link](new JButton("Card 2"), "Second");
[Link](panel);
[Link](panel, "First"); // Show first card
[Link](200, 150);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
5. GridBagLayout
Most flexible and complex.
Lets you place components in a grid with varying sizes and positions.
Uses GridBagConstraints for positioning.
Summary (for exams, 10 marks)
FlowLayout → Places components in a row, wraps to next line.
BorderLayout → Divides into 5 regions (N, S, E, W, Center).
GridLayout → Equal-sized grid (rows × columns).
CardLayout → Stack of cards, one visible at a time.
GridBagLayout → Flexible, allows custom positions & sizes.
23. Design an interface with any two standards text tools, menus and frames.
Two standard text tools (like TextField and TextArea)
Menus (using MenuBar, Menu, MenuItem)
Frame (main application window)
Here’s a simple Swing program that meets the requirements:
import [Link].*;
import [Link].*;
import [Link].*;
public class TextEditorInterface {
public static void main(String[] args) {
// Create Frame
JFrame frame = new JFrame("Simple Text Editor Interface");
[Link](400, 300);
[Link](JFrame.EXIT_ON_CLOSE);
// Text tools (TextField and TextArea)
JTextField textField = new JTextField("Enter title here...");
JTextArea textArea = new JTextArea("Write your text here...");
// Add them to frame
[Link](new BorderLayout());
[Link](textField, [Link]);
[Link](new JScrollPane(textArea), [Link]);
// MenuBar
JMenuBar menuBar = new JMenuBar();
// File Menu
JMenu fileMenu = new JMenu("File");
JMenuItem newItem = new JMenuItem("New");
JMenuItem exitItem = new JMenuItem("Exit");
// Add actions
[Link](e -> [Link](0));
[Link](newItem);
[Link](exitItem);
// Edit Menu
JMenu editMenu = new JMenu("Edit");
JMenuItem cutItem = new JMenuItem("Cut");
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem pasteItem = new JMenuItem("Paste");
// Add items to Edit Menu
[Link](cutItem);
[Link](copyItem);
[Link](pasteItem);
// Add Menus to MenuBar
[Link](fileMenu);
[Link](editMenu);
// Set MenuBar in Frame
[Link](menuBar);
// Show frame
[Link](true);
}
}
Explanation
Frame → JFrame frame = new JFrame(...) creates the main window.
Two text tools → JTextField (single-line input) and JTextArea (multi-line editor).
Menus → Created using JMenuBar, JMenu, and JMenuItem.
File menu has New and Exit.
Edit menu has Cut, Copy, Paste.
Sample Output (Interface Look)
Title bar: Simple Text Editor Interface
Top: a TextField
Center: a TextArea with scrollbar
Menu bar: File | Edit menus with standard items
24. Write short notes on Network basics and Socket Programming. (R)
Network Basics
Computer Network → A collection of interconnected devices (computers, servers, routers, etc.) that
communicate to share resources and information.
Types of Networks:
LAN (Local Area Network) – covers a small area like a building.
MAN (Metropolitan Area Network) – covers a city.
WAN (Wide Area Network) – covers large geographical areas, e.g., the Internet.
Key Concepts:
IP Address – Unique identifier of a device on a network.
Protocols – Set of rules for communication (e.g., TCP, UDP, HTTP, FTP).
Client–Server Model – Clients request services; servers provide them.
Ports – Logical endpoints for communication (e.g., port 80 for HTTP).
Socket Programming
Socket → An endpoint for communication between two machines over a network.
Socket Programming → Writing programs that use sockets to send/receive data over a network.
Works mainly with TCP (connection-oriented) or UDP (connectionless).
In Java:
Server Side
ServerSocket class is used to create a server socket.
accept() method waits for client requests.
Client Side
Socket class is used to connect to a server.
Communication → Data is exchanged using InputStream and OutputStream.
Example Flow:
Server creates a ServerSocket and waits.
Client creates a Socket and connects to server.
Data is exchanged.
Both sockets are closed.
✅ In short:
Network basics: cover IPs, protocols, ports, and client-server communication.
Socket programming: enables two-way communication between client and server using sockets in
Java.
MAY-2023
PART-C
[Link] the basic concepts of oops.
Basic concepts of OOP (Object-Oriented Programming) in Java.
OOP is a programming paradigm that organizes software design around objects instead of functions.
Here are the main concepts:
Class
A class is a blueprint or template for creating objects.
It defines data members (variables) and methods (functions).
Example:
class Car {
String color;
int speed;
void drive() {
[Link]("Car is driving");
}
}
Object
An object is an instance of a class.
It has state (values of variables) and behavior (methods).
Example:
public class Main {
public static void main(String[] args) {
Car c1 = new Car(); // object created
[Link] = "Red";
[Link] = 100;
[Link]();
}
}
Encapsulation
Wrapping data (variables) and methods into a single unit (class).
Access is controlled using access modifiers (private, public, protected).
Example:
class Bank {
private int balance = 1000; // private variable
public int getBalance() { // getter
return balance;
}
public void deposit(int amount) { // method controls access
balance += amount;
}
}
Inheritance
Mechanism by which one class inherits properties and behaviors of another.
Helps in code reusability.
Keyword: extends.
Example:
class Animal {
void eat() {
[Link]("Eating...");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking...");
}
}
Polymorphism
One thing, many forms → methods behave differently based on context.
Two types:
Compile-time (Method Overloading) – same method name, different parameters.
Runtime (Method Overriding) – child class provides a new implementation of parent method.
Example:
// Overloading
class MathOperation {
int add(int a, int b) { return a+b; }
double add(double a, double b) { return a+b; }
}
// Overriding
class Animal {
void sound() { [Link]("Some sound"); }
}
class Dog extends Animal {
void sound() { [Link]("Bark"); } // overriding
}
Abstraction
Hiding implementation details and showing only the essential features.
Achieved using abstract classes and interfaces.
Example:
abstract class Shape {
abstract void draw(); // abstract method
}
class Circle extends Shape {
void draw() {
[Link]("Drawing Circle");
}
}
Summary :
The basic concepts of OOP in Java are:
Class – blueprint for objects.
Object – instance of a class.
Encapsulation – data hiding and security.
Inheritance – reusability of code.
Polymorphism – many forms (overloading/overriding).
Abstraction – hiding details, showing only functionality.
[Link] the various types of inheritance in java.( R)
Inheritance in Java – Simple Explanation
Meaning:
Inheritance is a process in Java where one class (child) can use the properties and methods of another
class (parent).
It helps in:
Reusability of code
Avoiding duplication
Better organization of programs
Keyword: extends (for classes), implements (for interfaces).
Types of Inheritance in Java
Single Inheritance
One child class inherits from one parent class.
Easy and most common.
Example:
Dog inherits from Animal.
class Animal {
void eat() { [Link]("Eating..."); }
}
class Dog extends Animal {
void bark() { [Link]("Barking..."); }
}
Multilevel Inheritance
One class inherits another class, and then another class inherits from it.
Forms a chain (Grandparent → Parent → Child).
Example:
Puppy inherits Dog, and Dog inherits Animal.
class Animal { void eat() {} }
class Dog extends Animal { void bark() {} }
class Puppy extends Dog { void weep() {} }
Hierarchical Inheritance
Many child classes inherit from the same parent.
Example: Dog and Cat both inherit from Animal.
class Animal { void eat() {} }
class Dog extends Animal { void bark() {} }
class Cat extends Animal { void meow() {} }
Multiple Inheritance
A class inherits from more than one parent.
❌ Not possible in Java using classes (to avoid confusion → “Diamond problem”).
✅ Possible using interfaces.
interface A { void show(); }
interface B { void display(); }
class C implements A, B {
public void show() { [Link]("Show"); }
public void display() { [Link]("Display"); }
}
Hybrid Inheritance
A combination of two or more types of inheritance.
❌ Not possible with classes.
✅ Possible using interfaces in Java.
Extra Important Points
Code Reusability → Child class uses parent class methods without rewriting.
Method Overriding → Child can give new form to parent’s method.
Extends keyword → Used for inheritance between classes.
Implements keyword → Used when a class inherits from interfaces.
Object class → All classes in Java automatically inherit from the Object class (root class).
Helps in Polymorphism → Inheritance allows runtime polymorphism (method overriding).
Not all inheritance types supported with classes → Only single, multilevel, and hierarchical are
allowed.
Summary :
Inheritance in Java is a way to make a new class by using the features of an existing class.
The types are:
Single – one parent, one child.
Multilevel – grandparent → parent → child.
Hierarchical – one parent, many children.
Multiple – many parents, one child (possible only with interfaces).
Hybrid – mix of different inheritance (possible using interfaces).
[Link] the life cycle of a thread.
The life cycle of a thread in Java consists of several distinct states, representing its progress from
creation to termination. These states are:
New:
A thread enters the New state when an instance of Thread is created but the start() method has not yet
been invoked. In this state, the thread object exists, but it is not yet eligible to be run by the Java
Virtual Machine (JVM).
Runnable:
When the start() method is called on a new thread, it transitions to the Runnable state. In this state, the
thread is ready to execute and is awaiting allocation of CPU time by the thread scheduler. It might be
actively running or waiting in the run queue.
Blocked:
A thread enters the Blocked state when it is temporarily unable to execute because it is waiting for a
resource or a lock that is currently held by another thread. Common scenarios include waiting for a
monitor lock in a synchronized block/method or waiting for I/O operations to complete.
Waiting:
A thread enters the Waiting state when it is waiting indefinitely for another thread to perform a
specific action, such as calling notify() or notifyAll() on an object. Methods
like [Link]() without a timeout or [Link]() without a timeout can lead to this state.
Timed Waiting:
Similar to the Waiting state, but with a specified timeout. A thread enters the Timed Waiting state
when it is waiting for another thread to perform an action for a specific duration. Methods
like [Link](long millis), [Link](long millis), or [Link](long millis) can cause a
thread to enter this state. The thread will automatically transition out of this state after the timeout
expires, or if notified by another thread before the timeout.
Terminated (Dead):
A thread enters the Terminated state when its run() method completes execution, either normally or
due to an uncaught exception. Once a thread is in the Terminated state, it cannot be restarted.
[Link] the life cycle of an applet. (R)
The life cycle of a Java applet involves a series of methods that are automatically invoked by the Java
Virtual Machine (JVM) or the browser environment as the applet transitions through different
states. These states and their corresponding methods are:
Initialization State (Born State):
init(): This method is called once when the applet is first loaded. It is used for one-time
initialization tasks such as setting up the user interface, loading resources, or initializing variables.
Running State:
start(): This method is called after init() and whenever the applet becomes active or visible, for
example, when the user navigates back to the page containing the applet. It is used to start threads
or begin applet execution.
paint(Graphics g): This method is called whenever the applet needs to be redrawn, such as when it's
first displayed, resized, or when repaint() is called. It is responsible for drawing the applet's visual
content.
Idle or Stopped State:
stop(): This method is called when the applet becomes inactive or invisible, for example, when the
user navigates away from the page containing the applet or minimizes the browser window. It is
used to pause threads or suspend operations that are not needed when the applet is not visible.
Dead State:
destroy(): This method is called once when the applet is about to be removed from memory,
typically when the browser or applet viewer is closed. It is used to release any resources held by the
applet, such as closing file handles or stopping background processes.
Sequence of Execution:
When an applet is loaded, init() is called.
After init(), start() is called, followed by paint().
If the applet becomes inactive, stop() is called.
If the user returns to the applet, start() is called again, followed by paint().
When the applet is finally unloaded, stop() is called (if it's in the running state), and then destroy() is
called.
[Link] the various layout managers in java. (R )
Java's AWT and Swing libraries provide various layout managers to control the arrangement and
positioning of components within a container (like a JFrame or JPanel). These managers automatically
handle component sizing and placement, adapting to different screen sizes and resolutions.
Here are some of the common layout managers:
FlowLayout:
This is the simplest layout manager. It arranges components in a left-to-right, top-to-bottom flow,
similar to how text flows in a paragraph. Components are placed in the order they are added,
wrapping to the next line if the current line is full. It is the default layout for JPanel and Applet.
BorderLayout:
This layout manager divides the container into five regions: NORTH, SOUTH, EAST, WEST,
and CENTER. Each region can hold only one component. The CENTER component takes up the
remaining space after the other regions are allocated. It is the default layout
for JFrame and JDialog.
GridLayout:
This manager arranges components in a rectangular grid of rows and columns. All cells in the grid
have the same size, and components are placed in the grid from left to right, then top to bottom,
filling each cell sequentially.
CardLayout:
This layout manager treats each component as a "card" in a deck. Only one component is visible at
a time, and methods are provided to switch between the "cards." This is useful for creating
interfaces with multiple views or panels that can be toggled.
GridBagLayout:
This is the most flexible and complex layout manager. It arranges components in a grid, but
unlike GridLayout, cells can have different sizes, and components can span multiple rows and
columns. It offers fine-grained control over component placement using GridBagConstraints.
BoxLayout:
This manager arranges components in a single row or column. It can be set to arrange components
either horizontally (BoxLayout.X_AXIS) or vertically (BoxLayout.Y_AXIS).
GroupLayout:
This layout manager allows for flexible and complex layouts, often used with GUI builder tools like
NetBeans IDE. It defines relationships between components based on their baselines, edges, and
sizes.
SpringLayout:
This is a highly flexible but also complex layout manager that uses "springs" to define relationships
between component edges. It requires explicit definition of constraints for each component
MAY 2024
PART-C
20. Explain about various operators in Java.
In Java, operators are special symbols that perform operations on variables and values. They
are grouped into different categories based on their functionality. Here’s an overview of the various
operators in Java:
1. Arithmetic Operators
Used to perform basic mathematical operations.
• + → Addition
• - → Subtraction
• * → Multiplication
• / → Division (quotient)
• % → Modulus (remainder)
👉 Example:
int a = 10, b = 3;
[Link](a + b); // 13
[Link](a % b); // 1
2. Relational Operators
Used to compare two values, returning a boolean (true or false).
• == → Equal to
• != → Not equal to
• > → Greater than
• < → Less than
• >= → Greater than or equal to
• <= → Less than or equal to
👉 Example:
int a = 5, b = 7;
[Link](a < b); // true
3. Logical Operators
Used for logical (boolean) operations.
• && → Logical AND
• || → Logical OR
• ! → Logical NOT
👉 Example:
boolean x = true, y = false;
[Link](x && y); // false
[Link](!x); // false
4. Bitwise Operators
Operate on individual bits of integer types.
• & → Bitwise AND
• | → Bitwise OR
• ^ → Bitwise XOR
• ~ → Bitwise Complement
• << → Left shift
• >> → Right shift (signed)
• >>> → Unsigned right shift
👉 Example:
int a = 5, b = 3; // 5 = 0101, 3 = 0011
[Link](a & b); // 1 (0001)
5. Assignment Operators
Used to assign values to variables.
• = → Simple assignment
• += → Add and assign
• -= → Subtract and assign
• *= → Multiply and assign
• /= → Divide and assign
• %= → Modulus and assign
👉 Example:
int a = 10;
a += 5; // a = a + 5 → 15
6. Unary Operators
Work on a single operand.
• + → Positive (no effect)
• - → Negation
• ++ → Increment (pre/post)
• -- → Decrement (pre/post)
• ! → Logical NOT
👉 Example:
int a = 5;
[Link](++a); // 6 (pre-increment)
[Link](a--); // 6 (post-decrement, then a=5)
7. Ternary Operator (?:)
A shorthand for if-else.
👉 Example:
int a = 10, b = 20;
int max = (a > b) ? a : b;
[Link](max); // 20
8. Instanceof Operator
Checks whether an object is an instance of a specific class.
👉 Example:
String s = "Hello";
[Link](s instanceof String); // true
9. Type Cast Operators
Used to convert one data type into another.
• Implicit (widening) → automatic conversion
• Explicit (narrowing) → manual conversion
👉 Example:
double d = 10.5;
int i = (int) d; // narrowing
[Link](i); // 10
✅ Summary:
Java operators include Arithmetic, Relational, Logical, Bitwise, Assignment, Unary, Ternary,
instanceof, and Type Cast operators, each serving specific purposes in programming.
21. Write about wrapper classes for primitive data types with suitable examples (R)
Wrapper Classes in Java
In Java, the primitive data types (like int, char, double, etc.) are not objects. But sometimes, we
need objects instead of primitives (for example, when working with collections like ArrayList).
To solve this, Java provides wrapper classes that “wrap” (encapsulate) a primitive value inside an
object.
Primitive Data Types and Their Wrapper Classes
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Key Features of Wrapper Classes
1. Conversion between primitives and objects
o Primitive → Wrapper object (Boxing)
o Wrapper object → Primitive (Unboxing)
2. Autoboxing and Unboxing (automatic conversion introduced in JDK 1.5)
o Autoboxing: primitive is automatically converted to wrapper.
o Unboxing: wrapper is automatically converted to primitive.
3. Provide utility methods (like parsing, valueOf, compare, etc.).
Examples
1. Manual Boxing and Unboxing
public class WrapperExample {
public static void main(String[] args) {
int a = 10;
// Boxing (primitive to object)
Integer obj = [Link](a);
// Unboxing (object to primitive)
int b = [Link]();
[Link]("Boxed object: " + obj);
[Link]("Unboxed value: " + b);
}
}
2. Autoboxing and Unboxing
public class AutoBoxingExample {
public static void main(String[] args) {
// Autoboxing
int num = 25;
Integer obj = num; // automatically converted
// Unboxing
int value = obj; // automatically converted back
[Link]("Autoboxed object: " + obj);
[Link]("Unboxed value: " + value);
}
}
3. Using Wrapper Utility Methods
public class WrapperMethods {
public static void main(String[] args) {
// Converting String to primitive
int num = [Link]("100");
double d = [Link]("23.45");
// Getting max value of Integer
[Link]("Max Integer value: " + Integer.MAX_VALUE);
[Link]("Parsed int: " + num);
[Link]("Parsed double: " + d);
}
}
✅ Summary
• Wrapper classes provide an object representation of primitive types.
• They are essential when working with collections, generics, and utility methods.
• Support autoboxing and unboxing, making code simpler and cleaner.
22. Develop an interface with Jcheckbox, JTextarea and JButtons (R)
JCheckBox is a part of Java Swing package . JCheckBox can be selected or deselected . It displays
it state to the user . JCheckBox is an implementation to checkbox . JCheckBox inherits
JToggleButton class. Constructor of the class are :
8. JCheckBox() : creates a new checkbox with no text or icon
9. JCheckBox(Icon i) : creates a new checkbox with the icon specified
10. JCheckBox(Icon icon, boolean s) : creates a new checkbox with the icon specified and the
boolean value specifies whether it is selected or not.
11. JCheckBox(String t) :creates a new checkbox with the string specified
12. JCheckBox(String text, boolean selected) :creates a new checkbox with the string specified
and the boolean value specifies whether it is selected or not.
13. JCheckBox(String text, Icon icon) :creates a new checkbox with the string and the icon
specified.
14. JCheckBox(String text, Icon icon, boolean selected): creates a new checkbox with the string
and the icon specified and the boolean value specifies whether it is selected or not.
Methods to add Item Listener to checkbox.
6. addActionListener(ItemListener l): adds item listener to the component
7. itemStateChanged(ItemEvent e) : abstract function invoked when the state of the item to
which listener is applied changes
8. getItem() : Returns the component-specific object associated with the item whose state changed
9. getStateChange() : Returns the new state of the item. The ItemEvent class defines two states:
SELECTED and DESELECTED.
10. getSource() : Returns the component that fired the item event.
Commonly used methods:
13. setIcon(Icon i) : sets the icon of the checkbox to the given icon
14. setText(String s) :sets the text of the checkbox to the given text
15. setSelected(boolean b) : sets the checkbox to selected if boolean value passed is true or vice
versa
16. getIcon() : returns the image of the checkbox
17. getText() : returns the text of the checkbox
18. updateUI() : resets the UI property with a value from the current look and feel.
19. getUI() : returns the look and feel object that renders this component.
20. paramString() : returns a string representation of this JCheckBox.
21. getUIClassID() : returns the name of the Look and feel class that renders this component.
22. getAccessibleContext() : gets the AccessibleContext associated with this JCheckBox.
23. isBorderPaintedFlat() : gets the value of the borderPaintedFlat property.
24. setBorderPaintedFlat(boolean b) : sets the borderPaintedFlat property.
Example:
import [Link].*;
import [Link].*;
import [Link].*;
public class CheckBoxTextAreaDemo extends JFrame implements ActionListener {
JCheckBox checkBox;
JTextArea textArea;
JButton button;
public CheckBoxTextAreaDemo() {
Frame title
setTitle("Interface Example");
setSize(400, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Components
checkBox = new JCheckBox("I agree");
textArea = new JTextArea(5, 25);
button = new JButton("Submit");
// Add action listener
[Link](this);
// Add components to frame
add(checkBox);
add(new JScrollPane(textArea));
add(button);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if ([Link]()) {
[Link](this,
"Submitted: " + [Link]());
} else {
[Link](this,
"Please check the box before submitting!");
}
}
public static void main(String[] args) {
new CheckBoxTextAreaDemo();
}
}
🔎 How it works:
• JCheckBox → lets user confirm (e.g., "I agree").
• JTextArea → allows user to type text (multi-line).
• JButton → on click, checks if the box is selected; if yes, it displays the text in a dialog,
otherwise shows a warning.
23. Write a short note on (a) Socket Programming (b) Working with Fonts.
(a) Socket Programming (R)
(a) Socket Programming
9. Definition: Socket programming allows two-way communication between two systems
(client and server) over a network.
10. Socket: An endpoint of communication, represented by an IP address + port number.
11. Types of Communication:
o TCP (Transmission Control Protocol) → connection-oriented, reliable (uses Socket
& ServerSocket).
o UDP (User Datagram Protocol) → connectionless, faster but less reliable (uses
DatagramSocket).
12. Important Classes ([Link]):
o Socket → client-side connection.
o ServerSocket → server-side listener.
o DatagramSocket, DatagramPacket → for UDP communication.
13. Basic Steps (TCP):
o Server creates ServerSocket and waits for connection.
o Client creates Socket and requests connection.
o Input/Output streams are used to send and receive data.
o Connection closes after communication ends.
14. Streams Used:
o InputStream / BufferedReader → to read data.
o OutputStream / PrintWriter → to send data.
15. Advantages:
o Enables distributed applications.
o Provides reliable communication (with TCP).
o Allows both local and internet-based communication.
16. Applications:
o Chat systems, multiplayer games.
o File sharing apps.
o Remote login, messaging services.
o Web servers & client applications.
(b) Working with Fonts (R)
Definition: In Java GUI (AWT/Swing), fonts control the appearance of text in components.
Font Class ([Link]): Used to define font style, size, and name.
Constructor:
Font f = new Font("Serif", [Link], 18);
Parameters:
o Font Name → "Serif", "SansSerif", "Monospaced".
o Style → [Link], [Link], [Link].
o Size → font size in points (e.g., 12, 18).
Methods:
o getName() → returns font name.
o getStyle() → returns style.
o getSize() → returns size.
Usage in Graphics:
public void paint(Graphics g) {
Font f = new Font("SansSerif", [Link], 20);
[Link](f);
[Link]("Hello, World!", 50, 100);
}
Usage in Components: Fonts can be set in GUI components like JLabel, JTextArea, JButton
using setFont().
Advantages:
o Improves readability of applications.
o Allows customization of look and feel.
o Enhances user interface design.
Default Fonts: Java provides logical fonts (Serif, SansSerif, Monospaced, Dialog, DialogInput)
that map to system fonts.
[Link] the various layout managers in java. (R )
Java's AWT and Swing libraries provide various layout managers to control the arrangement and
positioning of components within a container (like a JFrame or JPanel). These managers automatically
handle component sizing and placement, adapting to different screen sizes and resolutions.
Here are some of the common layout managers:
FlowLayout:
This is the simplest layout manager. It arranges components in a left-to-right, top-to-bottom flow,
similar to how text flows in a paragraph. Components are placed in the order they are added,
wrapping to the next line if the current line is full. It is the default layout for JPanel and Applet.
BorderLayout:
This layout manager divides the container into five regions: NORTH, SOUTH, EAST, WEST,
and CENTER. Each region can hold only one component. The CENTER component takes up the
remaining space after the other regions are allocated. It is the default layout
for JFrame and JDialog.
GridLayout:
This manager arranges components in a rectangular grid of rows and columns. All cells in the grid
have the same size, and components are placed in the grid from left to right, then top to bottom,
filling each cell sequentially.
CardLayout:
This layout manager treats each component as a "card" in a deck. Only one component is visible at
a time, and methods are provided to switch between the "cards." This is useful for creating
interfaces with multiple views or panels that can be toggled.
GridBagLayout:
This is the most flexible and complex layout manager. It arranges components in a grid, but
unlike GridLayout, cells can have different sizes, and components can span multiple rows and
columns. It offers fine-grained control over component placement using GridBagConstraints.
BoxLayout:
This manager arranges components in a single row or column. It can be set to arrange components
either horizontally (BoxLayout.X_AXIS) or vertically (BoxLayout.Y_AXIS).
GroupLayout:
This layout manager allows for flexible and complex layouts, often used with GUI builder tools like
NetBeans IDE. It defines relationships between components based on their baselines, edges, and
sizes.
SpringLayout:
This is a highly flexible but also complex layout manager that uses "springs" to define relationships
between component edges. It requires explicit definition of constraints for each component