[go: up one dir, main page]

0% found this document useful (0 votes)
101 views57 pages

Java Impotant Que

The document contains a series of questions and answers related to Java programming concepts, including keywords, exception handling, GUI components, and object-oriented programming principles. Key topics covered include the final keyword, access specifiers, layout managers, listeners, and the use of various classes and methods in Java. It also discusses the differences between checked and unchecked exceptions, method overloading and overriding, and the purpose of wrapper classes.

Uploaded by

bhosalesakshi772
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views57 pages

Java Impotant Que

The document contains a series of questions and answers related to Java programming concepts, including keywords, exception handling, GUI components, and object-oriented programming principles. Key topics covered include the final keyword, access specifiers, layout managers, listeners, and the use of various classes and methods in Java. It also discusses the differences between checked and unchecked exceptions, method overloading and overriding, and the purpose of wrapper classes.

Uploaded by

bhosalesakshi772
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

1-marks question

1.A final keyword can not be overriden state true/false and justify.
->True.
The purpose of using final in a method declaration is to preserve the
implementation of that method, preventing any subclass from changing its
behavior.
2. Give the types of access specifiers.
->1.public.
2.private.
3.protected
3. Differentiate between Scanner and Buffered Reader class.
->Scanner:-
-Can read input from various sources (keyboard, file, etc.)
-Provides methods like next(), nextInt(), nextLine()
Buffered reader:
-Primarily used for reading text from files or streams
-Provides readLine() method to read entire lines
4. What is Layout Manager?
->-Layout maneger is an interface used to define the arrangement and
positioning of components within a container.
-It is responsible for controlling the layout of GUI elements in a container (like a
Frame, Panel, etc.)
5.Write the purpose of this keyword.
->The this keyword in Java refers to the current instance of the class.
It is used To refer to the current object's instance variables and methods.
6. List any two types of checked Exception.
-> 1.IOException 2. SQLException
7. What is listener ?
-> A listener is an object that is notified of specific events in a GUI (Graphical
User Interface) and responds accordingly.
- Listeners are used in event-driven programming to handle user interactions,
like button clicks, mouse movements, or key presses.
8.State any two Listeners.
-> 1. ActionListener: It listens for action events, such as a button press or menu
selection.
2.MouseListener: It listens for mouse events such as clicking, entering, exiting,
or pressing the mouse buttons.
9. What are command line arguments?
-> -Command-line arguments are arguments passed to a Java program when it
is executed from the command line (terminal).
- These arguments are stored in the String[] args array of the main method. ----
They allow users to pass input to the program when starting it.
10. Differentiate between throw and throws keyword.
->1. Throw:
- Used to explicitly throw an exception in the program
- Follows an exception object (e.g., throw new Exception();)
Ex- public void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older");
}
}
2.Throws:
- Used to declare that a method can throw certain exceptions
- Follows a list of exceptions (e.g., throws IOException, SQLException;)
Ex- public void readFile() throws IOException {
// Code that might throw IOException
}
10. Write the purpose of job.
->A job may involve performing an operation or running a program to achieve a
specific goal, like processing data, generating reports, or performing
maintenance tasks.
11. What is javadoc?
->-Javadoc is a documentation generator tool .
-It is used in Java to create API documentation in HTML format.
13. Define Constructor.
->-Constructors have the same name as the class and do not have a return
type.
-There are two types of constructors in Java:
1.default constructors
2.parameterized constructors.
14. List any two wrapper classes.
-> Integer (wraps the primitive type int)
Double (wraps the primitive type double)
15. Write the use of extends key word.
->- The extends keyword is used in Java to create a subclass or child class that
inherits properties and methods from a superclass or parent class.
16. Define functional interface.
-> A functional interface in Java is an interface that contains only one abstract
method, but it can have multiple default or static methods.
17. List any two uncheck exception.
-> 1. NullPointerException
2.ArrayIndexOutOfBoundsException
18. How to open file in read mode?
-> -To open a file in read mode in Java, you can use classes like FileReader,
BufferedReader, or FileInputStream
Example:
FileReader file = new FileReader("filename.txt");
19. What is AWT?
->- AWT (Abstract Window Toolkit) is a set of APIs in Java used to create
graphical user interfaces (GUIs).
- It provides components such as buttons, text fields, and menus, and allows
for event-driven programming in desktop applications.
20. Give the names of any two Adaptor class.
->1. MouseAdapter
2.KeyAdapter
21. What is use of Javac?
->javac is the Java compiler used to compile Java source code files (.java) into
bytecode (.class) files.
23. What is use of 'implements' keyword?
->The implements keyword is used in Java to define that a class implements an
interface.
Example:
class MyClass implements MyInterface {
// Implement the methods defined in MyInterface
}
25. What is use of Array?
->-An array is used to store multiple values of the same type in a single
variable.
-It allows efficient storage and retrieval of data by index.
Example: int[] numbers = {1, 2, 3, 4, 5};
26. Give the name of any two listeners.
->1.ActionListener – Used to handle action events (e.g., button clicks).
2.MouseListener – Used to handle mouse events (e.g., mouse clicks, mouse
movement).
27. What is exception?
->-An exception is an event that disrupts the normal flow of a program's
execution.
-Exceptions are usually errors that occur during the execution of a program
-exceptions using try, catch, and finally.
28. Give the syntax of ends with( ) method?
->syntax: boolean endsWith(String suffix).
Ex: String str = "hello";
boolean result = str.endsWith("lo"); // Returns true
29. What is package?
->-A package in Java is a namespace that organizes classes and interfaces in a
hierarchical manner.
-Examples of built-in packages are java.util, java.io, and java.lang
30. What is use of new operator?
->-The new operator in Java is used to create new objects.
-It allocates memory for an object and returns a reference to that object.
Example: MyClass obj = new MyClass();
32. Define Interface.
->-An interface in Java is a reference type that can contain abstract methods,
default methods, static methods, and constants.
Example: interface MyInterface {
void doSomething();
}
35. What is use of static keyword?
->-The static keyword in Java is used to declare members (fields, methods,
blocks, etc.)
-that belong to the class itself, rather than to instances of the class.
Example: class MyClass {
static int count = 0; // Shared across all instances
}
40. List any two listener.
->1. ActionListener
2.KeyListener.
41. What is JAR file?
->A JAR (Java Archive) file is a package file format that combines multiple Java
class files, associated metadata, and resources (like images or configuration
files) into a single file.
- It is used for distributing Java applications or libraries.
-JAR files are based on the ZIP file format
42. What is meant by Garbage collection?
->-Garbage collection in Java is the process of automatically reclaiming memory
by destroying objects that are no longer in use or reachable.
43. What is use of final keyword?
->-The final keyword in Java can be applied to variables, methods, and classes
44. “Import statement is not essential in Java”. True/False? Justify.
->
46. Define Unchecked exception.
->-An unchecked exception in Java is an exception that extends
RuntimeException.
-These exceptions do not need to be explicitly handled with a try-catch block or
declared using the throws keyword.
47. List any two methods of file class.
->1. exists()
Ex: File file = new File("example.txt");
boolean exists = file.exists();
2. delete()
Ex: File file = new File("example.txt");
boolean deleted = file.delete();
48. Which method is used for first time initialization in Applet?
->The init() method is used for first-time initialization in an Applet.
49. What is Anonymous classes?
->-Anonymous classes in Java are classes that are declared and instantiated at
the same time, without a named reference
-Anonymous classes are useful for event handling, callbacks, or when you need
a one-time implementation.
50. What is difference between repaint and update method.
->repaint():
- This method is used to request the repainting of a component.
-It schedules a call to the paint() method.
-is commonly used in modern Java programs to request a repaint of a
component.
update():
-This method is used in older versions of AWT to clear the area.
-then call the paint() method.
-update() is an older method and rarely used today.
51. What is Different types of Dialogs in in java?
->1. Message Dialog
2. Input Dialog.
3. Confirm Dialog
52. What is Scroll Pane?
->-A JScrollPane is a container in Java's Swing library that provides a scrollable
view of another component.
-It automatically adds scroll bars when the content is too large to fit within the
visible area.
- Common usage is for text areas, tables, and lists.
53. State any Four Methods of Windows Listener?
-> windowOpened(WindowEvent e)
windowClosing(WindowEvent e)
windowClosed(WindowEvent e)
windowIconified(WindowEvent e)
54. Write a syntax of JFileChooser class.
->JFileChooser fileChooser = new JFileChooser();
55. What is Checked and unchecked Exceptions?
->1.Checked Exceptions:
- These are exceptions that are checked at compile-time.
-Examples include IOException, SQLException.
2.Unchecked Exceptions:
-These are exceptions that are not checked at compile-time and occur at
runtime.
-They are typically subclasses of RuntimeException.
-Examples include NullPointerException, ArrayIndexOutOfBoundsException.
56. What is use of finally block?
->The finally block is used to execute important code (such as closing
resources) after a try-catch block, regardless of whether an exception was
thrown or not.
Example:
try {
// Code that may throw an exception
} catch (Exception e) {
// Handle exception
} finally {
// Code that will always execute, e.g., closing resources
}
57. Write pupose of static block
->-A static block is used to initialize static variables or perform initialization
tasks that should occur only once when the class is loaded into memory.
Syntax:
static {
// Static initialization code
}
58. import statement is not essential in java True/False?Justify.
->False.
The import statement is essential when you need to use classes from other
packages
60. State the use of toString method.
->-The toString method is used to provide a string representation of an object.
Ex: @Override
public String toString() {
return "Person[name=" + name + ", age=" + age + "]";
}
61. give the syntax of equlas() methods.
->public boolean equals(Object obj);
2 Marks Question
1. 'When constructor of class will be called?' Comment.
->-The constructor of a class in Java is called when an object of that class is
created.
-It is automatically invoked when you use the new keyword to instantiate an
object.
-The constructor initializes the newly created object.
2. What is command line argument? Where they are stored in a program.
->-Command-line arguments are values that are passed to a Java program
when it is run from the command line.
-They are stored in the String[] args parameter of the main method.
3. What is Frame? Give its any two methods.
->-A Frame in Java is a top-level window with a title.
- It is part of the java.awt package, used for building graphical user interfaces
(GUIs).
1. setTitle(String title): Sets the title of the frame.
2. setSize(int width, int height): Sets the size of the frame
**4. Differentiate between method overloading and method overriding.
5. Write any two access specifiers.
-> 1.public: The member is accessible from any other class.
2.private: The member is accessible only within the same class.
**7. Differentiate between class variables and instance variables.
8. Write the purpose of abstract keyword.
->-The abstract keyword is used to declare an abstract class or an abstract
method.
- To provide a base class with incomplete methods that must be completed in
derived classes.
- To achieve polymorphism in Java
Ex: abstract class Animal {
abstract void sound(); // Abstract method
void eat() {
System.out.println("Eating...");
}
}class Dog extends Animal {
void sound() {
System.out.println("Bark");
}
}
9. Which class and interface are at topmost position in Exception hierarchy.
->-Throwable is the topmost class in the exception hierarchy.
-It has two main subclass:
-Error and Exception classes.
10. Give the syntax of JFileChooser class
->JFileChooser fileChooser = new JFileChooser();
11. List any two methods of string buffer class.
->1.append(String str) – Appends the specified string to the end of the
StringBuffer object.
Ex: StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World
2. reverse() – Reverses the sequence of characters in the StringBuffer.
Ex: StringBuffer sb = new StringBuffer("Hello");
sb.reverse();
System.out.println(sb); // Output: olleH
12. What is use of 'throw' keyword.
->-The throw keyword is used to explicitly throw an exception in Java.
-It allows the programmer to manually trigger an exception in a method or
block of code.
13. Differentiate between final and finally keyword.
->Final :
-Final keyword is used with the classes, methods and variables.
-Final method is executed only when we call it.
-final is the keyword and access modifier
Ex: final int x = 10;
Finally:
-Finally block is always related to the try and catch block in exception handling.
-Finally block is executed as soon as the try-catch block is executed.
-finally is the block in Java Exception Handling to execute the important code
Ex: try {
// Code that may throw an exception
} catch (Exception e) {
// Exception handling
} finally {
// Code that will always execute
}
14. What is method overloading?
->-Method overloading in Java occurs when two or more methods in the same
class have the same name but differ in the number or type of their parameters.
-It allows a class to have multiple methods with the same name, making the
code more readable and concise.
15. What is anonymous inner class?
->-An anonymous inner class is a class defined and instantiated in a single
expression.
-It is not given a name, and it is used to provide the implementation of an
interface or abstract class without creating a separate class file.
16. Which Swing classes are used to create menu? `
->-JMenuBar – A menu bar that holds the menus.
-JMenu – Represents a single menu (File, Edit, etc.).
- JMenuItem – Represents an item in a menu (New, Save, etc.).
17. What is use of layout manager?
->-A layout manager in Java is used to arrange components in a container (like
a JFrame) in a specific, predictable way.
-Layout managers handle the size and position of components based on rules
and constraints.
18 Explain any one Layout Manager.
->FlowLayout:
-FlowLayout arranges components in a left-to-right flow, one after the other.
-If the container's width is exceeded, it moves the next component to the next
line.
-The layout can be aligned in three ways: left, center, and right.
-frame.setLayout(new FlowLayout(FlowLayout.CENTER));
19. What are the features of swing?
->1. Lightweight Components.
2. Event Handling
3. Support for Graphics
4. MVC Architecture
19. What is use final keyword
->-The final keyword is used in Java to declare constants, prevent method
overriding, and prevent inheritance.
20. Write difference between abstract class and interface
->
21. When we declare a method or class final?
->Final Method:
-A method is declared final when we want to prevent it from being overridden
by subclasses.
-If a method is marked as final, it cannot be redefined in any subclass.
- This is used to ensure that the behavior of the method remains consistent
across the class hierarchy.
Final Class:
-A class is declared final to prevent it from being subclassed.
-Once a class is marked as final, no other class can extend it.
-This is useful for creating immutable classes, or when you want to ensure that
the class’s behavior cannot be altered by inheritance.
Ex: final class MyClass {
// class definition
}
class SubClass extends MyClass { // This will cause a compile-time error
// class definition
}
22. State ths use of Wrapper classes ? Explain any two Wrapper classes.
->-Wrapper classes are used to convert primitive data types (like int, char, etc.)
into objects.
1. Integer: It wraps the primitive data type int. It provides methods to convert
an int to a string or perform mathematical operations.
Ex: Integer i = new Integer(5);
int x = i.intValue();
2.Character: It wraps the primitive char. It provides methods for converting
between characters and manipulating characters.
Ex: Character c = new Character('A');
char ch = c.charValue();
23. explain any four package names in java
->java.lang: Contains fundamental classes and functions essential for Java
programming (e.g., String, Math, Object, Thread).
java.util: Contains utility classes for data structures (e.g., ArrayList, HashMap,
Date), and classes for internationalization and collections framework.
java.io: Provides classes for system input and output through data streams,
serialization, and file handling (e.g., File, InputStream, BufferedReader).
java.net: Includes classes for networking functionality (e.g., URL, Socket,
HttpURLConnection), allowing you to create networked applications.
24. Explain the use of this keyword in java.
25. How println() differs from print method
->print(): This method prints the output without adding a new line at the end.
The next output will continue from where the previous output ended on the
same line.
Ex: System.out.print("Hello ");
System.out.print("World!");
// Output: Hello World! (on the same line)
println(): This method prints the output followed by a newline, so the next
output will appear on the next line.
Ex: System.out.println("Hello");
System.out.println("World!");
// Output:
// Hello
// World! (on two separate lines)
26. What do you mean by jdb?
->-jdb stands for Java Debugger.
-It is a command-line tool provided by the JDK for debugging Java programs. --It
allows developers to set breakpoints, step through the code, inspect variables,
and analyze the execution flow to help identify and fix bugs.
27. Java is Platform dependent language state true/false?justify
->False.
Java is platform-independent, not dependent on any specific platform
28.What is use of javap tool?
->-The javap tool is a disassembler for Java bytecode.
-It allows you to inspect the contents of compiled Java .class files.
-It can display information such as the methods, constructors, fields, and
bytecode instructions contained in the class files.
Ex: javap MyClass
3 Marks question
1.Explain the structure of java program
->*Class Declaration: -In Java, everything is part of a class.
- A program must contain at least one class to execute.
public class MyProgram {
public static void main(String[] args) {
// Code execution starts here
}
}
*Main Method: This is the entry point for any Java application.
-The main() method is the starting point where the program begins its
execution.
-The signature of the main method is always
public static void main(String[] args)
*Statements/Logic: Inside the main method, you write the logic or call
methods that define what the program will do.
* Imports (Optional): You can import Java libraries or packages to use their
functionality, like import java.util.Scanner; for using Scanner to read input.

2.Explain different types of Dialog Box with an example.


->1.Message Dialog: Shows a simple message to the user.
Ex: JOptionPane.showMessageDialog(null, "Hello, this is a message!");
2.Confirm Dialog: Asks the user to confirm an action.
Ex: int response = JOptionPane.showConfirmDialog(null, "Do you want to
continue?");
3. Input Dialog: Prompts the user to enter some input.
Ex: String name = JOptionPane.showInputDialog("Enter your name");
4. Option Dialog: Allows the user to select from a set of options.
Ex: Object[] options = {"Option 1", "Option 2", "Option 3"};
int choice = JOptionPane.showOptionDialog(null, "Choose an option", "Option
Dialog", JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);

3. Explain the execution process of java program.


->The execution process of a Java program involves several steps:
1. Writing the Code: You write Java code in a .java file using a text editor or
an IDE.
2. Compilation: The Java source code is compiled by the javac compiler into
bytecode, stored in .class files.
Example: javac MyProgram.java
3. Loading: The Java Virtual Machine (JVM) loads the bytecode (class files)
into memory.
4. Execution: The JVM executes the bytecode using the interpreter or JIT
(Just-In-Time) compiler. The main() method is executed first.
Example: java MyProgram
5. Output: The program generates output (e.g., prints on the console, GUI
updates, etc.).

4.Explain MVC architecture in details.


-> MVC Architecture in Detail
MVC (Model-View-Controller) is a design pattern used to separate concerns in
application development, typically in user interface (UI) programming.
1. Model: Represents the data or business logic of the application.
-It communicates with the database or data sources, stores and manipulates
data, and notifies the View when data changes.
Example: User, Product, or Database classes.
2. View: Represents the UI (User Interface) and is responsible for displaying
the data from the Model.
- It listens to the Model for updates.
Example: JPanel, JFrame (Swing components).
3. Controller: Acts as an intermediary between the Model and the View.
- It listens to user input (events) from the View, processes it (e.g., updates
Model), and updates the View accordingly.
Example: A class that handles button click events and updates the UI.
5.Explain uses of final keyword with example.
->-The final keyword is used to define constants, prevent method overriding,
and prevent inheritance.
1. Final Variables: Once a variable is assigned a value, it cannot be changed.
Ex: final int MAX_VALUE = 100;
2. Final Methods: A method marked as final cannot be overridden by
subclasses.
Ex: public final void display() {
System.out.println("This is a final method");
}
4. Final Classes: A class marked as final cannot be extended.
Ex: public final class MyClass {
// class code
}
6.Explain the features of Java
->Object-Oriented: Java is based on the concept of objects and classes.
Platform-Independent: Java code is compiled to bytecode which can run on any
platform with a JVM.
Robust: Strong memory management, exception handling, and garbage
collection.
Multithreading: Java supports multithreaded programming, allowing multiple
threads to run concurrently.
Distributed Computing: Java has built-in libraries for network communication
(e.g., RMI, Sockets).
Security: Java provides features like bytecode verification, secure class loaders,
and encryption.
7 . explain abstract class and abatract method
->.1. Abstract Class:
A class that cannot be instantiated on its own and may contain abstract
methods (methods without implementation).
Ex: abstract class Animal {
abstract void sound();
void eat() {
System.out.println("This animal eats food");
}
}
2. Abstract Method:
A method that does not have a body, and must be implemented by subclasses.
Ex: class Dog extends Animal {
void sound() {
System.out.println("Bark");
}
}
8. What is polymorphism ? explain its types.
->Polymorphism means "many forms" and refers to the ability of an object to
take on multiple forms.
-single action in different forms.
Types:
Compile-time Polymorphism (Method Overloading):
-Achieved by defining multiple methods with the same name but different
parameters
Ex: class MathOperations {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Runtime Polymorphism (Method Overriding):
Achieved by overriding a method in a subclass.
Ex: class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
9. Explain inner class with an example.
->-inner class refers to the class that is declared inside class
-An Inner Class is a class defined within another class.
Ex: class Outer {
class Inner {
void display() {
System.out.println("Inside the inner class");
}
}
}

public class Test {


public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}
10. What is Wrapper Class? How to create Wrapper class Objects
->Wrapper classes in Java are used to convert primitive data types into objects.
Every primitive type has a corresponding wrapper class:
 int -> Integer
 char -> Character
 boolean -> Boolean
 double -> Double
Create:int x = 10;
Integer obj = Integer.valueOf(x); // Autoboxing
System.out.println(obj); // Output: 10
Character ch = 'A'; // Autoboxing
11. Explain Methods in Object Class.
->1.toString():
-Returns a string representation of the object.
-By default, it returns the class name followed by the object's memory address.
-it is commonly overridden to provide a more meaningful string representation.
2. equals(Object obj):
-Used to compare two objects for equality.
-The default implementation checks reference equality (whether both
references point to the same memory location), but it is often overridden to
check the logical equality of objects.
3.hashCode():
- Provides a hash code value for the object, used in hash-based collections like
4.getClass():
- Returns the Class object associated with the class of the object
13 What is Scanner Class ? Explain its Mehod
-> The Scanner class is part of the java.util package
-is used to read input from various sources, such as user input from the
keyboard, files, or streams.
-It simplifies reading data in a program, especially primitive types like int,
double, and String.
Common methods of the Scanner class:
1. nextLine(): Reads a line of text (a string) from the input.
Ex: Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
2. nextInt(): Reads the next integer from the input.
Ex: int num = sc.nextInt();
3. nextDouble(): Reads the next double value from the input.
Ex: double d = sc.nextDouble();
4. nextBoolean(): Reads the next boolean value from the input.
Ex: boolean b = sc.nextBoolean();
5. hasNext(): Checks if there is another token in the input.
Ex: if (sc.hasNext()) {
// Do something
}
14. Which Methods are useful to convert from String to Other Primitive type
->1. parseInt(String s) in Integer (for converting String to int):
Ex: int i = Integer.parseInt("123");
2. parseDouble(String s) in Double (for converting String to double):
Ex: double d = Double.parseDouble("12.34");
3. parseBoolean(String s) in Boolean (for converting String to boolean):
Ex: boolean b = Boolean.parseBoolean("true");
4.parseFloat(String s) in Float (for converting String to float):
ex: float f = Float.parseFloat("12.34");
15. What is Array ? Explain its type
->-An array is a data structure in Java that allows you to store a fixed-size
collection of elements of the same type.
- The elements are stored in contiguous memory locations.
Types:
1. Single-Dimensional Array:
 An array with a single row or list of elements.
 Example:int[] arr = {1, 2, 3, 4, 5};
2. Multi-Dimensional Array:
 An array with more than one dimension. Commonly used as matrices
(2D arrays), or higher-dimensional structures.
 Example (2D Array):int[][] matrix = {{1, 2}, {3, 4}, {5, 6}};
16 . Difference Between Procedure Oriented Prgramming and Object
Oriented Programming
17. Difference between class and object
4Mark question.
1.What is inheritance? Explain multilevel inheritance with an example.
->Inheritance is a feature of object-oriented programming (OOP) that allows a
class to inherit properties and behaviors (fields and methods) from another
class.
Multilevel Inheritance :
-Multilevel Inheritance occurs when a class is derived from another derived
class.
- In other words, a class acts as a base class for a derived class, which in turn
becomes a base for another class.
Ex: class Animal {
void eat() {
System.out.println("Eating...");
}
}

class Dog extends Animal { // Dog inherits Animal


void bark() {
System.out.println("Barking...");
}
}

class Puppy extends Dog { // Puppy inherits Dog and Animal


void play() {
System.out.println("Playing...");
}
}
public class Main {
public static void main(String[] args) {
Puppy p = new Puppy();
p.eat(); // Inherited from Animal
p.bark(); // Inherited from Dog
p.play(); // Defined in Puppy
}
}
2. How to create and access package in a java? Explain with an example.
3. Differentiate between String and StringBuffer class.
5. What is polymorphism? How to implement it at compile time?
->- Polymorphism means the ability of an object to take many forms
-It allows methods to have the same name but behave differently based on the
objects' data types or the method arguments.
Compile-time polymorphism (also known as method overloading) occurs when
multiple methods have the same name but different parameter lists.

6.How to define and handle user defined exception?


-> You can define a user-defined exception by extending the Exception class. To
handle it, use try, catch, and optionally throw.
Ex: class AgeException extends Exception {
AgeException(String msg) {
super(msg);
}
}
public class Main {
public static void main(String[] args) {
try {
int age = 17;
if (age < 18) {
throw new AgeException("Age must be 18 or older.");
}
} catch (AgeException e) {
System.out.println(e.getMessage());
}
}
}

7.What is listener? How to inherit it in program?


->- A listener is an interface that receives and processes events.
- It's used in GUI programming (AWT/Swing) for handling user input like clicks,
mouse movements, etc.
Implement the relevant listener interface (like ActionListener, MouseListener,
etc.).
Define the methods of the interface (e.g., actionPerformed()).
8.Explain the uses of super keyword with example.
->- The super keyword refers to the parent class and can be used in the
following ways:
1. To call a parent class constructor.
2. To access parent class methods or fields that are overridden by the child
class.
Ex: class Animal {
void eat() {
System.out.println("Animal is eating");
}
}

class Dog extends Animal {


void eat() {
super.eat(); // Calls the parent class method
System.out.println("Dog is eating");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
}
}
9. What is string? Explain its any three method with an example.
->- A String is an object in Java that represents a sequence of characters.
Three methods:
1.length(): Returns the length of the string.
Ex: String str = "Hello World";
System.out.println(str.length());
2.charAt(int index): Returns the character at a specified index.
Ex: String str = "Hello World";
System.out.println(str.charAt(4)); // Output: 'o'
3.toUpperCase(): Converts all characters to uppercase.
Ex: String str = "Hello World";
System.out.println(str.toUpperCase()); // Output: "HELLO WORLD"
10. Differentiate between AWT & Swing
->

S.N
O AWT Swing

Swing is a part of Java Foundation


Java AWT is an API to develop
1. Classes and is used to create
GUI applications in Java
various applications.

The components of Java AWT The components of Java Swing are


2.
are heavy weighted. light weighted.

Java AWT has comparatively


Java Swing has more functionality
3. less functionality as compared
as compared to AWT.
to Swing.

The execution time of AWT is The execution time of Swing is less


4.
more than Swing. than AWT.

The components of Java AWT The components of Java Swing are


5.
are platform dependent. platform independent.

MVC pattern is not supported MVC pattern is supported by


6.
by AWT. Swing.

7. AWT provides comparatively Swing provides more powerful


S.N
O AWT Swing

less powerful components. components.

AWT components require Swing components requires


8
java.awt package javax.swing package

AWT is a thin layer of code on Swing is much larger swing also


9
top of the operating system. has very much richer functionality.

Swing is also called as JFC(java


AWT stands for Abstract
10 Foundation classes). It is part of
windows toolkit .
oracle’s JFC.

Using AWT , you have to


11 implement a lot of things Swing has them built in.
yourself .

11. Explain uses of super-keyword with suitable example.


->The super keyword is used in Java to refer to the immediate parent class
object. It can be used in the following scenarios:
1. Accessing Parent Class Constructor:
o super() is used to call the constructor of the parent class.
2. Accessing Parent Class Methods:
o You can use super to call methods of the parent class that are
overridden in the child class.
3. Accessing Parent Class Fields:
o You can access parent class instance variables (if they are not
shadowed by the child class).
Ex: class Animal {
void eat() {
System.out.println("Animal is eating");
}
}

class Dog extends Animal {


void eat() {
super.eat(); // Calling the parent class method
System.out.println("Dog is eating");
}
}

public class Test {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
}
}

13. Explain inner and Nested class with example.


->-An inner class is a class that is defined inside another class.
-Inner classes have access to the outer class’s members (variables, methods).
Ex: class Outer {
private int data = 10;

class Inner {
void display() {
System.out.println("Data: " + data); // Inner class can access Outer class
members
}
}
}

public class Test {


public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}
Nested Class:
 A nested class is a class that is statically nested inside another class. A
static nested class cannot access the instance variables of the outer class.
Ex: class Outer {
static int data = 10;

static class Nested {


void display() {
System.out.println("Data: " + data); // Nested class can access static
members of Outer class
}
}
}
public class Test {
public static void main(String[] args) {
Outer.Nested nested = new Outer.Nested();
nested.display();
}
}
14. What are user defined exceptions? Illustrate them with an example.
-> User-defined exceptions are exceptions created by the user by extending the
Exception class or its subclasses.
-These exceptions are thrown to handle specific error situations in the
application.
Ex: class AgeException extends Exception {
AgeException(String message) {
super(message);
}
}

class Test {
static void validateAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age is less than 18");
} else {
System.out.println("Age is valid");
}
}
public static void main(String[] args) {
try {
validateAge(16);
} catch (AgeException e) {
System.out.println(e.getMessage());
}
}
}
15. What is package? How to create a package.Explain with example.
-> A package in Java is a collection of related classes and interfaces.
-It helps organize the classes, interfaces, and sub-packages logically.
- Packages also help avoid name conflicts.
To create a package:
1. Use the package keyword at the beginning of the Java file.
2. The classes or interfaces defined in the package are stored in a directory
structure matching the package name.
Ex: // Saving this as MyPackage/HelloWorld.java
package MyPackage;

public class HelloWorld {


public void greet() {
System.out.println("Hello from MyPackage");
}
}

16. Write difference between Abstract class and Interface.


->
19. Which swing classes are used to create menu?
->1. JMenuBar: Used to create a menu bar.
2.JMenu: Represents a menu in the menu bar.
3.JMenuItem: Represents an individual item in a menu.
4.JCheckBoxMenuItem and JRadioButtonMenuItem: Represent checkable and
radio button items in a menu.

20. Explain Joption pane class with their static methods


-> -JOptionPane is a class in the Swing package used to display standard dialog
boxes for user interaction.
Static methods:
1. showMessageDialog(Component parentComponent, Object message):
Displays a message dialog.
2. showConfirmDialog(Component parentComponent, Object message):
Displays a confirm dialog and returns an integer indicating the user's choice.
3. showInputDialog(Component parentComponent, Object message): Displays
an input dialog and returns the user’s input as a String.
22.Explain Layout managers used in AWT.
->In AWT (Abstract Window Toolkit), layout managers are used to control the
position and size of components in a container.
-They automatically arrange the components based on their properties.
-Here are the most commonly used layout managers in AWT:
1. FlowLayout:
-Components are placed sequentially in the container, one after another.
-By default, components are placed from left to right.
2. BorderLayout:
 The container is divided into five areas: North, South, East, West, and
Center.
 Each component can be added to one of these regions
3. GridLayout:
 The container is divided into a grid of rows and columns, and
components are placed in the grid.
 Each component occupies one cell in the grid.
4. CardLayout:
 Allows switching between different panels, similar to a deck of cards.
 Each component is placed on a "card", and you can flip between them.
5. GridBagLayout:
 A more flexible layout manager that allows components to span multiple
rows and columns.
23. How is menu created in java? explain with sutaible example.
->Steps to create a menu:
1. Create a MenuBar.
2. Create Menu objects and add MenuItem objects to the menus.
3. Add the MenuBar to a frame.
Ex: import java.awt.*;
import java.awt.event.*;

public class MenuExample {


public static void main(String[] args) {
Frame frame = new Frame("Menu Example");

// Creating MenuBar
MenuBar menuBar = new MenuBar();

// Creating Menu
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");

// Creating MenuItems
MenuItem openItem = new MenuItem("Open");
MenuItem saveItem = new MenuItem("Save");

// Adding MenuItems to the Menu


fileMenu.add(openItem);
fileMenu.add(saveItem);

// Adding Menus to the MenuBar


menuBar.add(fileMenu);
menuBar.add(editMenu);

// Setting the MenuBar


frame.setMenuBar(menuBar);

// Frame settings
frame.setSize(300, 200);
frame.setVisible(true);
}
}
24. What is the use of Checkboxes and RadioButtons? Explain with sutaible
Example.
->Checkbox: A checkbox allows the user to select multiple options from a set of
options.
-Each checkbox can be independently selected or deselected.
Ex:
import java.awt.*;
import java.awt.event.*;

public class CheckboxExample {


public static void main(String[] args) {
Frame frame = new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("Option 1");
Checkbox checkbox2 = new Checkbox("Option 2");

frame.add(checkbox1, BorderLayout.NORTH);
frame.add(checkbox2, BorderLayout.SOUTH);

frame.setSize(300, 200);
frame.setVisible(true);
}
}
RadioButton: A radio button is used when the user must choose only one
option from a set of options. All radio buttons in a group are mutually
exclusive.
Ex: import java.awt.*;
import java.awt.event.*;

public class RadioButtonExample {


public static void main(String[] args) {
Frame frame = new Frame("RadioButton Example");

// Create radio buttons


CheckboxGroup group = new CheckboxGroup();
Checkbox radioButton1 = new Checkbox("Option 1", group, false);
Checkbox radioButton2 = new Checkbox("Option 2", group, false);

frame.add(radioButton1, BorderLayout.NORTH);
frame.add(radioButton2, BorderLayout.SOUTH);

frame.setSize(300, 200);
frame.setVisible(true);
}
}
25. Explain event handling classes .
->1. ActionListener: Used to handle action events like button clicks.
 Method: void actionPerformed(ActionEvent e)
2.  MouseListener: Used to handle mouse events.
 Methods: void mousePressed(MouseEvent e),
 void mouseReleased(MouseEvent e),
 void mouseClicked(MouseEvent e),
 void mouseEntered(MouseEvent e),
 void mouseExited(MouseEvent e)
3 KeyListener: Used to handle keyboard events.
 Methods: void keyPressed(KeyEvent e),
 void keyReleased(KeyEvent e),
 void keyTyped(KeyEvent e)
26. What is JFrame ? Explain its metods.
->JFrame is a class in Swing that represents a top-level window with a title and
borders.
- It is used to create the main window of a Swing application.
Methods:
1. setTitle(String title): Sets the title of the window.
2. setSize(int width, int height): Sets the size of the window.
3. setVisible(boolean visible): Makes the frame visible or invisible.
4. setDefaultCloseOperation(int operation): Defines the operation when the
user closes the window (e.g., JFrame.EXIT_ON_CLOSE).
5.getContentPane(): Gets the content pane of the JFrame, where components
are added.
Ex: import javax.swing.*;

public class JFrameExample {


public static void main(String[] args) {
JFrame frame = new JFrame("My JFrame Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
27. What is JComponent ? Explain its mehods.
->JComponent is the base class for all Swing components except top-level
containers (e.g., JFrame, JDialog).
-It provides a set of methods for common functionality like handling events,
painting, and managing the component’s layout.
Common methods of JComponent:
 setBounds(int x, int y, int width, int height): Sets the position and size of
the component.
 setPreferredSize(Dimension preferredSize): Sets the preferred size for
the component.
 setBackground(Color c): Sets the background color of the component.
 setForeground(Color c): Sets the foreground (text) color.
 repaint(): Requests a re-paint of the component.

28. How works AWT?


->1. Component-based: AWT provides basic components like buttons, text
fields, labels, and containers (such as frames and panels).
2. Event-Driven: AWT uses an event-driven model, where user actions (like
button clicks or key presses) generate events that are handled by event
listeners.
3. Heavyweight Components: AWT components are called heavyweight
because they are directly associated with the native platform's windowing
system.
-This means AWT relies on the platform's native GUI libraries for rendering.
4. Layout Management: AWT provides layout managers (like FlowLayout,
GridLayout, etc.) to control the arrangement of components in a container.
5. Event Handling: AWT uses event listeners to handle events such as mouse
clicks or key presses.
-When an event occurs, the appropriate event listener (like ActionListener or
MouseListener) is triggered to handle the event.
29. what is swing ? Give its Advantages and disadvantages.
->Swing is an advanced GUI toolkit in Java that builds on AWT but provides a
richer set of GUI components.
-It is part of the Java Foundation Classes (JFC) and offers a more flexible and
sophisticated way to create graphical interfaces.
Advantages of Swing:
1. Platform Independence
2. Lightweight Components
3. Customizable Look-and-Feel
4. Rich Set of Components
5. Flexible Layout Managers
6. Improved Event Handling.
Disadvantages of Swing:
1. Performance Issues
2. Complexity
3. Look-and-Feel Inconsistency
4. Resource Heavy
30. MVC Architecture in swing?
->Model: This represents the data or business logic of the application.
- The model is independent of the user interface (UI) and can be reused in
different contexts.
-For example, in a Swing application, the model could be a class that manages
the state of the application data (e.g., a bank account, or a list of items).
Example: A ListModel or TableModel that holds the data for a list or table.
 View: The view is responsible for displaying the data to the user.
 - In Swing, views are typically the graphical components like JButton,
JLabel, JTable, and JTextField.
 -The view listens for changes in the model and updates the display
accordingly.
Example: A JTextArea that shows the current status or a JButton that allows the
user to interact with the system.
 Controller: The controller acts as an intermediary between the model
and the view.
 -It listens for user input (like clicks, key presses, etc.) and updates the
model accordingly.
 - It may also update the view if the model changes.
Example: An ActionListener attached to a button which updates the model
when the button is clicked.

31. What is User difined exception ? Illustrate them with an example.


->A user-defined exception is a custom exception class that is created by the
user to handle specific error conditions in their program.
-It is derived from the Exception class (or RuntimeException class for
unchecked exceptions).
-This allows the user to throw and catch specific exceptions tailored to the
needs of their application.
Ex: class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

public class TestUserDefinedException {


public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older.");
} else {
System.out.println("Valid age: " + age);
}
}

public static void main(String[] args) {


try {
validateAge(16);
} catch (InvalidAgeException e) {
System.out.println(e.getMessage());
}
}
}
32. Explain Exception handling keywords
->1.try: Defines a block of code in which exceptions can occur.
 Syntax:try {
// Code that may throw an exception
}
2. catch: Catches the exception thrown by the try block.
 Syntax:try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Handle exception
}
3.finally: Defines a block of code that will always execute, whether or not an
exception occurs. It is commonly used for resource cleanup.
 Syntax: try {
// Code
} catch (Exception e) {
// Handle exception
} finally {
// Cleanup code
}
3. throw: Used to explicitly throw an exception.
 Syntax: throw new Exception("Message");
4 throws: Declares the exceptions that a method may throw.
 Syntax:
public void method() throws IOException, SQLException {
// Code
}
. 33. explain methods in InputStream and OutputSream classes
->InputStream Methods:
1. read(): Reads the next byte of data from the input stream. Returns -1
when the end of the stream is reached.
o Syntax: int read() throws IOException;
2. read(byte[] b): Reads up to b.length bytes of data into an array b.
o Syntax: int read(byte[] b) throws IOException;
3. skip(long n): Skips n bytes of input.
o Syntax: long skip(long n) throws IOException;
4. available(): Returns the estimated number of bytes available to read
from the stream.
o Syntax: int available() throws IOException;
5. close(): Closes the input stream and releases any associated system
resources.
o Syntax: void close() throws IOException;
OutputStream Methods:
1. write(int b): Writes the specified byte to the output stream.
o Syntax: void write(int b) throws IOException;
2. write(byte[] b): Writes an array of bytes to the output stream.
o Syntax: void write(byte[] b) throws IOException;
3. flush(): Flushes the stream, ensuring any buffered output is written
out.
o Syntax: void flush() throws IOException;
4. close(): Closes the output stream and releases system resources.
o Syntax: void close() throws IOException;

34. Explain methods in Reader and writer classes


->Reader Methods:
1. read(): Reads a single character of data from the input stream and
returns it as an integer.
o Syntax: int read() throws IOException;
2. read(char[] cbuf): Reads characters into a buffer (array).
o Syntax: int read(char[] cbuf) throws IOException;
3. skip(long n): Skips n characters of input.
o Syntax: long skip(long n) throws IOException;
4. close(): Closes the reader and releases system resources.
o Syntax: void close() throws IOException;
Writer Methods:
1. write(int c): Writes a single character to the output stream.
o Syntax: void write(int c) throws IOException;
2. write(char[] cbuf): Writes a character array to the output stream.
o Syntax: void write(char[] cbuf) throws IOException;
3. flush(): Flushes the stream and writes any buffered characters to the
output.
o Syntax: void flush() throws IOException;
4. close(): Closes the writer and releases system resources.
o Syntax: void close() throws IOException;

35. Explain different types of acess specifiers used in package.


1. ->public: The member is accessible from anywhere in the program,
including classes in different packages.
o Example: public int x;
2. protected: The member is accessible within the same package or in
subclasses (even if they are in different packages).
o Example: protected int y;
3. private: The member is accessible only within the same class.
o Example: private int z;
4. default (package-private): If no access specifier is provided, the member
is accessible only within the same package.
o Example: int a;

36.What is stringBuffer? Explain its any three method with an example.


->-A StringBuffer is a mutable sequence of characters, which means it can be
modified after creation.
-It is used for performing operations on strings efficiently, especially when
frequent changes (like append, insert, or delete) are required.
Ex:
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");

// 1. append() - Adds text to the end of the StringBuffer.


sb.append(" World");
System.out.println(sb); // Output: Hello World

// 2. insert() - Inserts text at the specified index.


sb.insert(5, ",");
System.out.println(sb); // Output: Hello, World

// 3. reverse() - Reverses the content of the StringBuffer.


sb.reverse();
System.out.println(sb); // Output: dlroW ,olleH
}
}
37. Explain all OOPs Concept in java

4 marks program
1.Write a java program to delete the files having extension. txt. (Use
command line arguments)
-> import java.io.File;
public class DeleteTxtFiles {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java DeleteTxtFiles <directory-path>");
System.exit(1);
}
String directoryPath = args[0];
File directory = new File(directoryPath);
if (!directory.exists() || !directory.isDirectory()) {
System.out.println("The provided path is not a valid directory.");
System.exit(1);
}
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".txt")) {
if (file.delete()) {
System.out.println("Deleted: " + file.getName());
} else {
System.out.println("Failed to delete: " + file.getName());
}
}
}
} else {
System.out.println("Error: Could not list files in the directory.");
}
}
}
2.Write a java program using swing to accept the details of project (PID, P
Name, duration) from user and display it by clicking on a button.
-> import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ProjectDetailsForm {
public static void main(String[] args))
JFrame frame = new JFrame("Project Details Form");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLayout(new FlowLayout());
JLabel labelPID = new JLabel("Project ID:");
JLabel labelPName = new JLabel("Project Name:");
JLabel labelDuration = new JLabel("Duration:");
JTextField textPID = new JTextField(15);
JTextField textPName = new JTextField(15);
JTextField textDuration = new JTextField(15);
JButton btnSubmit = new JButton("Submit");
JLabel labelResult = new JLabel("Project details will be displayed here.");
labelResult.setFont(new Font("Arial", Font.BOLD, 14));
frame.add(labelPID);
frame.add(textPID);
frame.add(labelPName);
frame.add(textPName);
frame.add(labelDuration);
frame.add(textDuration);
frame.add(btnSubmit);
frame.add(labelResult);
btnSubmit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String pid = textPID.getText();
String pname = textPName.getText();
String duration = textDuration.getText()
labelResult.setText("<html>Project ID: " + pid + "<br>Project Name: "
+ pname + "<br>Duration: " + duration + "</html>");
}
});
frame.setVisible(true);
}
}

3.Define an abstract class Shape with abstract method area ( ). Write a java
program to calculate area of Triangle
->abstract class Shape {
public abstract double area();
}
class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double area() {
return 0.5 * base * height;
}
}
public class Main {
public static void main(String[] args) {
Triangle triangle = new Triangle(5, 10);

System.out.println("Area of the Triangle: " + triangle.area());


}
}
4.Write a java program to change the text color of Lable to Red by clicking on
a button.
-> import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ChangeLabelColor {


public static void main(String[] args) {
JFrame frame = new JFrame("Change Label Color")
JLabel label = new JLabel("Click the button to change my color")
JButton button = new JButton("Change Color");
frame.setLayout(new FlowLayout());
frame.add(label);
frame.add(button);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
label.setForeground(Color.RED);
}
});
frame.setSize(300, 150);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setVisible(true);

}
5.Write a java program to copy the content from one file to another file,
while copying change the case of alphabets.
-> import java.io.*;
import java.nio.file.*;

public class FileCaseConverter {

public static void main(String[] args) )


String sourceFile = "source.txt";
String destinationFile = "destination.txt";
copyAndChangeCase(sourceFile, destinationFile);
}

public static void copyAndChangeCase(String sourceFile, String


destinationFile) {
try {
BufferedReader reader = new BufferedReader(new
FileReader(sourceFile));
BufferedWriter writer = new BufferedWriter(new
FileWriter(destinationFile));

String line;
while ((line = reader.readLine()) != null) {
String modifiedLine = changeCase(line);
writer.write(modifiedLine);
writer.newLine();
}
reader.close();
writer.close();

System.out.println("Content copied and case changed successfully.");


} catch (IOException e) {
e.printStackTrace();
}
}
public static String changeCase(String line) {
StringBuilder modifiedLine = new StringBuilder();
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (Character.isLowerCase(c)) {
modifiedLine.append(Character.toUpperCase(c));
}
else if (Character.isUpperCase(c)) {
modifiedLine.append(Character.toLowerCase(c));
}
else {
modifiedLine.append(c);
}
}return modifiedLine.toString();
}
}
6.Write a java program using swing to accept details of employee (eno,
ename, esal) and display it by clicking on a button.
-> import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class EmployeeDetailsForm {

private JFrame frame;


private JTextField enoField, enameField, esalField;
private JButton displayButton;
private JLabel resultLabel;

public EmployeeDetailsForm() {
frame = new JFrame("Employee Details Form");
frame.setSize(300, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

frame.add(new JLabel("Enter Employee Number (eno):"));


enoField = new JTextField(15);
frame.add(enoField);

frame.add(new JLabel("Enter Employee Name (ename):"));


enameField = new JTextField(15);
frame.add(enameField);

frame.add(new JLabel("Enter Employee Salary (esal):"));


esalField = new JTextField(15);
frame.add(esalField);

displayButton = new JButton("Display Details");


frame.add(displayButton);

resultLabel = new JLabel("Employee details will be shown here.");


frame.add(resultLabel);
displayButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String eno = enoField.getText();
String ename = enameField.getText();
String esal = esalField.getText();
resultLabel.setText("<html>Employee No: " + eno + "<br>Employee
Name: " + ename + "<br>Employee Salary: " + esal + "</html>");
}
});
frame.setVisible(true);
}
public static void main(String[] args) {
Thread (EDT)
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new EmployeeDetailsForm();
}
});
}
}

You might also like