[go: up one dir, main page]

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

Java 4 Mark Answers Ut2

The document contains a comprehensive question bank covering various topics related to Java Swing, event handling, JDBC, and networking. It includes definitions, programming examples, and comparisons between different concepts such as AWT and Swing, as well as JDBC architecture. Additionally, it provides code snippets for practical demonstrations of event listeners and database connectivity.

Uploaded by

roshanmormare909
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)
9 views16 pages

Java 4 Mark Answers Ut2

The document contains a comprehensive question bank covering various topics related to Java Swing, event handling, JDBC, and networking. It includes definitions, programming examples, and comparisons between different concepts such as AWT and Swing, as well as JDBC architecture. Additionally, it provides code snippets for practical demonstrations of event listeners and database connectivity.

Uploaded by

roshanmormare909
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
You are on page 1/ 16

Question bank

2 marks
1.What is frame in swing. how to create frame.
Ans: A frame is a window that can hold component like button, textFiels,
label etc. that can part of the javax.swing package.
Frame is extending two ways.
1.By extending Frame class.
Syntax. Class ABC extends JFrame()
{
}
2.By creating object.
Syntax: JFrame f=new JFrame();

2. Name different Layout manager.


Ans: 1) FlowLayout
2) Border Layout
3) Grid Layout
4) Card Layout
5) GridBag Layout

3) List the different Type Of Listener.


Ans: 1.KeyListener
2.TextListener
3.MouseListener
4. MouseMotionListener
5.ActionListener
6. Item Listener
4. List method of KeyListener with syntax:-
Ans: 1.KeyPressed()
Syntax:
public void keyPressed (KeyEvent e)

2. KeyTyped ()
Syntax:
public void keyTyped (KeyEvent e)
3. KeyReleased ()
Syntax:
public void keyReleased (KeyEvent e)

5)Name method of MouseListener with Syntax:-


Ans: 1) mousePressed()
Syntax:
public void mousePressed (MouseEvent e)

2) mouseEnterd()
Syntax:
public void mouseEnterd (MouseEvent e)

3) mouseClicked()
Syntax:
public void mouseClicked (MouseEvent e)

4) mouseExited()
Syntax:
public void mouseExited (MouseEvent e)

5)mouseReleased()
Syntax:
public void mouseReleased (MouseEvent e)

6) Name method of TextListener with syntax:.


1) textchanged
Syntax:
public void textChanged (TextEvent e)

7)Define Event, source and Listener.


Event : An event is an action or occurrence detected by the program.
Events are generated by user actions.
Source: the source is the object that generates an event. It is the
component Where an event occurs.
Listener: A Listener is an interface that handles events. It listens for events
from a source and executes a Specific method When the event occurs.

8)Name the package in Which URL class is des


→import java. net.*;

9) Enlist URL connection class method.


1) Object getContent()
2) long getDate ()
3) int getContentLength ()
4) String getContentType()

10) Name the Types of drivers for data base connectivity


1)JOBC- ODBC Bridge driver
2) Native API driver
3) All Java / Net - Protocol Driver
4) Pure Java Driver / Thin driver

11)List advantages JDBC Over ODBC.


1)platform independence
2) Better security.
3) Simpler Deployment.
4) Direct Database communication.

12) What is networking & Write it's advantages and disadvantages.


Ans: Networking is the process of connecting two or more computers to
share resources, like data, files, printers or the internet. It allows
communication between devices or wired or wireless connections.
Advantages: 1. Resources Sharing
2. communication
3. Data backup
Disadvantages: 1.Sequrity risks
2.Network failure
3.Virus
4.Setup & maintenance cost

13) Difference between statement prepared statement interface.


Ans:
Statement Prepared statement
1.used to execute simple SQL 1. used to executing parameterized
quires. SQL quires.
2. Compiled every time the 2. Compiled once and rescue
query runs. multiple times.
3. Slower due to repeated 3.faster as it reuses the
Compiltation. precompiled query.
4.sutaible simple one time 4.best for quires executed multiple
quires. times with different values.
Java 4 mark Answers
Q.1 Write a program to demonstrate the use of keyEvent when key is pressed and display
“keypressed” message.

Ans.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class KeyEventDemo extends JFrame implements KeyListener {


public JLabel label;

public KeyEventDemo() {
label = new JLabel("Press any key", SwingConstants.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 20));
add(label);

addKeyListener(this);
setSize(400, 200);
setTitle("Key Event Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}

public void keyPressed(KeyEvent e) {


label.setText("Key Pressed");
}

public void keyReleased(KeyEvent e) {


label.setText("Press any key");
}

public void keyTyped(KeyEvent e)


{
}

public static void main(String[] args) {


new KeyEventDemo();
}

}
Q.2 Explain Delegation Event Model?

Ans.
Event Handling is the mechanism that controls the event and decides what should happen if
an event occurs. This mechanism have the code which is known as event handler that is
executed when an event occurs. Java Uses the Delegation Event Model to handle the events.
This model defines the standard mechanism to generate and handle the events. Let's have a
brief introduction to this model.

The Delegation Event Model has the following key participants namely:
Source - A source is an object that generates an event. This occurs when the internal state of
that object changes in some way. Sources may generate more than one type of event. A source
must register listeners in order for the listeners to receive notifications about a specific type
of event. Each type of event has its own registration method.

Here is the general form:


public void addTypeListener(TypeListener el)
Here, Type is the name of the event and el is a reference to the event listener.
For example, the method that registers a keyboard event listener is called addKeyListener( ).
The method that registers a mouse motion listener is called addMouseMotionListener( ).
Listener - It is also known as event handler. Event listeners are objects that are notified as soon
as a specific event occurs. Event listeners must define the methods to process the notification.
Listener is responsible for generating response to an event. From java implementation point of
view the listener is also an object. Listener waits until it receives an event. Once the event is
received , the listener process the event an then returns.
Steps involved in event handling
The User clicks the button and the event is generated. (eg. ActionEvent)
Now the object of concerned event class is created automatically and information about the source
and the event get populated within same object.
Event object (ActionEvent e) is forwarded to the method (eg. actionPerformed) of registered
listener class (ActionListener).
The method is now get executed and returns.

Q.3 Write a program to demonstrate ActionListener interface?

import java.awt.*;
import java.awt.event.*;

public class EventDemo extends Frame implements ActionListener {


Button btn;

EventDemo() {
btn = new Button("Click Me");
btn.setBounds(50, 100, 80, 30);
btn.addActionListener(this);
add(btn);
setSize(300, 200);
setLayout(null);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


System.out.println("Button Clicked");
}

public static void main(String[] args) {


new EventDemo();
}
}

Q.4write a program to demonstrare the use of mouseDragged and mouseMoved method of


MouseMotionListener.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MouseMotionDemo extends JFrame implements MouseMotionListener {


private JLabel label;

public MouseMotionDemo() {
label = new JLabel("Move or Drag the Mouse");
label.setFont(new Font("Arial", Font.BOLD, 16));
add(label);
addMouseMotionListener(this);

setSize(400, 300);
setLayout(new FlowLayout());

setVisible(true);
}

public void mouseDragged(MouseEvent e) {


label.setText("Mouse Dragged at: " + e.getX() + ", " + e.getY());
}

public void mouseMoved(MouseEvent e) {


label.setText("Mouse Moved at: " + e.getX() + ", " + e.getY());
}

public static void main(String[] args) {


new MouseMotionDemo();
}
}

Q.5 write a JTree program to show following output.

Ans.

import javax.swing.*;
import javax.swing.tree.*;

public class JTreeDemo {


JTreeDemo() {
JFrame frame = new JFrame("JTree Example");
DefaultMutableTreeNode style = new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color = new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font = new DefaultMutableTreeNode("font");
style.add(color); style.add(font); color.add(new DefaultMutableTreeNode("red"));
color.add(new DefaultMutableTreeNode("blue"));
color.add(new DefaultMutableTreeNode("black"));
color.add(new DefaultMutableTreeNode("green"));
JTree tree = new JTree(style);
frame.add(new JScrollPane(tree));
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args)
{
new JTreeDemo();
}

Q.6 write a program to generate following output using BorderLayout.


import javax.swing.*;
import java.awt.*;

public class b1
{
public static void main(String[] args)
{
Create frame JFrame frame = new JFrame("Border Layout Example");
frame.setSize(300, 200);
frame.setLayout(new BorderLayout());

frame.add(new JButton("North"), BorderLayout.NORTH);


frame.add(new JButton("South"), BorderLayout.SOUTH);
frame.add(new JButton("East"), BorderLayout.EAST);
frame.add(new JButton("West"), BorderLayout.WEST);
frame.add(new JButton("Center"), BorderLayout.CENTER);

frame.setVisible(true);
}

Q.7 Difference between swing and AWT?


Q.8 Write a program using a URL class to retrieve he host protocol port and file of URl
http://www.msbte.org.in.

import java.net.*;
import java.io.*;

public class URLInfo {


public static void main(String[] args) {
try {
URL url = new URL("http://www.msbte.org.in");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort());
System.out.println("File: " + url.getFile());
}
catch (MalformedURLException e)
{
System.out.println("Invalid URL");
}
}
}

Q.9 explain factory method of Ip address class.

getByName(String host)

 Returns an InetAddress object for the given hostname or IP.


 Example: InetAddress.getByName("www.google.com");

getLocalHost()

 Returns the InetAddress object of the local system (your computer).


 Example: InetAddress.getLocalHost();

getAllByName(String host)

 Returns an array of InetAddress objects for a hostname (useful if a website


has multiple IPs).
 Example: InetAddress.getAllByName("www.google.com");

getByAddress(String host, byte[] addr)

 Returns an InetAddress object for a specific hostname and byte array IP.
 Example: InetAddress.getByAddress("localhost", new byte[]{127, 0, 0, 1});

getByAddress(String host, byte[] addr)

 public static InetAddress getByAddress(String host, byte[] addr) throws


UnknownHostException
 host → The hostname (e.g., "example.com").
 addr → The IP address in byte array form.
 Throws UnknownHostException if the IP address is invalid.
Q.10 Devlop a program using InetAdress class to retrieve IP address of
computer when hostname is enter by the user.

Ans.
import java.net.*;

import java.util.Scanner;

public class IP1 {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter hostname: ");

String hostname = scanner.nextLine();

try {

InetAddress address = InetAddress.getByName(hostname);

System.out.println("IP Address: " + address.getHostAddress());

} catch (UnknownHostException e) {

System.out.println("Invalid hostname");

Q.11 Write a program to create a student table in database and insert a recors in student
table.

import java.sql.*;
public class St1{

public static void main(String[] args) {

String url = "jdbc:mysql://localhost:3306/your_database";

String user = "your_username";

String password = "your_password";

try {

Connection conn = DriverManager.getConnection(url, user, password);

Statement stmt = conn.createStatement();

String createTable = "CREATE TABLE Student (Roll_no INT PRIMARY KEY, stu_name
VARCHAR(50), course_id INT, percentage FLOAT)";

stmt.executeUpdate(createTable);

String insertData = "INSERT INTO Student VALUES (1, 'John Doe', 101, 85.5)";

stmt.executeUpdate(insertData);

System.out.println("Table created and record inserted successfully");

stmt.close();

conn.close();

} catch (SQLException e) {

e.printStackTrace();

Q.12 Explain with neat diagram of JDBC architecture


o JDBC APllication:
This is the core of JDBC, providing a set of interfaces and classes that allow Java
applications to interact with databases.
o JDBC Driver Manager:
This component manages the loading and registration of JDBC drivers, connecting the
application to the appropriate driver for a specific database.
o JDBC Drivers:
These are database-specific implementations of the JDBC API, enabling Java
applications to connect to and interact with different database systems.
Two-Tier Architecture:
o In this model, Java applications directly interact with the database through JDBC.
o The application uses the JDBC API to establish a connection, execute queries, and retrieve
results.
o The JDBC driver translates the JDBC API calls into database-specific protocols and
communicates with the database.
Three-Tier Architecture:
o This architecture introduces a middle tier (or business logic layer) between the application
and the database.
o The application interacts with the middle tier, which in turn uses JDBC to interact with the
database.
o This separation of concerns can improve application scalability, maintainability, and
security.

Key Interfaces and Classes in JDBC API:


o Connection: Establishes a connection to a database.

o Statement: Creates and executes SQL statements.


o ResultSet: Handles the data returned by the database.
o PreparedStatement: Executes parameterized SQL statements.

Q.13 Explain a two tier model of JDBC architecture .


A two-tier architecture is a type of software architecture that consists
of two main layers:

1. Client Tier (Presentation Layer) – This is the front end where users
interact with the application. It can be a Java GUI application
(Swing, JavaFX, or AWT) that takes user input and displays results.
2. Database Tier (Data Layer) – This is the back end where data is
stored. A database (like MySQL, Oracle, or PostgreSQL) stores and
manages the application's data. The client directly communicates
with the database to fetch or store data

How It Works:
 The client application sends a request (e.g., fetching user details).
 The request is sent to the database via JDBC (Java Database
Connectivity).
 The database processes the request and sends back the result.
 The client application displays the retrieved data.

You might also like