0% found this document useful (0 votes)
145 views16 pages

Java Programming Concepts and Methods

The document is a question bank for a Java Programming course at Shivajirao S. Jondhle Polytechnic, covering various topics such as KeyListener methods, Swing frames, layout managers, JDBC architecture, event handling models, and JDBC drivers. It includes practical programming examples and explanations of concepts like Socket and ServerSocket classes, panels in Swing, and the TextListener interface. Overall, it serves as a comprehensive guide for students to understand and apply Java programming principles.

Uploaded by

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

Java Programming Concepts and Methods

The document is a question bank for a Java Programming course at Shivajirao S. Jondhle Polytechnic, covering various topics such as KeyListener methods, Swing frames, layout managers, JDBC architecture, event handling models, and JDBC drivers. It includes practical programming examples and explanations of concepts like Socket and ServerSocket classes, panels in Swing, and the TextListener interface. Overall, it serves as a comprehensive guide for students to understand and apply Java programming principles.

Uploaded by

gauravbangar4449
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SHIVAJIRAO S.

JONDHLE POLYTECHNIC, ASANGAON


UT 2- JPR (314317) Question Bank

Program:CO / IF​ ​ ​ ​ ​ ​ ​ Semester: CO4K/IF4K


Subject: Java Programming​ ​ ​ ​ ​ SubjectCode:314317

1.​ List method of KeyListener with syntax.


ANS :

Method name Description

public abstract void It is invoked when a key has


keyPressed (KeyEvent e); been pressed.

public abstract void It is invoked when a key has


keyReleased (KeyEvent e); been released.

public abstract void It is invoked when a key has


keyTyped (KeyEvent e); been typed.

2.​ What is frame in swing. How to create frame.​

ANS : In Swing, a Frame is a top-level container used to create a window where components
like buttons, labels, text fields, and other Swing components can be added. It is a part of the
[Link] package and is the main container in a graphical user interface (GUI) application. A
frame represents a window with a title bar, borders, and other controls.

How to Create a Frame in Swing


To create a frame in Swing, you typically follow these steps:
1.​ Import the necessary classes: You need to import JFrame from the [Link] package.​

2.​ Create a JFrame object: The JFrame class is used to create a frame object.​

3.​ Set properties for the frame: You can set the frame's title, size, close operation, visibility,
etc.​

4.​ Make the frame visible: After setting up the frame, you need to make it visible.
3.​ List the different layout manager.
ANS:
The java. awt package provides five layout managers:
FlowLayout,
BorderLayout,
GridLayout,
CardLayout,
GridBagLayout.

4.​ Name method of ItemListener , ActionListener with syntax


ANS: 1. ItemListener

The ItemListener interface listens for changes to an item's state (such as a checkbox being
checked or unchecked).

●​ Method Name: itemStateChanged()

Syntax: void itemStateChanged(ItemEvent e);

○​ Description: This method is invoked when the state of an item (like a checkbox or
a radio button) changes.

2. ActionListener

The ActionListener interface listens for action events (such as button clicks).

●​ Method Name: actionPerformed

Syntax: void actionPerformed(ActionEvent e);

○​ Description: This method is called when an action event occurs, like pressing a
button.

Both methods are used to handle events triggered by user actions in GUI components.

5.​ Explain Two tier Model of JDBC Architecture ​


ANS:
In the two-tier model, a Java applet or application talks directly to the data source. This requires
a JDBC driver that can communicate with the particular data source being accessed. A user's
commands are delivered to the database or other data source, and the results of those statements
are sent back to the user.

6.​ Write a program to display The Number on Button from 0 to 9 using FlowLayout.
ANS:
import [Link].*;
import [Link].*;

public class NumberButtons {


public static void main(String[] args) {
// Create a JFrame for the application
JFrame frame = new JFrame("Number Buttons");

// Set FlowLayout for the frame


[Link](new FlowLayout());

// Create 10 buttons with numbers from 0 to 9


for (int i = 0; i <= 9; i++) {
JButton button = new JButton([Link](i)); // Create a button for each
number
[Link](button); // Add the button to the frame
}

// Set default close operation to exit on close


[Link](JFrame.EXIT_ON_CLOSE);

// Set the size of the frame


[Link](300, 150);

// Set the frame visibility to true


[Link](true);
}
}

7.​ Define Socket and ServerSocket class. ​

ANS: Socket Class:

The Socket class in Java is used to establish a client-side connection to a server over a network.
It allows the client to send and receive data to/from the server. The socket connection is made
using the IP address and port number of the server.

Constructor:​
Socket(String host, int port);
This constructor creates a new socket connected to the specified server using the given host and
port number.​
ServerSocket Class:

The ServerSocket class in Java is used to create a server-side socket that listens for incoming
client connections. It is used to establish a communication channel between the server and the
client.

●​ Constructor:​
ServerSocket(int port) throws IOException;

This constructor creates a server socket bound to the specified port number.​

8.​ Differences between SWING and AWT​


ANS:
9.​ Explain Delegation Event Model​
ANS:
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.

The below image demonstrates the event processing.

the modern approach for event processing is based on the Delegation Model. It defines a
standard and compatible mechanism to generate and process events. In this model, a
source generates an event and forwards it to one or more listeners. The listener waits until
it receives an event. Once it receives the event, it is processed by the listener and returns
it. The UI elements are able to delegate the processing of an event to a separate function.

Flow of Event Handling in Delegation Event Model:


1.​ An Event Source Generates an Event:
2.​ The Event is Propagated to the Listener:
3.​ Listener Handles the Event:
4.​ Event Handling Is Separated from Event Generation:​
Explanation of Delegation Event Model:
1.​ Event Source:​

○​ The Event Source is the object that generates an event. This could be any GUI
component such as a button, a text field, a checkbox, etc.
○​ For example, a JButton (button) is an event source that generates an event when
clicked.​
2.​ Event Object:​

○​ The Event Object represents the actual event that is generated by the event source.
It contains information about the event such as the type of event, the source of the
event, and other relevant data (e.g., mouse click coordinates, key pressed, etc.).
○​ For example, ActionEvent, MouseEvent, KeyEvent, etc., are event objects used to
represent specific types of events.​

3.​ Listener:​

○​ A Listener is an object that waits for and responds to events. The listener is
responsible for handling events generated by event sources.
○​ Listeners are typically interface implementations. For example, the
ActionListener interface listens for ActionEvent objects, and MouseListener
listens for MouseEvent objects.
○​ A listener must implement an interface that defines the methods that will handle
the event. These methods are called when the event occurs.​

10.​Explain URL class Constructor (any 4)


ANS:
1 public URL(String protocol, String host, int port, String file) throws
MalformedURLException
Creates a URL by putting together the given parts.

2 public URL(String protocol, String host, int port, String file, URLStreamHandler handler)
throws MalformedURLException
Creates a URL by putting together the given parts with the specified handler within a
specified context.

3 public URL(String protocol, String host, String file) throws MalformedURLException


Identical to the previous constructor, except that the default port for the given protocol is
used.

4 public URL(String url) throws MalformedURLException


Creates a URL from the given String.

5 public URL(URL context, String url) throws MalformedURLException


Creates a URL by parsing together the URL and String arguments.

6 public URL(URL context, String url, URLStreamHandler handler) throws


MalformedURLException
Creates a URL by parsing together the URL and String arguments with the specified
handler within a specified context.
11.​ Explain Factory method of InetAddress class
ANS:

The InetAddress class in Java, part of the [Link] package, represents an IP address. It provides
methods for obtaining the IP address of a machine, whether it is in IPv4 or IPv6 format. The
class includes several factory methods to create instances of InetAddress. These methods are
designed to return a specific InetAddress object based on different input criteria.

the important factory methods of the InetAddress class is:

getByName(String host): Resolves a host name or IP address to an InetAddress object.​

getByAddress(String host, byte[] addr): Creates an InetAddress object using an IP


address represented by a byte array.​

getAllByName(String host): Returns an array of InetAddress objects for a host with


multiple IP addresses.​

getLocalHost(): Returns the InetAddress object for the local machine (localhost).

12.​ Explain four types of JDBC drivers.


ANS:
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.

For example, using JDBC drivers enable you to open database connections and to interact with it
by sending SQL or database commands then receiving results with Java.

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC
bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.
Advantages:
●​ easy to use.
●​ can be easily connected to any database.

Disadvantages:
●​ Performance degraded because JDBC method call is converted into the ODBC function
calls.
●​ The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.

Advantage:
●​ performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
●​ The Native driver needs to be installed on the each client machine.
●​ The Vendor client library needs to be installed on client machine.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
●​ No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.

Disadvantages:
●​ Network support is required on client machine.
●​ Requires database-specific coding to be done in the middle tier.
●​ Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.

4) 100% Pure Java/Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.
Advantage:
●​ Better performance than all other drivers.
●​ No software is required at client side or server side.

Disadvantage:
●​ Drivers depend on the Database.

13.​ Write program to Create a student table in database and insert a record in
student table.
ANS:
import [Link].*;

public class StudentDatabase {


public static void main(String[] args) {
// Step 1: Load and register the JDBC-ODBC driver
try {
// Register JDBC ODBC driver (JDBC-ODBC Bridge is deprecated in modern
versions of Java)
[Link]("[Link]");

// Step 2: Establish a connection to the database (replace DSN with your actual
DSN)
String url = "jdbc:odbc:StudentDB"; // Replace "StudentDB" with your ODBC
DSN
Connection conn = [Link](url);

// Step 3: Create a statement object


Statement stmt = [Link]();
// Step 4: Create a student table
String createTableSQL = "CREATE TABLE Student (" +
"id INT PRIMARY KEY, " +
"name VARCHAR(100), " +
"age INT, " +
"address VARCHAR(255))";
[Link](createTableSQL);
[Link]("Student table created successfully.");

// Step 5: Insert a record into the student table


String insertSQL = "INSERT INTO Student (id, name, age, address) VALUES (1,
'John Doe', 22, '123 Main St')";
[Link](insertSQL);
[Link]("Record inserted successfully.");

// Step 6: Close the connection


[Link]();
} catch (ClassNotFoundException e) {
[Link]("JDBC-ODBC driver not found.");
} catch (SQLException e) {
[Link]("SQL Exception: " + [Link]());
}
}
}

14.​ What is panel ? How to create with example.

ANS: In Java Swing, a Panel is a container used to group together components like buttons,
labels, text fields, etc. A JPanel is a subclass of the Container class and provides a space for
placing multiple GUI components. Panels are often used to organize components within a frame
and allow for better layout management.

●​ Purpose of a Panel:​

○​ It helps to organize components visually by grouping them logically.​

○​ It is used to add multiple components to a single container or to use it for layout


management (e.g., FlowLayout, GridLayout, etc.).​

○​ Panels are used to divide a GUI into sections for more manageable and
maintainable code.

How to Create a JPanel:

You can create a JPanel by either:


1.​ Creating a panel directly and adding components to it.​

2.​ Using a layout manager to arrange the components within the panel.

15.​ Name method of TextListener with syntax

ANS: The TextListener interface in Java is used to listen for text events (such as when text is
changed in a text field or text area). It has a single method that you need to implement to handle
text events.

Method of TextListener:

1.​ textValueChanged(TextEvent e)​

○​ Description: This method is called when the text in a text component (like
TextField or TextArea) is changed. You can implement this method to handle the
event when the text is modified.​

Syntax: public void textValueChanged(TextEvent e);

○​ Parameters:​

■​ TextEvent e: This is the event object that contains information about the
text event.​

○​ Return Value:​

■​ This method does not return anything (void).

16.​ Write a program using JTextField to perform the addition of two numbers
ANS:
import [Link].*;
import [Link].*;
import [Link].*;

public class AdditionApp {


public static void main(String[] args) {
// Create a JFrame to hold all the components
JFrame frame = new JFrame("Addition Program");

// Create the components (labels, textfields, button)


JLabel label1 = new JLabel("Enter first number:");
JLabel label2 = new JLabel("Enter second number:");
JTextField textField1 = new JTextField(10);
JTextField textField2 = new JTextField(10);
JButton addButton = new JButton("Add");
JLabel resultLabel = new JLabel("Result:");

// Set layout manager for the frame


[Link](new FlowLayout());

// Add components to the frame


[Link](label1);
[Link](textField1);
[Link](label2);
[Link](textField2);
[Link](addButton);
[Link](resultLabel);

// Add an action listener to the button to perform addition


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// Get the numbers from text fields and parse them as integers
int num1 = [Link]([Link]());
int num2 = [Link]([Link]());

// Perform addition
int sum = num1 + num2;

// Display the result


[Link]("Result: " + sum);
} catch (NumberFormatException ex) {
// Handle invalid input
[Link]("Please enter valid numbers.");
}
}
});

// Set frame properties


[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
17.​Write the difference between SeverSocket and DatagramPacket
ANS:
Feature ServerSocket DatagramPacket

Purpose Used to create a server-side socket Used to represent a packet of data for
for accepting client connections in a sending or receiving in a UDP
TCP connection. connection.

Protocol TCP (Transmission Control UDP (User Datagram Protocol), which


Protocol), which is is connectionless and does not
connection-oriented and reliable. guarantee reliability.

Use Case Typically used in a client-server Used for sending/receiving data over
application to listen for incoming the network in the form of discrete
TCP connections from clients. packets.

Connection Requires a connection between the No connection between the sender and
Type client and server, ensuring receiver, data is sent as discrete
reliability and order. packets without any connection.

Flow Control Provides flow control and No flow control or error-checking,


error-checking to ensure that data is each packet is independent.
sent and received correctly.

Method for ServerSocket serverSocket = new DatagramPacket packet = new


Creation ServerSocket(port); DatagramPacket(data, length, address,
port);

Reliability Reliable: Guarantees in-order Unreliable: No guarantee of data


delivery of data and error-free delivery or order; packets may be lost
transmission. or arrive out of order.

18.​Write a program using URL class to retrieve the host, protocol, port and file of URL
[Link]
ANS:
import [Link].*;
public class URLExample {
public static void main(String[] args) {
try {
// Create a URL object with the given URL
URL url = new URL("[Link]
// Get the protocol of the URL
String protocol = [Link]();
[Link]("Protocol: " + protocol);
// Get the host of the URL
String host = [Link]();
[Link]("Host: " + host);
// Get the port of the URL (default is -1 if not specified)
int port = [Link]();
if (port == -1) {
port = [Link](); // Get default port if not specified
}
[Link]("Port: " + port);
// Get the file part of the URL (after the domain name)
String file = [Link]();
[Link]("File: " + file);
} catch (MalformedURLException e) {
// Handle invalid URL format
[Link]("The URL is malformed: " + [Link]());
}
}
}

19.​Write the use of Class .forName()


ANS:

[Link]() is a method in Java that is used to load a class dynamically at runtime. It is


commonly used for loading classes whose names are not known at compile time, typically in
cases such as JDBC (Java Database Connectivity), where a database driver is loaded
dynamically.

Syntax:
[Link]("fullyQualifiedClassName");

●​ "fullyQualifiedClassName": This is the fully qualified name of the class you want to load
(including the package name).

20.​Explain Applet Life Cycle in Java

Ans: In Java, an applet is a special type of program embedded in the web page to generate
dynamic content. Applet is a class in Java.

The applet life cycle can be defined as the process of how the object is created, started, stopped,
and destroyed during the entire execution of its application. It basically has five core methods
namely init(), start(), stop(), paint() and destroy().These methods are invoked by the browser to
execute.

Methods of Applet Life Cycle


There are five methods of an applet life cycle, and they are:

●​ init(): The init() method is the first method to run that initializes the applet. It can be
invoked only once at the time of initialization. The web browser creates the initialized
objects, i.e., the web browser (after checking the security settings) runs the init() method
within the applet.
●​ start(): The start() method contains the actual code of the applet and starts the applet. It is
invoked immediately after the init() method is invoked. Every time the browser is loaded
or refreshed, the start() method is invoked. It is also invoked whenever the applet is
maximized, restored, or moving from one tab to another in the browser. It is in an
inactive state until the init() method is invoked.
●​ stop(): The stop() method stops the execution of the applet. The stop () method is invoked
whenever the applet is stopped, minimized, or moving from one tab to another in the
browser, the stop() method is invoked. When we go back to that page, the start() method
is invoked again.
●​ destroy(): The destroy() method destroys the applet after its work is done. It is invoked
when the applet window is closed or when the tab containing the webpage is closed. It
removes the applet object from memory and is executed only once. We cannot start the
applet once it is destroyed.
●​ paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.

You might also like