Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Advanced Java Notes

The document is a question bank solution for Advanced Java focusing on event handling using AWT and Swing components. It covers key concepts such as frames, panels, layout managers, listeners, and network programming, providing definitions, methods, and examples. Additionally, it discusses the differences between AWT and Swing, as well as networking basics including sockets and URL handling.

Uploaded by

Dipak Dumbe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Advanced Java Notes

The document is a question bank solution for Advanced Java focusing on event handling using AWT and Swing components. It covers key concepts such as frames, panels, layout managers, listeners, and network programming, providing definitions, methods, and examples. Additionally, it discusses the differences between AWT and Swing, as well as networking basics including sockets and URL handling.

Uploaded by

Dipak Dumbe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Advanced Java

Question Bank Solution


UNIT 4 – EVENT HANDLING USING ABSTRACT WINDOW
TOOLKIT (AWT) & SWINGS COMPONENTS
2 Marks
1. What is frame in swing. how to create frame.
Answer:
In Java Swing, a frame is a main window where components like buttons,
labels, text fields etc. are added. It is used to create Graphical User Interface
(GUI) applications. The class used for creating a frame is JFrame. It is a part of
the javax.swing package.
A frame works like a container that holds all GUI components. It provides
features like setting size, title, layout, visibility, close operation, etc
To create a frame in Swing, follow these steps:
1. Create an object of JFrame class.
2. Set the title using setTitle().
3. Set the size using setSize(width, height).
4. Set layout if needed.
5. Set default close operation using setDefaultCloseOperation().
6. Make the frame visible using setVisible(true).

2. What is panel ? How to create with example.


Answer:
In Java Swing, a panel is a container used to group and organize GUI
components like buttons, labels, and text fields. It is created using the JPanel
class, which is a part of the javax.swing package.
To create a panel in Swing:
1. Create an object of JPanel.

1
2. Set layout if needed.
3. Add components to the panel.
4. Add the panel to the frame.
Example:
JFrame frame = new JFrame("Panel Example");
JPanel panel = new JPanel();
JButton button = new JButton("Click Me");
panel.add(button);
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);

3. Name Different Layout manager.


Answer:
Different types of layout managers are:
1. FlowLayout – Arranges components in a row, one after another.
2. BorderLayout – Divides the container into five regions: North, South,
East, West, and Center.
3. GridLayout – Arranges components in rows and columns like a table.
4. BoxLayout – Places components either vertically or horizontally.
5. CardLayout – Allows switching between components like cards.
6. GridBagLayout – A flexible and complex layout for advanced
positioning.
7. GroupLayout – Used mostly with GUI builders like NetBeans.

2
4. Define Container list any 4 type of container
Answer:
A container is a class in Swing that is used to hold and manage GUI
components like buttons, text fields, labels, and even other containers.
Containers help in organizing the layout of components on the screen.
Four types of commonly used containers are:
1. JFrame – Main window for a GUI application.
2. JPanel – Used to group components inside a frame.
3. JDialog – Popup window for messages or inputs.
4. JScrollPane – Provides scrolling for large components.

5. Name the package which is used to design AWT control.


Answer:
The package used to design AWT controls is java.awt.
To use AWT controls, we must import the package like this:
import java.awt.*;

6. List the different types of Listeners.


Answer:
Different types of listeners are:
1. ActionListener – Handles button clicks or menu actions.
2. ItemListener – Handles item selection events in checkboxes or combo
boxes.
3. KeyListener – Handles keyboard key press, release, and typing.
4. MouseListener – Handles mouse clicks, presses, releases, entry, and exit.
5. MouseMotionListener – Handles mouse movement and dragging.
6. WindowListener – Handles window events like open, close, minimize,
etc.

3
7. FocusListener – Handles focus gained or lost events.
8. TextListener – Handles text changes in text components.

7. List method of KeyListener with syntax.


Answer:
Methods of KeyListener:
1. public void keyPressed(KeyEvent e)
– Called when a key is pressed.
2. public void keyReleased(KeyEvent e)
– Called when a key is released.
3. public void keyTyped(KeyEvent e)
– Called when a key is typed (pressed and released).
Syntax Example:
import java.awt.event.*;

public class MyKeyListener implements KeyListener {


public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed");
}
public void keyReleased(KeyEvent e) {
System.out.println("Key Released");
}
public void keyTyped(KeyEvent e) {
System.out.println("Key Typed");
}
}

4
8. Name method of MouseListener with syntax
Answer:
Methods of MouseListener:
1. public void mouseClicked(MouseEvent e)
– Called when a mouse button is clicked.
2. public void mousePressed(MouseEvent e)
– Called when a mouse button is pressed.
3. public void mouseReleased(MouseEvent e)
– Called when a mouse button is released.
4. public void mouseEntered(MouseEvent e)
– Called when the mouse enters a component.
5. public void mouseExited(MouseEvent e)
– Called when the mouse leaves a component.
Syntax Example:
import java.awt.event.*;

public class MyMouseListener implements MouseListener {


public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked");
}
public void mousePressed(MouseEvent e) {
System.out.println("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
System.out.println("Mouse Released");
}
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse Entered");

5
}
public void mouseExited(MouseEvent e) {
System.out.println("Mouse Exited");
}
}

9. Name method of MouseMotionListener with syntax


Answer:
Methods of MouseMotionListener:
1. public void mouseMoved(MouseEvent e)
– Called when the mouse is moved over a component without pressing
any button.
2. public void mouseDragged(MouseEvent e)
– Called when the mouse is moved while a button is being pressed.
Syntax Example:
import java.awt.event.*;

public class MyMouseMotionListener implements MouseMotionListener {


public void mouseMoved(MouseEvent e) {
System.out.println("Mouse Moved");
}
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse Dragged");
}
}

6
10. Name method of ItemListener , ActionListener with syntax
Answer:
ItemListener:
ItemListener is used to handle item selection events, such as when a checkbox
or choice is selected or deselected.
• Method:
public void itemStateChanged(ItemEvent e)

ActionListener:
ActionListener is used to handle action events, such as button clicks.
• Method:
public void actionPerformed(ActionEvent e)

11. Name method of TextListener with syntax


Answer:
Method of TextListener:
• public void textValueChanged(TextEvent e)
– Called whenever the value of the text changes.
Syntax Example:
import java.awt.*;
import java.awt.event.*;
public class MyTextListener implements TextListener {
public void textValueChanged(TextEvent e) {
System.out.println("Text changed");
}
}

7
12. Name the package which is used to design AWT control and swing.
Answer:
To design AWT and Swing controls in Java, two different packages are used:
java.awt – This package is used to create AWT (Abstract Window Toolkit)
controls like buttons, labels, text fields, checkboxes, etc.
javax.swing – This package is used to create Swing controls, which are
advanced and flexible GUI components like JButton, JLabel, JTextField, etc.
Swing is built on top of AWT and provides more features and a better look.

13. Define Event, source and Listener


Answer:
In Java, Event Handling is a process where we manage user interactions like
button clicks, key presses, mouse actions, etc. Three main parts are involved:
Event:
An event is an object that shows a user action, like clicking a button or
typing a key.
Example: ActionEvent, MouseEvent, KeyEvent.
Source:
The source is the component (like a button or text field) where the event
happens.
Example: If a button is clicked, the button is the source.
Listener:
A listener is an interface that waits for events and runs the required code
when the event occurs.
Example: ActionListener, MouseListener, KeyListener

8
4 Marks
3. Explain feature of swing.
Answer:
Swing is a part of Java Foundation Classes (JFC) used to create Graphical
User Interface (GUI) applications. It is more powerful and flexible than AWT.
Swing is available in the javax.swing package.
Features of Swing:
1. Lightweight – Swing components do not depend on the operating
system, so they are more flexible and portable.
2. Platform Independent Look and Feel – Swing allows the GUI to look
the same on all platforms or take the look of the current OS.
3. Pluggable Look and Feel – Developers can change the appearance of
components without changing their code.
4. Rich Set of Components – Swing provides advanced components like
JTable, JTree, JTabbedPane, etc.
5. MVC Architecture – Swing follows Model-View-Controller for better
separation of data and UI.
6. Customizable – Swing components can be easily customized.

7. Explain Delegation Event Model


Answer:
Delegation Event Model in Java
The Delegation Event model is defined to handle events in GUI programming
languages. The GUI stands for Graphical User Interface, where a user
graphically/visually interacts with the system.
The GUI programming is inherently event-driven; whenever a user initiates an
activity such as a mouse activity, clicks, scrolling, etc., each is known as an
event that is mapped to a code to respond to functionality to the user. This is
known as event handling.

9
In this section, we will discuss event processing and how to implement the
delegation event model in Java. We will also discuss the different components
of an Event Model.

Event – An object that describes a user action. Example: ActionEvent,


MouseEvent.
Source – The component where the event occurs. Example: A Button is the
source when it is clicked.
Listener – An interface that listens for the event and handles it when it
occurs. Example: ActionListener, MouseListener.
How it works:
• The source generates an event.
• The event is sent to the listener registered for it.
• The listener performs some action based on the event.

10
18. Differences between SWING and AWT.
Asnwer:
Point AWT Swing

Package java.awt javax.swing


Lightweight/Heavyweight Heavyweight Lightweight (does not
(depends on OS) depend on OS)
Look and Feel Same as OS Custom look and feel
(pluggable)
Components Basic components Rich components
(Button, Label, etc.) (JButton, JLabel,
JTable)
Platform Independent Not fully (depends on Fully platform
native code) independent
Features Limited Advanced (tooltips,
icons, tabbed panes,
etc.)
Threading Not thread-safe Mostly thread-safe

11
UNIT 5 – BASICS OF NETWORK PROGRAMMING

2 Marks
1. What is networking? Write its advantage and disadvantage
Answer:
Networking is the process of connecting two or more computers to share
data, files, and resources like printers or internet. It is used in communication
systems, the internet, and client-server models.
Advantages:
• Easy data sharing
• Centralized data management
• Cost-effective resource sharing
Disadvantages:
• Security risks
• Virus and malware spread easily
• Expensive setup for large networks

2. Define Socket and ServerSocket class.


Answer:
• Socket class is used by the client to connect to the server. It allows
sending and receiving data.
• ServerSocket class is used by the server to listen and accept client
requests.
Both classes are part of the java.net package.

12
3. Write the use of getByName() and getAllByName() method
Answer:
• getByName(String host): Returns the IP address of the given host.
• getAllByName(String host): Returns all IP addresses associated with the
host name.
Both methods are from the InetAddress class.

4. Write the function of Connect(), Bind()


Answer:
• connect(): Used to establish a connection between the client and the
server.
• bind(): Used by the server to assign a specific IP address and port number
to the socket.

5. Name the package in which URL class is defined


Answer:
The URL class is defined in the java.net package.

6. Write the use of openConnection() method of URLConnection class.


Answer:
The openConnection() method is used to open a connection to a URL and
return a URLConnection object. It helps in reading from or writing to the
URL resource.

13
4 Marks
3. Write the difference between SeverSocket and DatagramPacket
Answer:
Point ServerSocket DatagramPacket

Used for TCP (connection-oriented UDP (connectionless


communication) communication)
Purpose Listens for incoming client Sends or receives data
connections packets
Reliability Reliable, ensures data Not reliable, no guarantee of
delivery delivery
Connection Requires a connection No connection required
Type
Class java.net.ServerSocket java.net.DatagramPacket
Package

4. Explain URL class with example.


Answer:
The URL (Uniform Resource Locator) class in Java is used to represent a web
resource address like a file, image, or web page on the internet. It is defined in
the java.net package.
The URL class helps in:
• Reading data from web resources
• Opening a connection to a website
• Getting parts of a URL (protocol, host, file, etc.)
Common constructors and methods:
• URL(String spec) – creates a URL object from a string.
• getProtocol() – returns the protocol (e.g., http).
• getHost() – returns the domain name.

14
• getFile() – returns the file name.
• openStream() – opens a stream to read content.
Example:
import java.net.*;

public class URLExample {


public static void main(String[] args) throws Exception {
URL url = new URL("https://www.javatpoint.com/java-url-class");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("File: " + url.getFile());
}
}

5. Explain URLConnection class method (any 4)


Answer:
The URLConnection class in Java is used to connect to a resource on the
internet and communicate with it. It is present in the java.net package.
Common methods of URLConnection:
1. connect() – Opens a connection to the resource.
2. getInputStream() – Returns an input stream to read data from the URL.
3. getContentType() – Returns the MIME type (content type) of the
resource.
4. setDoOutput(boolean) – Sets whether the connection allows sending
data (for POST requests).
These methods are useful for reading from or writing to websites, APIs, or
online files.

15
6. Explain URL class Constructor (any 4)
Answer:
The URL class constructors are used to create URL objects with different
inputs. These are present in the java.net package.
Common constructors of URL class:
1. URL(String spec)
– Creates a URL from a full string.
Example: new URL("https://www.google.com")
2. URL(String protocol, String host, String file)
– Creates a URL with protocol, host, and file path.
Example: new URL("https", "www.google.com", "/search")
3. URL(String protocol, String host, int port, String file)
– Same as above but includes a port number.
Example: new URL("http", "localhost", 8080, "/index.html")
4. URL(URL context, String spec)
– Creates a URL using a base URL and relative path.
Example: new URL(baseURL, "/page.html")

7. Explain Factory method of InetAddress class


Answer:
Factory methods of the InetAddress class are static methods used to create or
get InetAddress objects. These methods help in resolving IP addresses from
hostnames.
Common factory methods:
1. getByName(String host)
– Returns the InetAddress of the given host name.
Example: InetAddress ip =
InetAddress.getByName("www.google.com");
2. getAllByName(String host)
– Returns all InetAddress objects for a host name.
Example: InetAddress[] ips =
InetAddress.getAllByName("www.google.com");

16
3. getLocalHost()
– Returns the IP address of the local machine.
Example: InetAddress local = InetAddress.getLocalHost();
These methods help in DNS lookup and network communication.

8. Explain Instance Methods of InetAddress class


Answer:
Instance methods of InetAddress are used on objects returned by factory
methods. They help in getting details of an IP address.
Common instance methods:
1. getHostName()
– Returns the hostname of the IP address.
Example: ip.getHostName();
2. getHostAddress()
– Returns the IP address in string form.
Example: ip.getHostAddress();
3. isReachable(int timeout)
– Checks if the host is reachable within given time (in ms).
Example: ip.isReachable(5000);
4. toString()
– Returns the IP address and hostname as a string.
Example: ip.toString();
These methods are useful for network diagnostics and communication.

17
UNIT 6 – INTERACTING WITH DATABASE

2 Marks
1. Name the Types of drivers for database connectivity.
Answer:
There are 4 types of JDBC drivers for database connectivity in Java:
1. Type-1: JDBC-ODBC Bridge driver
2. Type-2: Native-API driver
3. Type-3: Network Protocol driver
4. Type-4: Thin driver (Pure Java driver)

2. Write the use of Class.forName()


Answer:
Class.forName("driver_class_name") is used to load the JDBC driver class
dynamically at runtime. It registers the driver with the DriverManager to
enable database connection.
Example:
Class.forName("com.mysql.cj.jdbc.Driver");

3. List Advantages JDBC over ODBC.


Answer:
• JDBC is platform-independent (pure Java).
• No need for native libraries like ODBC.
• Better performance in Java apps.
• Easier to deploy in web applications.
• JDBC supports multiple databases easily.

18
4. Write Advantages and Disadvantages of Statements and
PreparedStatement
Answer:
Point Statement PreparedStatement

Advantages Easy to use for simple Faster for repeated queries,


queries secure
No pre-compilation needed Prevents SQL injection
Disadvantages Slower for repeated Slightly more complex to set
execution up
Prone to SQL injection Pre-compilation may take time
attacks

5. List steps for database connectivity


Answer:
1. Load the driver using Class.forName()
2. Establish connection using DriverManager.getConnection()
3. Create statement using createStatement() or prepareStatement()
4. Execute query using executeQuery() or executeUpdate()
5. Process results from ResultSet
6. Close connection using close()

6. Differentiate between Statement and PreparedStatement Interface


Answer:
Feature Statement PreparedStatement

Query Type Used for static queries Used for dynamic queries
Performance Slower for repeated use Faster due to pre-
compilation
Security Prone to SQL injection Safe from SQL injection

19
Parameter Does not support Supports placeholders (?)
Support parameters

20
4 Marks
5. Explain Types of ResultSet
Answer:
The ResultSet in JDBC is an object that holds data retrieved from a database
after executing a SQL query. It is part of the java.sql package.
There are three main types of ResultSet based on movement and updates:
1. TYPE_FORWARD_ONLY
o Cursor moves only forward.
o This is the default type.
o Fast and memory efficient.
2. TYPE_SCROLL_INSENSITIVE
o Cursor can move forward and backward.
o Data is not updated if the database changes after fetching.
3. TYPE_SCROLL_SENSITIVE
o Cursor can move in any direction.
o Data is updated if the database changes after fetching.
Syntax to create a scrollable ResultSet:
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
These types help control how data is read and navigated in result sets.

6. Explain the methods of ResultSet Interface


Answer:
The ResultSet interface in JDBC provides methods to read and move through
the data returned by a SQL query. It is defined in the java.sql package.
Here are some commonly used methods:

21
1. next()
o Moves the cursor to the next row.
o Returns false if there are no more rows.
2. getString(int columnIndex) / getString(String columnName)
o Returns the value of the specified column as a String.
3. getInt(int columnIndex) / getInt(String columnName)
o Returns the value of the specified column as an integer.
4. previous()
o Moves the cursor to the previous row (only in scrollable
ResultSet).
5. first() / last()
o Moves the cursor to the first or last row (scrollable ResultSet).
6. absolute(int row)
o Moves the cursor to the given row number.
7. close()
o Closes the ResultSet to free up resources.
These methods help in navigating and accessing the data row by row.

7. Explain with neat diagram of JDBC architecture.


Answer:
JDBC (Java Database Connectivity) architecture provides a way for Java
applications to communicate with databases. It uses drivers to interact with
different databases and perform operations like insert, update, delete, and read.
JDBC Architecture has two main layers:
1. JDBC API Layer
o Provides interfaces like Connection, Statement, ResultSet, etc.
o Java application uses this layer to send SQL queries.

22
2. JDBC Driver Layer
o Converts Java calls into database-specific calls.
o Uses one of the four JDBC driver types to interact with the
database.
Steps in JDBC Communication:
• Java Application → JDBC API → JDBC Driver → Database
• Database → JDBC Driver → JDBC API → Java Application

8. Explain Two Tier Model of JDBC Architecture


Answer:
The Two-Tier Architecture of JDBC is a simple client-server model. In this
model, the Java application (client) connects directly to the database (server)
using JDBC API and a JDBC driver.
Working of Two-Tier Model:

23
1. The Java application uses JDBC to send SQL queries.
2. The JDBC driver converts these queries into database-specific
commands.
3. The Database server processes the request and sends back the result.
4. The result is shown to the user through the Java application.
Main Components:
• Client (Java Application)
• JDBC API
• JDBC Driver
• Database Server
Features:
• Simple and fast communication.
• Best for small-scale applications.
• Less secure for large systems as direct access to DB is given.

9. Explain JDBC drivers.


Answer:
JDBC drivers are software components that help Java applications connect to
databases. These drivers translate JDBC method calls into database-specific
calls.
There are 4 types of JDBC drivers:
1. Type-1: JDBC-ODBC Bridge Driver
o Converts JDBC calls into ODBC calls.
o Requires ODBC driver installed.
o Slower and outdated, not recommended.
2. Type-2: Native-API Driver
o Converts JDBC calls into native database API calls using native
libraries.

24
o Platform-dependent.
o Better performance than Type-1.
3. Type-3: Network Protocol Driver
o Sends JDBC calls to a middleware server, which then
communicates with the database.
o Flexible, suitable for enterprise apps.
o Requires network configuration.
4. Type-4: Thin Driver
o Pure Java driver, directly connects to the database.
o Best performance and platform-independent.
o Commonly used in modern applications.

25

You might also like