AdvJava IMP
AdvJava IMP
ANS:- The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI forms.
LayoutManager is an interface that is implemented by all the classes of layout managers. There are
the following classes that represent the layout managers: one of this is
Java BorderLayout:-The BorderLayout is used to arrange the components in five regions: north,
south, east, west, and center. Each region (area) may contain one component only. It is the default
layout of a frame or window. The BorderLayout provides five constants for each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
Constructors of BorderLayout class:BorderLayout(): creates a border layout but with no gaps
between the components.
BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps
between the components.
Example of BorderLayout class: Using BorderLayout() constructor
FileName: Border.java
import java.awt.*;
import javax.swing.*;
public class Border {
JFrame f;
Border() {
f = new JFrame();
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
f.setSize(300, 300);
f.setVisible(true); }
public static void main(String[] args) {
new Border();
}}
Output:
Q2. Explain Event Delegation Model.
ANS:- The Event Delegation model is a design pattern used in event handling to manage and
handle events in a more efficient and centralized way. It is often applied in graphical user
interface (GUI) programming, where numerous components may generate events. Instead of
each component directly handling its own events, the Event Delegation model introduces a
mediator (event listener) that manages and dispatches events to appropriate handlers.
Components:-All the elements like the button, text fields, scroll bars, etc. are called components. In
Java AWT, there are classes for each component as shown in above diagram. In order to place every
component in a particular position on a screen, we need to add them to a container.
Container:-The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as Frame,
Dialog and Panel.
It is basically a screen where the where the components are placed at their specific locations. Thus it
contains and controls the layout of components.
Types of containers:
There are four types of containers in Java AWT:
Window
Panel
Frame
Dialog
Window:-The window is the container that have no borders and menu bars. You must use frame,
dialog or another window for creating a window. We need to create an instance of Window class to
create this container.
Panel:-The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc. An
instance of Panel class creates a container, in which we can add components.
Frame:-The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used container
while developing an AWT application.
Useful Methods of Component Class
Method Description
public void add(Component c) Inserts a component on this component.
public void setSize(int width,int height) Sets the size (width and height) of the component.
public void setLayout(LayoutManager m) Defines the layout manager for the component.
public void setVisible(boolean status) Changes the visibility of the component, by default
false.
Q5. Describe MVC architecture of Swing in detail.
ANS:- The model-view-controller (MVC) architecture serves as the foundation for all of Swing’s
component designs. MVC divides GUI components into three main parts. Every one of these
components is essential to the way the component functions. In MVC terminology
• Model corresponds to the state information associated with the component (data). For
example, in case of a check box, the model contains a field that indicates if the box is
checked or unchecked.
• The view visual appearance of the component based upon model data.
• The controller acts as an interface between view and model. It intercepts all the requests i.e.
receives input and commands to Model / View to change accordingly.
In reality, Swing uses a condensed version of model-delegate architecture for MVC. The
approach integrates the view and the controller object into a single component, the UI
delegate, which manages GUI events and draws the component the screen. Since Swing
handles a large portion of the event management, it is relatively simple to combine graphical
capabilities with the event processing in Java. The model and UI delegate can then
communicate with each other in both directions, as you might anticipate.
➢ MVC advantages
• It facilitates the concurrent creation of software by multiple teams; some may focus on
the model, while others may work on the view.
• They simply need to make a choice prior to model interface.
• It makes software maintenance easier since we can modify the view without having to
rebuild the model. It also permits several views on a single model.
Swing Feature
• Swing is Lightweight compared to AWT.
• Pluggable Look and Feel: This feature allow the user to change the Swing components’
appearance and feel without having to restart an application.
• Sophisticated features like JScollPane, JTable, JTabbedPane,etc.
• An application’s GUI built using Swing components is unaffected by GUI’s ownership and
delivery by a platform-specific operating system.
• Swing controls can be customized in a very easy way as visual appearance is
independent of internal representation.
• Rich controls- Swing provides a rich set of advanced controls like Tree TabbedJPane,
slider, colorpicker, and table controls.
• Uses MVC architecture.
• Platform Independent.
Q6. What are the different features of JFC? Explain.
Ans:- JFC stands for Java Foundation Classes. It is a rich and comprehensive set of GUI components
and services that simplify the development and deployment of desktop, client-side, and internet
applications. It is a superset that contains AWT. JFC extends AWT by adding many components and
services that are as follows:
API/ Feature Description
Swing GUI It includes everything from buttons to split panes to tables. Many components are capable of sorting,
Components printing, and drag and drop, to name a few of the supported features.
Pluggable The look and feel of Swing applications is pluggable, allowing a choice of look and feel. For example, the
Look-and- same program can use either the Java or the Windows look and feel. Additionally, the Java platform
Feel Support supports the GTK + look and feel, which makes hundreds of existing looks and feels available to Swing
programs. Many more look-and-feel packages are available from various sources.
Accessibility It is a part of JFC that works with alternate input and output devices. It enables assistive technologies,
API such as screen readers, screen magnifiers, and Braille terminals, to get information from the UI.
Java 2D API It enables developers to easily incorporate high-quality 2D graphics, text, and images in applications and
applets. Java 2D includes extensive APIs for generating and sending high-quality output to printing
devices.
International It allows developers to build applications that can interact with users worldwide in their own languages
ization and cultural conventions. With the input method framework, developers can build applications that
accept text in languages that use thousands of different characters, such as Japanese, Chinese, or Korean.
Drag and Drag and Drop is one of the more common metaphors used in GUI. The user is allowed to click and "hold"
Drop (DnD) a GUI object, moving it to another window or frame in the desktop with predictable results. It allows
users to implement droppable elements that transfer information between Java applications and native
applications. Although DnD is not part of Swing, it is crucial to a commercial-quality application.
STUB:- The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When caller invokes
method on stub object, it does following tasks:
1. It initiates a connection with remote Virtual Machine (JVM),
2. It writes and transmits (marshallls) the parameters to remote Virtual Machine (JVM)
3. It waits for result.
4. It reads (unmarshals) return value or exception, and
5. It finally returns the value to caller.
SKELETON:- The skeleton is an object, acts as a gateway for server-side object. All incoming requests
are routed through it. When skeleton receives incoming request, it does following tasks:
1. It reads parameter for remote method.
2. It invokes method on actual remote object, and
3. It writes and transmits (marshalls) result to caller.
4.
Q11. Explain networking basic terminologies.
ANS:- Networking Basic Terminologies
Q12 . Explain Java Networking Classes and Interfaces.
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");
con.close();
}}
Q14. What is the difference between Statement and PreparedStatement interface.
1. Statement :
It is used for accessing your database. Statement interface cannot accept parameters and useful
when you are using static SQL statements at runtime. If you want to run SQL query only once then
this interface is preferred over PreparedStatement.
Example –
//Creating The Statement Object
Statement prep_statement = con.createStatement();
//Executing The Statement
prep_statement.executeUpdate("CREATE TABLE STUDENT(ID NUMBER NOT NULL, NAME
VARCHAR)");
2. PreparedStatement :
It is used when you want to use SQL statements many times. The PreparedStatement interface
accepts input parameters at runtime.
Example –
//Creating the PreparedStatement object
PreparedStatement prep_statement = con.prepareStatement("update STUDENT set NAME = ?
where ID = ?");
//Setting values to place holders
//Assigns "RAM" to first place holder
prep_statement.setString(1, "RAM");
//Executing PreparedStatement
prep_statement.executeUpdate();
Difference between Statement and PreparedStatement :
Statement PreparedStatement
It is used when SQL query is to be executed It is used when SQL query is to be executed
only once. multiple times
.You can not pass parameters at runtime. You can pass parameters at runtime.
Used for CREATE, ALTER, DROP statements. Used for the queries which are to be executed
multiple times.
Performance is very low. Performance is better than Statement.
It is base interface. It extends statement interface.
Used to execute normal SQL queries. Used to execute dynamic SQL queries.
We can not use statement for reading binary We can use Preparedstatement for reading
data. binary data.
It is used for DDL statements. It is used for any SQL Query.
We can not use statement for writing binary We can use Preparedstatement for writing
data. binary data.
No binary protocol is used for communication. Binary protocol is used for communication.
Q15. What are jdbc statements explain its types.
ANS:- Java Database Connectivity basically is an application programming interface(API) for Java.
This helps in connecting and executing a query with the database. Thus, it helps us in defining how a
client accesses the database. This can be classified as a Java-based data access technology for
connecting to a Database.
When using JDBC, we will come across several other statements that basically define how we will be
accessing the database and up to which level of access. In this blog, we will learn about the different
types of statements in JDBC and how we can use them as an API to the database.
JDBC is used to create SQL statements in Java by providing methods to execute queries with the
database. Thus, JDBC works as an API for Java-Based Programs. JDBC also provides universal data
access from the Java programming language. These interfaces also define the methods that are
generally known to assist the bridge data type differences that exist between Java and SQL data
types basically used in a database.
There are basically three types of statements in JDBC: Create statements, Prepared statements,
Callable statements.
1.Create statement:- This is usually used when we want a general-purpose access to the database
and can be very helpful when running static SQL statements in the runtime.
Syntax:- Statement statement = connection.createStatement();
Example
Statement statement = con.createStatement();
String sql = "select * from orders";
ResultSet result = statement.executeQuery(sql);
You can also try this code with Online Java Compiler
Run Code
2.Prepared statement
These types of statements basically represent recompiled SQL statements that can be executed
many times. Thus, instead of having actual parameters in the SQL Queries it has “?” in place of the
parameters to be passed dynamically by using the methods of prepared statements at the run time.
Syntax:- String query = "INSERT INTO ORDERS(id, product) VALUES(?,?)";
` Statement test = connection.createStatement();
test.setInt(1, 45);
test.setString(2, "Pen");
Example
PreparedStatement test = con.prepareStatement("
SELECT product FROM ORDERS WHERE ID = ?");
test.setInt(1,45);
ResultSet result = test.executeQuery();
3.Callable statement
In some cases we need to work with multiple databases for some task and the scenario becomes
very complex here. Thus, rather than sending multiple queries we can simply send the required data
to the stored procedure. This will decrease the load on the database significantly. This is where
callable statements work as the stored procedures which are essentially a group of statements that
we compile in the database and are very beneficial.
Syntax:-CallableStatement cs = con.prepareCall("{call procedure_name(?,?)}")
Example
CallableStatement test = con.prepareCall("{call orderinfo(?,?)}");
test.setInt(1, 45);
test.setString(2, "Pen");
Q16. Write steps to Create Servlet Application using tomcat server.
ANS:- All these 5 steps to create our first Servlet Application.
1. Creating the Directory Structure:-Sun Microsystem defines a unique directory structure that must
be followed to create a servlet application.
servlet directory strucutre
Create the directory structure inside Apache-Tomcat\webapps directory. All HTML, static
files(images, css etc) are kept directly under Web application folder. While all the Servlet classes are
kept inside classes folder.
The web.xml (deployement descriptor) file is kept under WEB-INF folder.
2. Creating a Servlet:- There are three different ways to create a servlet.
By implementing Servlet interface
By extending GenericServlet class
By extending HttpServlet class
But mostly a servlet is created by extending HttpServlet abstract class. As discussed earlier
HttpServlet gives the definition of service() method of the Servlet interface. The servlet class that we
will create should not override service() method. Our servlet class will override only doGet() or
doPost() method.
When a request comes in for the servlet, the Web Container calls the servlet's service() method and
depending on the type of request the service() method calls either the doGet() or doPost() method.
NOTE: By default a request is Get request.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResposne response)
throws ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello Readers</h1>");
out.println("</body></html>");
}
}
Write above code in a notepad file and save it as MyServlet.java anywhere on your PC. Compile
it(explained in next step) from there and paste the class file into WEB-INF/classes/ directory that you
have to create inside Tomcat/webapps directory.
3. Compiling a Servlet:- To compile a Servlet a JAR file is required. Different servers require different
JAR files. In Apache Tomcat server servlet-api.jar file is required to compile a servlet class.
Steps to compile a Servlet:
• Set the Class Path.
• compiling a Servlet
• Download servlet-api.jar file.
• Paste the servlet-api.jar file inside Java\jdk\jre\lib\ext directory.
• compiling a Servlet
• Compile the Servlet class.
• compiling a Servlet
NOTE: After compiling your Servlet class you will have to paste the class file into WEB-INF/classes/
directory.
4. Create Deployment Descriptor:- Deployment Descriptor(DD) is an XML document that is used by
Web Container to run Servlets and JSP pages. DD is used for several important purposes such as:
• Mapping URL to Servlet class.
• Initializing parameters.
• Defining Error page.
• Security roles.
• Declaring tag libraries.
Now we will see how to create a simple web.xml file for our web application.
web.xml file
5. Start the Server:- Double click on the startup.bat file to start your Apache Tomcat Server.
Or, execute the following command on your windows machine using RUN prompt.
C:\apache-tomcat-7.0.14\bin\startup.bat
6. Starting Tomcat Server for the first time:- If you are starting Tomcat Server for the first time you
need to set JAVA_HOME in the Enviroment variable. The following steps will show you how to set it.
• Right Click on My Computer, go to Properites.- setting JAVA_HOME for Tomcat
• Go to Advanced Tab and Click on Enviroment Variables... button.- setting JAVA_HOME for
Tomcat
• Click on New button, and enter JAVA_HOME inside Variable name text field and path of JDK
inside Variable value text field. Click OK to save.- setting JAVA_HOME for Tomcat
7. Run Servlet Application
Open Browser and type http:localhost:8080/First/hello
Running first servlet application.