AJAVA Question With Answer
AJAVA Question With Answer
UNIT-1
1) Explain Life cycle of APPLET
Ans:
Every java applet inherits a set of default behaviours from the Applet class.so when an
applet is loaded ,it undergoes a series of changes in its state.
The applet states are:
1. Born or Initialization state
2. Running state
3. Idle state
4. Dead or destroyed state
1) Initialization state(Born)
Applet enters the initialization state when it is first loaded.this is achieved by calling the init()
method of Applet class.The applet is born.
Initialization occurs only once in the applet’s life cycle.
To provide any of behaviour mentioned above,we must overrride init() method:
public void init()
{
............(Action)
............
}
2) Running state
Applet enters the running state when the system calls start() method of Applet class.This
occurs automatically after applet is initialized.
Unlike init() method,the start() method may be called more than once.
We may override the start() method to create a thread to control the applet.
public void start( )
{
............(Action)
............
Computer Department, VPMP POLYTECHNIC 1
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
HEIGHT = Pixels
[ALIGN= Alignment]
[VSPACE = Pixels]
[HSPACE = Pixles]
[<PARAM NAME=name1 VALUE= value1 >]
[<PARAM NAME=name2 VALUE= value2 >]
..............
</APPLET>
NO Attribute Meaning
CODE=AppletfileName.class Specifies the name of the applet class to be
1 (necessary) loaded.
CODEBASE= codebase_URL Specifies URL of the directory in which the
2 (Optional) applet resides.(must used in remote applet)
WIDTH = Pixels Specify width and height of the space on the
3 HEIGHT = Pixels(necessary) HTML page that will be reserved for applet.
Name = applet_instance_name A name for the other applet on the page may
4 (Optional) refer to this applet.
[ ALIGN= Alignment] Alignment of applet on page.
5
(Optional)
[ VSPACE = Pixels ] It specifies amount of vertical blank space the
6
(Optional) browser should leave surrounding the applet.
[ HSPACE = Pixels] It specifies amount of horizontal blank space the
7
(Optional) browser should leave surrounding the applet.
[ALT = Alternate_text ] Non _java browser will display this text where
8
(Optional) the applet would normally go.
We can define init() method in applet to get hold of the parametes defined in
<PARAM> tags.
getParameter() method ,takes one string argument representing the name of program.
Each <PARAM...> tag has a name attribue and value attribute .
Syntax:
<APPLET ......>
<PARAMname=color value=“red”>
<PARAMname=text value=“I like java!”>
</APPLET>
Example:
import java.applet.*;
import java.awt.*;
/*
<applet code=ParamTest.class width=500 height=300>
<param Name="Author" value="Balaguru swami">
</applet>
*/
import java.awt.*;
import java.applet.*;
/*<applet code=Hello.class width=400 heigth=400>
</applet>*/
public class Hello extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.pink);
g.drawString( “Hello java” ,10,100);
}
}
import java.awt.*;
import java.applet.*;
/*<applet code=Hello.class width=400 heigth=400>
</applet>*/
public class Hello extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.pink);
g.drawString( “Hello java” ,10,100);
}
}
No Methods Action
UNIT-2
1) What is Swing? Explain the need of swing.
Ans:
Swing is a part of the java foundation classes.
It is an extension library to AWT.
Swing is a set of classes that provide more powerful and flexible components than
AWT
Need of Swing
The uniform look and feel across platform is an advantage of swing
Swing is light weight components.
Swing is compatible for standalone/GUI applications, Applets and servlets.
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=FrameDemo1.class width=250 height=150></applet>*/
public class FrameDemo1 extends Applet
{ Frame f;
Button b1;
public void init()
{ f=new Frame("Frame Window");
b1=new Button("Show Window");
add(b1);
}
Computer Department, VPMP POLYTECHNIC 8
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
Before
After
Canvas();
Canvas(graphics configuration config);
Methods:
GetAccessibleContext();
getBufferStrartegy();
paint(Graphics g);
update(Graphics g);
createBufferStrategy(int num Buffers);
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=CanvasDemo.class width=250 height=150></applet>*/
public class CanvasDemo extends Applet
{ Canvas c;
public void init()
{
c=new Canvas();
c.setBackground(Color.pink);
c.setSize(50,90);
add(c);}}
Output:
Listeners: It is an object that the listener to the event. Once the event is received by the
listener can the process of event and then returns it.
8) List layouts manager, classes in java. Explain any one with example.
Ans:
public void setMnemonic(int a): is used to set the mnemonic on the button.
public void addActionListener(ActionListener a): is used to add the action
listenerto this object.
Constructor for JButton:
JButton(Icon i)
JButton(String s)
JButton(String s,Icon i) //s and i are the string and icon used for the button.
Example:
import java.awt.*;
import javax.swing.*;
public class JButtonDemo extends JFrame
{
JButtonDemo(String title)
{
super(title);
setLayout(new GridLayout(3,2));
Icon plus= new ImageIcon("plus.png");
JButton b1=new JButton("ADD",plus);
JButton b2=new JButton("OK");
add(b1);
add(b2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
JButtonDemo t=new JButtonDemo("JButton Demo");
t.setSize(300,100);
t.setVisible(true);
}}
CheckboxGroup () method.
Checkbox is use for multiple selection RadioButton is use for single selection.
Syntax:- Syntax:-
Checkbox ch1=new checkbox(“pen”); CheckboxGroup ch=new CheckboxGroup();
Add(ch1); Checkbox ch1=new checkbox(“female”);
Ch1.setcheckboxgroup(ch1);
Ch1.setstate(false);
Add(ch1);
MouseEvent Description
Method
getClickCount() It can return number of times the mouse was clicked.
getPoint() It can return a point of object is an AWT class that can represents
the X and Y co-ordinates.
getX() It can return the X co-ordinates of the point at which the event
can occur.
getY() It can return the Y co-ordinates of the point at which the event
can occur.
EXAMPLE: -
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code= Mousedemo.class Width=500 Height=500>
</applet>*/
Public class Mousedemo extends Applet implement MouseListener
{
String message;
Computer Department, VPMP POLYTECHNIC 14
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
Method Description
Public void KeyTyped Invoked when a key has been typed
(KeyEvent e) (pressed and released).
Public void KeyPressed Invoked when a key has been pressed.
(KeyEvent e)
Public void KeyReleased Invoked when a key has been released.
(KeyEvent e)
EXAMPLE: -
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code= Keydemo.class Width=500 Height=500>
</applet>*/
Public class Keydemo extends Applet implement KeyListener
{
TextArea t1;
Public void init()
{
addKeyListener(this);
}
Public void KeyPressed(KeyEvent e)
{
showStatus(“Key is pressed”);
}
Public void KeyReleased(KeyEvent e)
{
showStatus(“Key is Released”);
}
Public void KeyTyped(KeyEvent e)
{
showStatus(“Key is Typed”);
}}
1) Component
Component class is derived from object class.
It is the super class for all AWT components class such as Label, TextComponent,
RadioButton, and CheckBox etc.
2) Container
Container class is derived from component class.
The Container is a component in AWT that can contain another component like
buttons, textfields, labels etc. The class that extends Container class is known as
container such as Frame, Dialog and Panel.
3) Windows
Windows class is derived from container class.
The window is the containers that have no borders and menu bars. You must use frame,
dialog or another window for creating a window.
4) Panel
{
String s = "This is a very long label";
Label l1 = new Label(s, Label. LEFT);
add (l1);
Label l2 = new Label(s, Label. CENTER);
add (l2);
Label l3 = new Label(s, Label. RIGHT);
add (l3);
}}
18) Explain border layout, flow layout, grid layout with example.
Ans:
Flow Layout (default Layout): see above Question-answer.
Grid Layout:
The Grid layout class puts each component into a place on a grid that is equal in size to all
the other places.
The grid is given specific dimensions when created; Components are added to the grid in
order, starting with upper-left corner to right.
Components are given equal amounts of space in the container.
Grid layout is widely used for arranging components in rows and columns.
Computer Department, VPMP POLYTECHNIC 18
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
However unlike, Flow Layout, here underlying components are resized to fill the row-
column area. if possible.
Grid Layout can reposition objects after adding or removing components. Whenever area is
resized, components are also resized.
GridLayout b1=new GridLayout (2, 3); // 4 rows and 1 column
SetLayout (b1)
Border Layout
Border layout is the default layout manager for all window, dialog and frame class.
In Border layout, components are added to the edges of the container, the center area is
allotted all the space that’s left over.
Border layout ,provides five areas to hold component:
Four border north, south, east, and west
Remaining space: center
When you add a component to the layout you must
Specify which area to place it in.
Java event handling mechanism is represented by event classes.At the root of the java
event class hierarchy is EventObject.
EventObject (Object src)-src are the object that generates event.
Method Description
WindowActivated Invoked when a window is activated.
(WindowEvent e)
WindowClosed Invoked when a window has been closed.
(WindowEvent e)
WindowClosing Invoked when a window is in the process of being
(WindowEvent e) closed.
WindowOpened (WindowEvent e) Invoked when a window has been opened.
WindowDeactivated(WindowEvent e) Invoked when a window is deactivated.
EXAMPLE:
import java.awt.*;
import java.awt.event.*;
public class windowprogram extends Frame implements WindowListener
{
TextArea t1;
Public windowprogram()
{
addWindowListener(this);
setTitle(“Windowed Program”);
setSize(400,400);
setVisible(true);
t1=new TextArea(5,50);
add(t1);
}
public void WindowClosing(WindowEvent e)
{
setVisible(false);
System.exit(0);
}
Public void WindowOpened(WindowEvent e)
{
t1.append Text(“window is opened”);
}
Public void WindowClosed(WindowEvent e)
{
t1.append Text(“window is closed”);
}
Public static void main(String[] args)
{
New windowprogram();
}}
UNIT-3
1) Which package is used to perform almost all JDBC operations?
Ans: Java.sql package is used to perform almost all JDBC operations.
2) List JDBC API components. Explain in brief.
Ans:
JDBC has four Components:
1. The JDBC API.
2. The JDBC Driver Manager.
3. The JDBC Test Suite.
4. The JDBC-ODBC Bridge.
1. JDBC API
JDBC API (application programming interface) is a part of the Java platform that
have included in Java Standard Edition (Java SE) and the Java Enterprise Edition
(Java EE) in itself.
The latest version of JDBC 4.0 application programming interface is divided into
two packages
java.sql
javax.sql.
These packages contain all the APIs which provide programmatic access to a
relational database (like oracle, SQL server, MySQL etc.)
Using it, front end java applications can execute query and fetch data.
2 JDBC Driver Managers
This interface manages a list of database drivers. Matches connection requests from
the java application with the proper database driver using communication sub
protocol.
The first driver that recognizes a certain sub protocol under JDBC will be used to
establish a database Connection.
Internally, JDBC Driver Manager is a class in JDBC API. The objects of this class
can connect Java applications to a JDBC driver.
Driver Manager is the very important part of the JDBC architecture. The main
responsibility of JDBC Driver Manager is to load all the drivers found in the system
properly.
The Driver Manager also helps to select the most appropriate driver from the
previously loaded drivers when a new open database is connected.
3 JDBC Test Suite
The function of JDBC driver test suite is to make ensure that the JDBC drivers will
run user's program or not.
The test suite of JDBC application program interface is very useful for testing a
driver based on JDBC technology during testing period.
It is used to check compatibility of JDBC driver with (J2EE)Java Platform
Enterprise Edition.
4 JDBC-ODBC Bridge
The JDBC-ODBC Bridge, also known as JDBC type 1 driver is a database driver
that utilizes the ODBC driver to connect the database.
Computer Department, VPMP POLYTECHNIC 23
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
This driver translates JDBC method calls into ODBC function calls. The Bridge
implements JDBC for any database for which an ODBC driver is available. The
Bridge is always implemented as the sun.jdbc.odbc
Java package and it contains a native library used to access ODBC.
ODBC driver is already installed or come as default driver in windows.
4) List JDBC driver .explain JDBC .NET pure java driver (Type -3).
Ans:
5) Whatis a JDBC connection? Explain steps to get database connection using java program.
Ans:
A Connection is the session between java application and database.
The Connection interface is a factory of Statement, PreparedStatement, and
DatabaseMetaData i.e. object of Connection can be used to get the object of
Statement and DatabaseMetaData.
The Connection interface provide many methods for transaction management like
commit(),rollback() etc
Steps to get Database connection
1. Register the driver class
Computer Department, VPMP POLYTECHNIC 25
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
7) Develop a JDBC application that uses any JDBC drivers to display all records.
Ans:
Import java.sql.*;
public class selectdata
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection ("jdbc: mysql://localhost:3306/mydb","root", "");
Statement stmt=cn.createStatement ();
System.out.println (“Table data :”);
ResultSet rs=stmt.executeQuery ("select distinct * from stud");
While (rs.next ())
{
System.out.println (rs.getInt ("id") + "\t");
System.out.println (rs.getString ("name") +"\n");
}
}
Catch (Exception e)
{
System.out.println (e);
}
}
}
Output:
Computer Department, VPMP POLYTECHNIC 26
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
Table data:
1 Sita
8) Develop a JDBC application that uses any JDBC drivers to deletea record.
Ans:
import java.sql.*;
public class del { public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection ("jdbc: mysql://localhost:3306/mydb","root","");
Statement stmt=cn.createStatement();
String sql = "delete from stud “+ "where id=2";
stmt.execute(sql);
System.out.println ("Row is deleted");
}
Catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Row is deleted
1 Rita
9) Develop a JDBC application that uses any JDBC drivers to insert a record.
Ans:
import java.sql.*;
public class insert
{
public static void main (Stringargs [])
{
Try
{
Class.forName ("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection ("jdbc: mysql: //localhost:3306/mydb","root","");
Statement stmt=cn.createStatement ();
String sql = "INSERT INTO student VALUES (1, 'Rita') ";
stmt.execute (sql);
String sql = "INSERT INTO student VALUES (2, 'Ram') ";
stmt.execute (sql);
System.out.println (“Row is inserted");
ResultSet rs=stmt.executeQuery ("select DISTINCT * from stud ");
While (rs.next ())
{
Computer Department, VPMP POLYTECHNIC 27
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
Ans:
Advantages:
1. Can read any database if proper derivers are installed.
2. Creates XML structure of data from database automatically.
3. No content conversion required.
4. Query and stored procedure supported.
5. Supports modules.
Disadvantages:
1. JDBC is not good if used in large project.
2. It is not at all good in the transaction management.
3. JDBC needs database specific queries.
4. JDBC cannot maintain the database independent SQL statement.
5. When multiple connection are created and closed affects the performance.
6. Exception handling is one of the main drawbacks in JDBC.
The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers
connected to multiple databases.
In the three-tier model, commands are sent to a "middle tier" of services, which then
sends the commands to the data source.
The data source processes the commands and sends the results back to the middle
tier, which then sends them to the user.
MIS (management information system) directors find the three-tier model very
attractive because the middle tier makes it possible to maintain control over access
and the kinds of updates that can be made to corporate data.
Another advantage is that it simplifies the deployment of applications. Finally, in
many cases, the three-tier architecture can provide performance advantages.