Model Answer AJ
Model Answer AJ
Advanced JAVA
Q.1 Solve any five :
a) What is JApplet?
Ans :- JApplet is a simple extension of java. applet. Applet to use when creating
Swing programs designed to be used in a web browser (or appletviewer ).
As a direct subclass of Applet , JApplet is used in much the same way, with the
init( ) , start( ) , and stop( ) methods still playing critical roles.
b) Define Port.
Ans :- The port number is used to uniquely identify different applications. It acts
as a communication endpoint between applications.
The port number is associated with the IP address for communication between
two applications.
Other containers used to save screen space include split panes and tabbed
panes.
f) What is BDK ?
Ans :- The BDK for Java is Symphony's preferred tooling for Java developers to
build bots. It is a library of tools and API bindings that provides simplified
configuration and authentication, intuitive message and room management,
customizable message templating and an activities API that makes it easy to
build bot workflows.
The Beans Development Kit (BDK) includes example beans and the BeanBox
tool. The BDK is optional; you can create beans without it. However, the
BeanBox tool is extremely useful and is used throughout this book.
Q.2
a) Describe any two layout manager with an example.
Ans :-
1. Border Layout :
This layout will display the components along the border of the container. This
layout contains five locations where the component can be displayed. Locations
are North, South, East, west, and Center. The default region is the center. The
above regions are the predefined static constants belonging to the BorderLayout
class.
Example :
import java.awt.*;
public class BorderLayoutDemo
{
public static void main (String[]args)
{
Frame f1 = new Frame ();
f1.setSize (250, 250);
Button b1 = new Button ("Button1");
Button b2 = new Button ("Button2");
Button b3 = new Button ("Button3");
Button b4 = new Button ("Button4");
Button b5 = new Button ("Button5");
f1.add (b1, BorderLayout.NORTH);
f1.add (b2, BorderLayout.EAST);
f1.add (b3, BorderLayout.WEST);
f1.add (b4, BorderLayout.SOUTH);
f1.add (b5);
f1.setVisible (true);
}
}
2. Flow Layout :
This layout will display the components from left to right, from top to bottom.
The components will always be displayed in the first line and if the first line is
filled, these components are displayed on the next line automatically.
In this Layout Manager, initially, the container assumes 1 row and 1 column of
the window. Depending on the number of components and size of the window,
the number of rows and columns count is decided dynamically.
Example :
import java.awt.*;
import javax.swing.*;
public class FlowLayoutDemo
{
JFrame f;
FlowLayoutDemo ()
{
f = new JFrame ();
JLabel l1 = new JLabel ("Enter Name");
JTextField tf1 = new JTextField (10);
JButton b1 = new JButton ("SUBMIT");
f .add (l1);
f.add (tf1);
f.add (b1);
f.setLayout (new FlowLayout (FlowLayout.RIGHT));
f.setSize (300, 300);
f.setVisible (true);
}
public static void main (String[]args)
{
new FlowLayoutDemo ();
}
}
b) Design GUI for factorial application and display factorial of given
number.
Ans :-
import javax.swing.JOptionPane;
public class mainclass
{
public static void main(String[] args)
{
String number;
int result,inputNumber;
number = JOptionPane.showInputDialog("enter a number");
inputNumber = Integer.parseInt(number);
result = computeFactorial(inputNumber);
JOptionPane.showMessageDialog(null, "the factorial is :" + result);
}
public static int computeFactorial(int n)
{
int i;
int result = 1;
for (i = 1; i <= n; i++)
{
result = result * i;
}
return result;
}
}
Q.3
a) What is the role of stub and skeleton in RMI? What are the steps to
implement RMI application ?
Ans :-
Stub :
The stub is an object, acting on the client side as a gateway. It routes all the
outgoing applications. It lies on the side of the client and represents the object
remote. When calling technique on the stub item, the caller performs the
following duties :
The skeleton is an object that acts as a gateway to the side object of the server.
It routes all incoming requests through it. When the incoming request is received
by the skeleton, the following tasks are performed:
The next step is to implement the remote interface. To execute the remote
interface, the class should extend to the UnicastRemoteObject class java.rmi
package. In addition, a default constructor must be formed to transfer the
java.rmi.RemoteException from its class parent constructor.
The rmic instrument is used to invoke the rmi compiler which produces the Stub
and Skeleton items. His prototype is the rmic class's name. For the above
program, the following command must be executed at the rmicSearchQuery
command prompt.
Start the service of the registry by putting the following command on the prompt
of start rmiregistry.
The next step is the development and execution on a separate command prompt
of the server application program.
The server program uses the creation technique of the LocateRegistry
class to produce rmiregistry with the passed port number as the argument
within the JVM server.
The Naming class rebind method is used to bind the remote object to the
new name.
6. Write and execute the client application program :
The last stage is to generate and implement the client application program on a
distinct command prompt. The Naming class lookup method is used to get the
Stub object reference.
Ans :-
Chatserver.java :
import java.net.*;
import java.io.*;
public class chatserver
{
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(2000);
Socket sk=ss.accept();
BufferedReader cin=new BufferedReader(new
InputStreamReader(sk.getInputStream()));
PrintStream cout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new
InputStreamReader(System.in));
String s;
while ( true )
{
s=cin.readLine();
if (s.equalsIgnoreCase("END"))
{
cout.println("BYE");
break;
}
System.out.print("Client : "+s+"\n");
System.out.print("Server : ");
s=stdin.readLine();
cout.println(s);
}
ss.close();
sk.close();
cin.close();
cout.close();
stdin.close();
}
}
Chatclient.java :
import java.net.*;
import java.io.*;
public class chatclient
{
public static void main(String args[]) throws Exception
{
Socket sk=new Socket("127.0.0.1",2000);
BufferedReader sin=new BufferedReader(new
InputStreamReader(sk.getInputStream()));
PrintStream sout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new
InputStreamReader(System.in));
String s;
while ( true )
{
System.out.print("Client : ");
s=stdin.readLine();
sout.println(s);
s=sin.readLine();
System.out.print("Server : "+s+"\n");
if ( s.equalsIgnoreCase("BYE") ) break;
}
sk.close();
sin.close();
sout.close();
stdin.close();
}
}
Q.4
a) Explain property change event with an example.
Normally PropertyChangeEvents are accompanied by the name and the old and
new value of the changed property. If the new value is a primitive type (such as
int or boolean) it must be wrapped as the corresponding java.lang.* Object type
(such as Integer or Boolean).
Null values may be provided for the old and the new values if their true values
are not known.
An event source may send a null object as the name to indicate that an arbitrary
set of if its properties have changed. In this case the old and new values should
also be null.
Example :
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
{
private StringProperty name = new SimpleStringProperty();
public Person(String name)
{
this.name.set(name);
this.name.addListener((observable, oldValue, newValue) ->
{
System.out.println("Name changed from " + oldValue + " to " +
newValue);
});
}
public String getName()
{
return name.get();
}
public void setName(String name)
{
this.name.set(name);
}
public StringProperty nameProperty()
{
return name;
}
public static void main(String[] args)
{
Person person = new Person("John");
person.setName("Jane");
}
}
Q.5
a) Write a code to design login form (user name and password) and also
check valid user.
Ans :-
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginFrame extends JFrame implements ActionListener
{
Container container = getContentPane();
JLabel userLabel = new JLabel("USERNAME");
JLabel passwordLabel = new JLabel("PASSWORD");
JTextField userTextField = new JTextField();
JPasswordField passwordField = new JPasswordField();
JButton loginButton = new JButton("LOGIN");
JButton resetButton = new JButton("RESET");
JCheckBox showPassword = new JCheckBox("Show Password");
LoginFrame()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
}
public void setLayoutManager()
{
container.setLayout(null);
}
public void setLocationAndSize()
{
userLabel.setBounds(50, 150, 100, 30);
passwordLabel.setBounds(50, 220, 100, 30);
userTextField.setBounds(150, 150, 150, 30);
passwordField.setBounds(150, 220, 150, 30);
showPassword.setBounds(150, 250, 150, 30);
loginButton.setBounds(50, 300, 100, 30);
resetButton.setBounds(200, 300, 100, 30);
}
public void addComponentsToContainer()
{
container.add(userLabel);
container.add(passwordLabel);
container.add(userTextField);
container.add(passwordField);
container.add(showPassword);
container.add(loginButton);
container.add(resetButton);
}
public void addActionEvent()
{
loginButton.addActionListener(this);
resetButton.addActionListener(this);
showPassword.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == loginButton)
{
String userText;
String pwdText;
userText = userTextField.getText();
pwdText = passwordField.getText();
if (userText.equalsIgnoreCase("Rajpardeshi") &&
pwdText.equalsIgnoreCase("2231"))
{
JOptionPane.showMessageDialog(this, "Login Successful");
}
Else
{
JOptionPane.showMessageDialog(this, "Invalid Username or
Password");
}
}
if (e.getSource() == resetButton)
{
userTextField.setText("");
passwordField.setText("");
}
if (e.getSource() == showPassword)
{
if (showPassword.isSelected())
{
passwordField.setEchoChar((char) 0);
}
Else
{
passwordField.setEchoChar('*');
}
}
}
}
public class Login
{
public static void main(String[] a)
{
LoginFrame frame = new LoginFrame();
frame.setTitle("Login Form");
frame.setVisible(true);
frame.setBounds(10, 10, 370, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
}
}
Ans :- JList A component that displays a list of objects and allows the user to
select one or more items. A separate model, ListModel , maintains the contents
of the list. A ListModel can be supplied directly to a JList by way of a constructor
or the setModel method.
The object of JList class represents a list of text items. The list of text items can
be set up so that the user can choose either one item or multiple items. It
inherits JComponent class.
JList( ) : This Constructor in the JList class will create a List with a read-
only, empty, model.
JList( Array[ ] list data ) : This Constructor in the JList class will create
a list that will display the elements from the array specified within the
parameter.
JList( ListModel<Array> data model ) : This Constructor in the JList
class will create a list that will display the elements from the specified, no-
null, model.
JList( Vector <?> list data ) : This Constructor in the JList class will
create a list that will display the elements from the vector specified within
the parameter.
Example :
import javax.swing.*;
public class ListExample
{
ListExample()
{
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}
Ans :- The JSP engine compiles the servlet into an executable class and
forwards the original request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML format.
The session bean performs work for its client, shielding the client from
complexity by executing business tasks inside the server.
Because the first software module performs the role of the client, and the
second, the role of the server, this mode is also referred to as client/server
interaction.
Ans :- web. xml defines mappings between URL paths and the servlets that
handle requests with those paths.
The web server uses this configuration to identify the servlet to handle a given
request and call the class method that corresponds to the request method.
Ans :- In JavaServer Pages (JSP), import directives are used to import Java
packages or classes into a JSP page. The import directive is similar to the import
statement in regular Java programming and serves the same purpose.
Q.7
a) Describe servlet life cycle.
Ans :- The web container maintains the life cycle of a servlet instance.
Ans :-
Forward() SendRedirect()
Q.8
a) Explain Custom tags of JSP.
Ans :- Custom tags are user-defined action tags that can be used within Java
Server Pages. A tag handler is associated with each tag to implement the
operations.
Therefore, it separates the business logic from JSP and helps avoid the use of
scriptlet tags.
The scriptlet tag embeds java code inside the JSP page itself rendering the page
difficult to understand therefore, it is better to avoid the use of scriptlet.
Syntax to use custom tag :
There are two ways to use the custom tag. They are given below:
1. Tag Handler :
It is a file saved with a .tld extension that contains a set of related tags mapped
to their respective tag handlers along with their description such as the name of
the tag, attributes of the tag, etc. The root tag of the TLD document is <taglib>
in which multiple tags can be encapsulated using <tag> tag. It is stored inside
the WEB-INF folder.
3. Taglib Directive :
Taglib directive is used to access a particular tag library within a JSP. It specifies
the URI of the tag library and its prefix.
Syntax:
b) How to create session in JSP? How to access it? Write a sample code.
For all these purposes, the JSP provides the "session implicit object". In this
chapter, you will learn about various methods and concepts used to create and
manage a session using JSP.
A session can be defined as an object associated with each user with a unique
session ID, and the user's data is based on the account they have registered.
Different forms of data can be set in a session;
These data related to each user of the site help the user and the website owner
in different ways. As you know, HTTP is a "stateless" protocol; Whenever a user
visits a web page, the user opens a separate connection with the webserver, and
the server does not keep a record of preceding client requests.
1. Creating a Session :
Implicitly : A session is created automatically when a user accesses a
JSP page for the first time.
Explicitly : Use the HttpSession object in a servlet or JSP page :
HttpSession session = request.getSession();
Q.9
a) Design a login form. Write a servlet to retrieve form values an display
whether user is valid or not.
Ans :-
b) Explain request and response implicit objects of JSP with any its two
methods.
Ans :-
Request :
o The request object is an instance of java.servlet.http.HttpServletRequest
and it is one of the argument of service method.
o It will be created by container for every request.
o It will be used to request the information like parameter, header
information , server name, etc.
o It uses getParameter() to access the request parameter.
o The request object provides methods to get the HTTP header information
including form data, cookies, HTTP methods etc.
o We can cover a complete set of methods associated with the request
object in a subsequent chapter − JSP - Client Request.
Commonly used methods :
o getParameter(String name) : Retrieves the value of a form parameter
or query string parameter.
Example: String userName = request.getParameter("username");
o getHeader(String name) : Retrieves the value of an HTTP header.
Example: String userAgent = request.getHeader("User-Agent");
Response :
o “Response” is an instance of class which implements HttpServletResponse
interface.
o Container generates this object and passes to _jspservice() method as
parameter.
o “Response object” will be created by the container for each request.
o It represents the response that can be given to the client.
o The response implicit object is used to content type, add cookie and
redirect to response page.
o The response object also defines the interfaces that deal with creating
new HTTP headers. Through this object the JSP programmer can add new
cookies or date stamps, HTTP status codes, etc.
o We will cover a complete set of methods associated with the response
object in a subsequent chapter − JSP - Server Response.
Q.10
a) Explain the life cycle of enterprise bean.
Ans :-
The Life Cycles of Enterprise Beans : An enterprise bean goes through
various stages during its lifetime, or life cycle. Each type of enterprise
bean--session, entity, or message-driven--has a different life cycle.
The stages that a session bean passes through during its lifetime. The client
initiates the life cycle by invoking the create method. The EJB container
instantiates the bean and then invokes.
The setSessionContext and ejbCreate methods in the session bean. The bean is
now ready to have its business methods invoked.
2. The Life Cycle of an Entity Bean :
The stages that an entity bean passes through during its lifetime. After the EJB
container creates the instance, it calls the setEntityContext method of the entity
bean class. The setEntityContext method passes the entity context to the bean.
After instantiation, the entity bean moves to a pool of available instances. While
in the pooled stage, the instance is not associated with any particular EJB object
identity. All instances in the pool are identical. The EJB container assigns an
identity to an instance when moving it to the ready stage.
At the end of the life cycle, the container calls the ejbRemove method. The
bean's instance is then ready for garbage collection.
b) Explain message driven beans.
Ans :-
A message driven bean (MDB) is a bean that contains business logic. But, it is
invoked by passing the message. So, it is like JMS Receiver.
A message driven bean receives message from queue or topic, so you must have
the knowledge of JMS API.
The messages can be sent by any Java EE component (an application client,
another enterprise bean, or a web component) or by a JMS application or system
that does not use Java EE technology. Message-driven beans can process JMS
messages or other kinds of messages.
In eclipse ide, create EJB Project then create a class as given below:
package com.javatpoint;
import javax.ejb.MessageDriven;
import javax.jms.*;
@MessageDriven(mappedName="myTopic")
public class MyListener implements MessageListener{
@Override
public void onMessage(Message msg) {
TextMessage m=(TextMessage)msg;
try{
System.out.println("message received: "+m.getText());
}catch(Exception e){System.out.println(e);}
}
}