Advance Java
Advance Java
Only shows u the selected item U can view all the item whether it is selected
or deselected.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Q20. Illustrate how components and containers are assembled into applets and applications.
Ans. Components are added to containers and then container can be added to the applet or
application.
E.g.
TextField t=new TextField();
Button b=new Button(“click me”);
Panel p=new Panel();
p.add(t);
p.add(b);
add(p)
Q21. Explain which classes and interfaces support layouts and event handling.
Ans. All LayoutManager classes provides the different layout to arrange component in the
container. These classes are FlowLayout, GridLayout, BorderLayout, CardLayout
Event handling is provided by different event classes to handle these events. Java also
provides interfaces and support event delegation model. These classes and interfaces are
Classes
ActionEvent, MouseEvent, AdjustmentEvent, KeyEvent , FocusEvent, ItemEvent etc.
Interfaces
ActionListener, MouseMotionListener, MouseListener, AdjustmentListener, KeyListener,
FocusListener, ItemListener etc.
Q22. Describe how layout managers simplify the process of organizing GUI components.
Ans. Layout managers provided by the java helps to organize the components on container.
Different types of Layout managers provide different types of layout to place the components.
User can choose according his requirement.
Q23. Why can’t my applet connect via sockets, or bind to a local port and what are socket
option, and why should I use them?
Ans. Applets are the small program executed on client machine by the server. But these are not
connected with the socket because applet is more secure program provided by java. Once it
launch from the server machine to client no transaction is possible from server to client. No
additional information we can send. So we cannot attach Socket to the applet.
Applets are used for secure, small animation or dynamic messages on the web page.
Q24. Define Panel.
Ans. The Panel class is a concrete sub class of container. It doesn’t add any new methods; It simply
implements Container. A Panel may be thought of as a recursively nestable, concrete screen
component. It is super class of Applet. It is a window that does not contain a title bar, menu
bar , or border.
Q25. What is Frame?
Ans. It is a sub class of Window and has a title bar, menu bar, and border and resizing corners.
When we create a Frame object within an Applet a warning message appears, commonly
Frames are used to implement Application programming using awt controls.
Q26. What are Dialog Boxes?
Ans. A Dialog box is used to hold a set of related controls. Dialog boxes are primarily used to
obtain user input. They are similar to frame window, except that dialog boxes are always
child windows of a top-level window.
Q27. What is File Dialog?
Ans. Java provides a built in dialog box that lets the user specify a file this is called FileDialog
box.. To create Filedialog box, instantiate an object of type FileDialog. This causes the File
dialog to be displayed.
Q28. How an Image can be loaded on the Applet window?
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Ans. To load the Image on the Applet window the getImage method is defined by the applet class.
It has the following forms.
Image getImage(URL url);
Image getImage(URL url, String imageName)
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Q1. How does applets differ from application program? Why do applet class need to be
declared as public? Write the applet tag with arguments.
Ans.
Applet Application
1. Applet executes on web browser 1. Executes on Command prompt
2. No need of main function to 2. Every application program need to
execute. define main () function in the program
3. No command line argument is 3. We can pass command line arguments
passed. in an application
4. A fast and small program executed 4. Program those does not support web
on the internet. browsers
Applet class need to declare public because applets are launched by the applet tag and that tag
can be defined within the same program and in different .html files. It is declared public
because it can be called outside the package in which it is declared.
<applet code=abc.class height=200 width=200>
<param name=”name” value=”raj”>
<param name=”rollno” value=1>
<param name=”class” value=12>
</applet>
Q2. Write an applet that takes an integer and reverse that egg. 756 to 657.
Ans.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class app1 extends Applet implements ActionListener
{
/*<applet code=app1 height=200 width=200></applet> */
TextField t,t1;
Label l,r;
Button b;
public void init()
{
l=new Label("Enter no");
r=new Label("Result");
t=new TextField(10);
t1=new TextField(10);
b=new Button("click");
add(l);
add(t);
add(r);
add(t1);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent g)
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
{
String s=t.getText();
int i=Integer.parseInt(s);
int r1=0;
while(i>0)
{
r1=r1*10+i%10;
i/=10;
}
t1.setText(" "+r1);
}
}
Q3. Write a Java program to create a Fibonacci series.
Ans.
class feb
{
public static void main(String ap[])
{
int a=1,b=0,c=0;
while(c<=21)
{
System.out.println(c);
c=a+b;
a=b;
b=c;
}.
}
Q4. What do you mean by Layout Manager? What are the various types of Layout?
Ans. A layout refers to arranging and placing of the component in a container. A Layout manager
will determines how components will be arranged when they are added to a container.
Types of Layout
1. FlowLayout: - The default layout of the container. The FlowLayout class is the simplest of
layout manager. It layouts the components in similar way as Word place data in there pages.
It provides the following constructor
FlowLayout(), FlowLayout(FlowLayout.LEFT);
2. GridLayout: - The GridLayout manager arranges components into a grid of rows and
columns. Components are added first to the top row of the grid.
The following constructor are provided by GridLayout
GridLayout(),GridLayout(row,col), GridLayout(row,col,hrz,vert);
3. BorderLayout: - Divide the container into five different section these sections are .
SOUTH, EAST, WEST, NORTH, CENTER.
Provide two constructors
BorderLayout()
BorderLayout(int,int);
4. CardLayout: - In CardLayout the components are arranged in the card style and some of
the components can be hidden or viewed using this layout. In this layout other layout can be
mixed to manage different container components inside the main container.
Q5. Write an application/applet to implement the binary search technique.
Ans. class xyz
{
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
if(f==1)
System.out.println(mid);
else
System.out.println("no match found");
}
}
Q6. Write an applet, which takes the input, and compute the factorial.
Ans.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class fact1 extends Applet implements ActionListener
{
/*<applet code=fact1 height=200 width=300></applet> */
Label l,l1;
TextField t,t1;
Button b;
public void init()
{
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
{
int x[] = {10,100,150,50};
int y[] = {10,10,100,100};
g.drawPolygon (x,y,z);
}
}
Q12. What is Event Handling?
Ans. Almost all programs must respond to commands from the user in order to be useful. Java's
AWT uses event driven programming to achieve processing of user actions: once that
underlies all modern window systems programming. Within the AWT, all user actions belong
to an abstract set of things called events. An event describes, in sufficient detail, a particular
user action. Rather than the program actively collecting user-generated events, the Java run
time notifies the program when an event occurs. Programs that handles user interaction in this
fashion are said to be event driven.
There are three parts to the event model in Java:
Event object - this is an instance of a Java class that contains the characteristics of the event.
For example, if the event is generated from clicking a mouse button, the event object would
contain information such as the coordinates of the mouse cursor, which button was clicked,
how many times it was clicked, etc.
Dispatching class/method - this is an object, which detects that an event has occurred and is
then responsible for notifying other objects of the event, passing the appropriate event object
to those objects. These other objects are "listeners" for the event. Most AWT components,
such as Button, List, TextField, etc. are examples of dispatching classes.
A Button, for instance, is capable of notifying other components when it is "pushed." These
classes will typically have a set of two methods that can be invoked by would-be "listeners":
one to tell the class that the object wants to listen and another to tell the class that the object
no longer wants to listen.
These methods are conventionally named i.e. addxxListener (to add an object as a listener) or
removexxListener (to remove the object as a listener). Here ‘xx’ is the specific type of event
to listen for. In the case of the Button, this would be "Action" to indicate the action of pushing
the button. (So the methods would be addActionListener and removeActionListener).
Listener Interface - for the dispatching to work properly, the dispatching class must be able
to rely on each of its listeners to contain the method that it executes when the event occurs.
This is easily accomplished in Java through the use of an Interface class. The important point
is that a class, which is going to be a listener, must implement that interface.
Q13. What advantages do java’s Layout Managers provides over traditional windowing
system?
Ans. Layout Mangers in java provides us the way to arrange components in windows programming
or applet programming. There are different types of layout Manager provided by java using
java.awt package.
1. Flow Layout
2. BorderLayout.
3. GridLayout.
4. Cardlayout.
Layout Manager helps us to place the components on the container, as we want to place.
Every layout provides different types of style, to place the components and make easy to
arrange component on traditional windowing system.
• Flow layout is the default layout Manager for java window application.
• Using layout managers we can align components to left and right.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
• Using Layout Manager we can place different component in different position like center,
left, top, right and bottom. For this we can use, BorderLayout.
• Required components can be hidden using CardLayout.
• Components can be arranged in tabular form using GridLayout.
Q14. Describe how layout managers simplify the process of organizing GUI components.
Ans. A layout refers to arranging and placing of the components in a container, much like
arranging the furniture in a house. To design a user interface, a programmer has to specify
row, column, position of all the objects used in the interface. Based on this input the
programming environment will create the user interface and display it on screen.
A Layout Manager determines how components will be arranged when they are added to a
container. Different types of LayoutManager provide different type of Layout setting. These
are of followings.
1. FlowLayout: - FlowLayout Manager, which is the default Layout for applet window, place
the components on the window as they are added on the window. We specify the alignment of
these components as left, right or center.
2. GridLayout: - GridLayout Manager divide the whole area of the window into rows and
columns to display the components in matrix form with specified space distance the
components.
3. BorderLayout: - Divide the whole window into different border like North, East, South ,
West and Center. The specified is displayed on the specified area.
4. CardLayout: - To view the specified component on the top of the other components.
Q15. Explain how listeners and adapters are used to implement the event-delegation model.
Ans. Listener: -A Listener object can listen object and passing the event object to the method as an
argument. A Listener object can listen for events for a particular object. Just a single button
for instance, Or it can listen for several different objects. This mechanism for handling events
using listeners is very flexible, and very efficient, particularly for GUI events. Any number
of listeners can receive a particular event. However, a particular event is only passed to the
listener that have registered to receive it, so interested parties are involved in responding to
each event. This is the way in which events are handled in java, using listener objects and it
provides event delegation model.
Adapter classes: - Java provides a special feature called an adapter class that can simplify the
creation of event handlers in certain situations. An adapter class provides an empty
implementation of all methods in an event listener interface. Adapter classes are useful when
you want to receive and process only some of the events that are handled by a particular event
listener interface. You can define a new class to act as an event listener by extending one of
the adapter classes and implementing only those events in which you are interested. Which
helps you implements partial listener interface in this way adapter classes provides event
delegation model to delegate the listener object.
Q16. Illustrate how components and containers are assembled into applets and applications.
Ans. Panel class, which is the sub class of container, a window that does not contain a title bar,
menu bar, or border. Can contain different components those are assembled on applet
window.
Following example will show you how component and container are assembled on the applet
window.
In this example there are two text fields and button placed on the panel and panel is added on
applet window.
import java.awt.*;
import java.applet.*;
public class myapp extends Applet
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
{
TextField t,t1;
Button b;
public void init()
{
t=new TextField(10);
t1=new TextField(10);
b=new Button(“ok”);
Panel p=new Panel();
p.add(t);
p.add(t1);
p.add(b);
add(p);
}
}
Q17. Describe how a client applet or application read a file from a server through a URL
connection?
Ans. In java we can create application for web page and application for single Machine. The
application for Web page is created with the help of applet and application using the Java.awt
Frame.
In java we can create two types of applets.
1. Local
2. Remote
Local applet means: - Clients and server program both are on the same machine.
Remote applet means: - Applet is available on the different machine (on the server) and
client requests for that applet from different machine. These diagrams show the local and
Remote applets.
Local Computer
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Internet
Client
Q19. What is advantage of the event delegation model over the earlier event inheritance
model?
Ans. Event delegation is the process to delegate any event to the function means:- events are
handled using different function defined in a listener.
There are numbers of benefits of event delegations model.
1. Different events are categories in different listener Interfaces.
2. By delegating the events to the listener interfaces now we can use these events to
window programming classes. Without delegation it is very difficult to extend
multiple classes.
3. By delegating events any member of listener can receive that event.
4. But any event is only passed to the listener that has registered to receive it.
5. We can also restrict the programmers to use all type of methods in a listener.
Q20. Design a java applet that tries to delete a file on the local file system. This program
demonstrates that when the applet tries to delete a file on the local system, it throws on
security exception.
Ans. import java. Applet.*;
import java.awt.*;
import java. awt.event. *;
public class Delfile extends Applet implements Action Listener
{
TextField t;
Button b;
File d; Label l;
public void init ()
{
l= new label (“file deleted”);
t = new TextField (ion);
b= new Button (“Delete”);
add (t);
add (b);
add(i);
b.addActionListener (this);
}
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Ans. Threads are used with applets to develop any animated applet. The following applet will
display the scrolling banner this applet scrolls a message from right to left.
import java.awt.*;
import java.applet.*;
/*<applet code=”SimpleBanner” width=300 height=50>
</applet>*/
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
{
g.drawString(msg,50,50);
}
}
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Ans. sleep() is the static method provided by java Thread class. Used to temporarily suspend a
thread for specified period of time after that the thread will resume again.
Q23. Define Serialization.
Ans. Serialization is the process of writing the state of object to a byte stream. This is useful when
you want to save the state of your program to a persistent storage area, such as file. At a later
time, you may restore these objects by using the process of deserialization.
amount of CPU time that a thread gets often depends on several factors. To set the thread
priority the setPriority() method is used. Three types of levels we can specify as a parameter
in this methods. These levels are 1 MIN_PRIORITY 2. MAX_PRIORITY 3.
NORM_PRIORITY.
Q32. What is use of IsAlive() and join() methods in thread?
Ans. The isAlive() method returns true if the thread upon which it is called is still running
otherwise it return false.
Join() method waits until the thread on which it is called terminates. Its name comes from the
concept of the calling thread waiting until the specified thread joins it.
Q33. What is main thread?
Ans. When a java program starts up ,one thread begins running immediately . this is usually called
the main thread of your program , because it is the one that is executed when your program
begins. It is important for two reasons.
1. It is the thread from which other child threads will be spawned
2. It must be the last thread to finish execution. When the main thread stops, your program
terminates.
Q34. What is thread based multi tasking?
Ans. A Thread based multitasking is the process in which the thread is smallest unit of dispatch
able code. This means that a single program can perform two or more tasks simultaneously.
Using the single process space.
Q35. What is an Exception?
Ans. An exception is an abnormal condition that arises in a code sequence at run time. An
exception is a run-time error. To execute the program successfully in computer languages
these exception must be handled.
Q36. Define Swing?
Ans. Swing is a part of java foundation classes library. It is an extension of the Awt
that has been integrated in Java2. It offers much improved functionality over
awt, like tables, traview, better graphics. Event handling dialog box and drag
and drop support.
Q37. Define JFC?
Ans. JFC stands for java foundation classes. These are introduced by the joint
efforts between Sun Microsystems and Netscape to provide better graphics
supports and expanded component features. Java swing is one of the parts of JFC
contain number of other strings than swing.
1. Cut and paste –clipboard support
2. The desktop color features.
3. java 2d-Improved color, image and text support.
Q38. Define height weight component in swing?
Ans. The component those are not dependable on any native system classes are called
lightweight components. In swings the most of the component have their own view
supported by java look and feels classes.
Q39. Differentiate between Swing and AWT?
Ans. There are number of differences between Swing and AWT:
1. Swing components are absolutely implemented with no native code whereas
AWT components may use native code.
2. Swing button and labels can display images but not the AWT components.
3. Swing button can be round or rectangular but AWT button are only rectangular
buttons.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
{
new mythread();
try
{
for(int I=5;I>0;I--)
{
System.out.println(“main tthread “+I);
Thread.sleep(1000);
}
}catch(Exception e){}
}
}
Thread class
class mythread extends Thread
{
mythread()
{
super(“demo thread”);
System.out.println(“child thread”+this);
start();
}
public void run()
{
try{for(int I>5;I>0;I--)
{
System.out.println(“child thread”+I);
Thread.sleep(1000);
}
catch(Exception e){}
}
}}
class you
{
public static void main(String ap[])
{new mythread();
try{
for(int I=5;I>0;I--)
{
System.out.prntln(“main Thread”+I);
Thread.sleep(1000);
}
}
catch(Exception e){}
}}
Q2. Distinguish between preemptive and non-preemptive scheduling. Which does Java use?
Ans. Preemptive Scheduling: - In preemptive scheduling of threads a higher priority thread will
run when it wants to be run by suspending the running thread. This feature is also called
preemptive multitasking.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Q6. How I/O is accomplished using input stream OutputStream, Reader and Writer classes?
Ans. InputStream is an abstract class that defines java’s model of steaming byte input. all of
methods in this class will throw an IOException or error conditions. It provides different
methods to handle input
Int available(), void close(), void mark(int numBytes), Boolean markSupported(), int read(),
void reset()
OutputStream: - OutputStream is an abstract class that defines streaming byte output. All of
the methods in the class return void value and throw IOException in the case of error.
Methods of OutputStream.
void close(),void flush(),void write(int b).
Reader: - Reader is an abstract class that defines java ‘s model of streaming character input.
All of the methods in this class will throw an IOException on error condition.
abstract void close(),void mark(int numchars), boolean markSupported()
int read(),void reset()
Writer: - Writer is an abstract class that defines streaming character output. All of the
methods in the class return a void value and throw an IOException in the case of errors.
Q7. Define Thread Priority and Synchronization in java.
Ans. Thread Priority: -Java assigns to each thread a priority that determines how that thread
should be treated with respect to the others. Thread priorities are integers that specify the
relative priority of one thread to another. A higher priority thread doesn’t run any faster than a
lower –priority thread .it is used to decide when to switch from one thread to the next. This
process is called context switching.
Synchronization: - Multithreading programming introduces asynchronous behavior means a
thread can be interrupted by the another thread at any time, but some time It will create some
problems e.g. you must prevent one thread from writing data while another thread is in the
middle of reading it. In this situation there is a need of synchronization, which is provided by
monitor. The monitor is the small box can store single thread at a time when a thread enters in
the monitor no other thread can interrupt it until it exits from the monitor. But java has no
monitor class instead each object has its own implicit monitor that is automatically entered
when one of the object’s synchronized methods called once thread is inside a synchronized
method no other thread can call any other synchronized method code.
Q8. Explain Dead Lock in java.
Ans. A special type of error that you need to avoid that relates specifically to multitasking is
deadlock it occurs when two thread have a circular dependency on a pair of synchronized
objects. E.g suppose one thread enter the monitor on object x and another thread enter the
monitor on object y. if x tries to call any other synchronized method on y, it will block as
expected ,the thread wait for ever, because to access X, it would have to release its own lock
on Y so that the first thread could complete. It is difficult to debug for two reasons.
1. It occurs only rarely, when two threads time-slice in just the right way.
2. It may involve more than two threads and two synchronized objects.
Q9. How can you to write data in text files in java?
Ans. To read /write data into the files java provides two classes FileInputStream and
FileOutputStream. In java files are byte oriented and java provides methods to read and write
bytes from and to a file. Java allows you to wrap a byte-oriented file stream within a
character-based object.
FileOutputStream :- which create byte streams linked to files. To open a file you simply
create an object of one of these classes, specifying the name of the file as an agrument to the
constructor.both classes support additonal ,overriden constructors and throws
FileNotFoundException when an output file is opened any pre existing file by the same name
is destroyed. To close the a file call close() method.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
FileInputSteam: - to read data from the file you can use read() method which defined under
a version of read() that is defined within FileInputStream
These methods also generate FileNotFoundException.
To read and write data of specific type in the file there is a need of two more classes
DataOutputStream and DataInputStream ,they create Stream objects to write and read data in
specific type . DataOutputStream provides method for writing like writeInt(),
WriteFloat(),writeDouble etc.
DataInputStream class provides method to read data from the file like
readInt(),readFloat(),readDouble() etc.
Q10. Describe the major features of Java exception handling. How is exception handling
carried out in java? What are the major statements that are employed in java
exeception handling and what do they do?
Ans. An exception is a condition that is caused by a run-time error in the program. When the Java
interpreter encounters an error such as dividing an integer by zero, it creates an exception
object and throws it. The purpose of exception handling mechanism is to provide a means:- to
detect and report an “exceptional circumstance” so that appropriate action can be taken.
Features
1. Structured exception handling
2. Provide security from executing illegal instruction those prone to termination of the
program.
3. Use the concept of object oriented approach to handle exceptions
4. User defined exception can also be handled.
Following are the major statements to handle exceptions
1. Try: - Program statements that you want to monitor for exceptions are contained within a
try block.
2. Catch: - If any exception occurs within the try block, it is thrown. These exceptions are
caught in catch block.
3. Finally: - Finally is the last block that will always execute although exception is raised on
not.
4. Throw: - Use to throw exception manually.
5. Throws: - To explicitly throws the exception.
Q11. What is use of Buffered Reader class? Explain with Example.
Ans. BufferedReader class is one of the class define under the java.io package.
Because System not define any method to take input from the keyboard. Buffered Reader
class provide to read and readLine method read data from the keyword also generate
exception called IOException. read() is used to read a character from keyboard and readLine()
method is used to read a line of character from the keyboard. It can be explain by the
following example.
class my
{
public static void main(Strring ap[]) thrws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a,b,c;
System.out.print(“Enter 1st no”);
a=Integer.parseInt(br.readLine());
System.out.print(“enter 2nd no”);
b=Integer.parseInt(br.readLine());
c=a+b;
System.out.println(“sum is “+c);
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
}
}
in this class file br is BufferedReader object which access the readLine() method to get the
value from keyboard.
Q12. Write a short note of Collection Framework.
Ans. The Java collection framework standardizes the way in which groups of objects are handled
by your programs. Java provides ad hoc classes like Dictionary, Vector, Stack and Properties
to store and manipulate groups of objects.. It was designed to meet several goals. First, the
framework had to be high-performance. Another item created by the collections framework is
the Iterator interface. An Iterator gives you a general-purpose, standardized way of accessing
the elements within a collection one at a time. An iterator provides a means:- of enumerating
the contents of a collection .Because each collection implements Iterator, the elements of any
collection class can be accessed through the methods defined by Iterator.
The framework defines several map interfaces and classes. Maps store key/value pairs
although maps are not “collection” they are fully integrated with the collection view of map.
Q13. In the Java I/O libraries, what is the role of the Reader and Writer classes? What is the
difference between the Reader and Writer classes and the Stream classes?
Ans. In java I/O libraries, the Reader and Writer classes are used to handle character stream.
Character stream are not the part of the java when it was released in 1995. They were added
later when the version1.1 was announced. These classes defined separately as
1. Reader Stream Classes: - Reader stream classes are designed to read character from the
files. Reader class is the base class for all other classes. These classes are functionally
very similar to the input stream classes, except input streams use bytes as their
fundamental unit of information, while reader streams use characters.
2. Writer Stream classes: - The writer stream classes are designed to perform all output
operations on files. Only difference is that while output stream classes are designed to
write bytes, the writer stream classes are designed to write characters.
Q14. What are the basic steps that are required to write data out to the stream? What are the
basic steps that are required to read data from a stream? In your answer, provide
pseudo code or java code.
Ans. The following the java code is used to write data into the file.
1. Create the object of FileOutputStream class e.g.
FileOutputStream f=new FileOutputStream(“c:\myfile.txt”);
2. Create the object of DataOutputStream class to store primitive data and link it with file
using following code.
DataOutputStream d=new DataOutputstream(f);
3. Write different type of data using DataoutputStream object.
d.writeInt(10)’;
d.writeUTF(“Aman”);
d.writeDouble(23.45);
4. Close the DataOutputstream object and file object
d.close();
f.close();
The following steps are used to read data from file.
Create object of FileInputStream to read data from file e.g
FileInputStream f=new FileInputStream(“c:\myfile.txt”);
Create object of DataInputStream to read data of different types e.g.
DataInputStream d=new DataInputStream(f);
Read data and store these into the different variables. e.g.
String n; int c; Double s;
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
while(d.available()>0)
{ n=d.readUTF();
c=d.readInt();
s=d.readDouble();
System.out.println(“Name “+n);
System.out.println(“code “+c);
System.out.println(“salary “+s); }
Close the DatInputStream object and file object e.g
d.close(); f.close();
Q15. Write statement to create a file stream that concatenates two existing files.
Ans. import java.io.*;
class my
{
public static void main(String ap[]) throws IOException
{
FileInputStream file1=null;
FileInputStream fiel2=null;
SequenceInputStream file3=null;
File1=new FileInputStream(“Text1.dat”);
File2=new FileInputStream(“Text2.dat’);
File3=new SequenceInputStream(file1,file2);
BufferedInputStream inBuffer=new BufferedInputStream(file3);
BufferedOutputStream outBuffer=new BufferedOutputStream(System.out);
int ch;
while((ch=inBuffer.read())!=-1)
{
outBuffer.write((char)ch);
}
inBuffer.close();
outBuffer.close();
file1.close();
file2.close();
}
}
Q16. Write a program to count the number of characters in a file.
Ans.
import java.io.*;
class my
{
public static void main(String ap[]) throws IOException
{
int c=0,i;
FileInputStream f=new FileInputStream("first.txt");
do
{
i=f.read();
c++;
}while(i!=-1);
System.out.println("No of character in the file is " + c);
}
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
}
Q17. What are the basic user interface components? Explain with example.
Ans. User Interface components help the user to interact with application. Java provides different
types of user interfaces. Some of the basic user interface components in the AWT are
followings.
Label: - A Label can be defined as static text string that act as a description for other AWT
components.
e.g
Label l=new Label(“welcome”,Label.CENTER);
add(l);
The specified creates a Label l displaying static text welcome and place it on the container
2. Buttons: - the component most commonly used in windows that trigger some action in the
interface when they are pressed. Button can be created using the following code in java.
Button b=new Button(“click me”);
add(b);
3. CheckBoxes: - These components have two states : on and off (selected and unselected).
They don’t trigger direct actions in the UI , but are used to indicate optional feature of some
other actions. They can be used in two ways.
Non exclusive :- Given the series of checkboxes , any of them can be selected.
Exclusive :- Given a series of check boxes, only one check box from the series can selected at
a time.
4. Radio Buttons: - A Radio button is hollow round. These are also created from the
checkbox class . In the case of Radio Button only one in a series can be selected at a time.
5. TextField: - provide an area where one can enter the text of single at runtime. Generally
used to get text from the user.
6. Choice menu or Choice list: - the popup list of items from which one can select an item.
Can be created using following code.
Choice ch=new Choice();
ch.add(“apples”);
ch.add(“mangos”);
add(ch);
7. TextArea: - TextArea are editable text fields that can handle more than one line of text
input. TextAreas are created from the TextArea class.
8. Scrolling List: - similar to the Choice List with two significant differences.
More than one item can be selected
Multiple items are displayed.
Created using the following codes.
List l=new List(3);
l.add(“ornage”);
l.add(“Mango”);
l.add(“Vanila”);
add(l);
Q18. Describe the class and interface hierarchy supported by the Collections API.
Ans. There are different types of classes and interfaces provides by java for Collection framework.
Collection Framework was designed to meets several goals . Like to achieve high
performance, high degree of interoperability.
The collection framework defines several interfaces these are of followings.
1. Collection :- Enables you to work with groups of objects; It is at the top of the
collections hierarchy.
2. List :- Extends Collection to handle sequences of List of objects
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
3. Set :- Extends Collection to handle sets, which must contain unique elements
4. SortedSet :- Extends Set to handle sorted sets.
The collection framework defines the following classes.
1. AbstractCollection :_ Implements most of the Collection interface.
2. AbstractLIst :- Extends AbstractCollection and implements most of the List interface.
3. AbstractSequentialList :- Extends AbstractList for use by a collection that uses
sequential rather than random access of its elements.
4. LinkedList :- Implements a linked list by extending AbstractSequentialList.
Q19. How UDP socket is used ? Discuss with an example.
Ans. public class clientTestUDP
{
Datagramsocket datasocket;
DatagramPacket dataPacket;
public static void main (String args [])
ClientTestUDP UDPClient = new ClientTestUDP ();
UDPClient.go ();
}
public void go ()
{
byte B[] = new. Byte [64];
String str;
try
{
datasocket = new Datagram Socket(1313);
dataPacket = new DatagramPacket(B, B.length);
While (true)
{
dataSocket.receive (dataPacket);
str= new String (datapacket.getData ());
System.Out.printIn (“Td signals received
From” + dataPacket.getAddress ()+
“In Time is: “+Str);
}
}
catch (Exception raised”);
}
}
}
Q20. What is Multithreading?
Ans. A thread executes a series of instructions. Every line of code that is executed is done so by a
thread. Some threads can run for the entire life of the applet, while others are alive for only a
few milliseconds.
Multithreading is the ability to have various parts of program perform program steps
seemingly at the same time. Java let programs interleave multiple program steps through the
use of threads. For example,one thread controls an animation, while another does a
computation. In Java, multithreading is not only powerful, it is also easy to implement.
You can implement threads within a java program in two ways – Creating an object that
extends Class Thread or implementing the interface Runnable.
The key difference between the two is that Thread class has a strart() method which your
program simple calls whereas the Runnable class does not have a start method and you must
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
create a Thread object and pass your thread to its constructor method. You never call run()
method directly; the start method calls it for you.
Example: Extending thread class
class MyProcess extends Thread{
public void run(){
}
public static void main(String args[]){
MyProcess mp = new MyProcess();
mp.start();
} }
Example: using Runnable interface
class MyProcess implements Runnable {
public void run(){ }
public static void main(String args[]){
Thread mp = new Thread(new MyProcess());
mp.start();
} }
Q21. What are DatagramPacket and why it is used in Socket Programming?
Ans. DatagramPackets can be created with one of four constructors. The first constructor specifies
a buffer that will receive data, and the size of a packet. It is used for receiving data over a
DatagramSocket. The second form allows you to specify an offset into the buffer at which
data will be stored. The third form specifies a target address and port, which are used by a
DatagramSocket to determine where the data in the packet will be sent. The fourth form
transmits packets beginning at the specified offset into the data. Think of the first two forms
as building and the second two forms as stuffing and addressing . the constructor used by
DatagramSocket has four constructor.
DatagramPacket(byte data[], int size)
DatagramPacket(byte data[], int offset,int size)
DatagramPacket(byte data[], int size,InetAddres ipAddress, int port)
DatagramPacket(byte data[], int size, int offset , int size, InetAddress ipAddress, int port)
There are several methods for accessing the internal state of a DatagramPackat. They give
complete access to the destination address and port number of a packet as well as the raw data
and its length.
Q22. Define PushbackReader?
Ans. The PushbackReader class allows one or more characters to be returned to the input stream.
This allows you to look ahead in the input stream. The two constructors of this class is
PushbackReader(Reader inputStream)
PushbackReader(Reader inputstream, int bufsize);
The first form creates a buffered stream that allows one character to be pushed back. In the
second , the size of the Pushback buffer is passed in bufSize.
PushbackReader provides unread() method which returns one or more characters to the
invoking inputstream. It has the three forms
Void unread(int ch);
Void unread(char buffer[])
Void unread(char buffer[], int offset, int numchars)
The first form pushes back the character passed in ch. This will be the next character returned
by the a subsequent call to read(). The second form returns the characters in buffer. The third
form pushes back numChars characters beginning at offset from buffer. An IOException will
thrown if there is an attempt to return a character when the pushback buffer is full.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Syntax
Synchronized (object)
{
statement to be synchronized.
}
Q25. Write down all user interface component classes provided by swing their uses.
Ans. Swing package provide a great number of prebuilt components classes.
1. Japplet - Use to design applet in swings.
2. Jbutton - To design push button.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Ans. To Execute Servlet , we need a package known as JSDK (Java Servlet Development Kit).It
provides all the class libraries and interfaces used to create a small servlet. The package used
by all the servlet programs i.e. java% servlet also available in JSDk.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Ans. The ServletConfig Interface is implemented by the server. It allows a servlet to obtain
configuration data when it is loaded. The Method declared by the interface are
getServletContext()
getInitParameter(String param), getInitParameterNames().
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
2. Specify jdbc.odbc.JdbcOdbcDriver in the program using class’s class’s for Name method.
3. Initialize the Connection with the help of Driver Manger ‘s getConnection method.in
which u have to specify the jdbc:odbc bridge with dsn reference.
4. Perform all the code in try/catch blocks ,because connection statements generate two type
of exception SQLException,ClassNotFound Exception.
5. After all that compile the program. With javac
Q4. What are the method provides by ResultSetInterface to Handle primitive data.
Ans. ResultSetInterface :- Resultset Interface will store the result of the select SQL query .
it provide different types of methods like
1.next() :- it will return true if any next record is available in the ResultSet.
2.close() :- It is used to close the ResultSet object.
Methods to handle primitive data
1. getInt() :- use to get integer value from the database.
2. getString():- use to get string value from the database.
3. getFloat():- use to get float value form the the database
4. getDouble():- to get Double value from the database.
5. getShort():- to get small int value from the database.
Q5. Define the connectivity model used by the java to connect database.
Ans. The java application is the UI . this in turn communicates with a driver manager using
underlying java code. The Driver Manager is a class that belongs to the java.sql package. The
driver manager communicates with 32bit ODBC driver.and odbc communicates with access
database.
Functionality of java connectivity model
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
6. Servlets are durable objects. because they remain in main memory until specifically
instructed to be destroyed.
7. Servlets can dynamically loaded either locally or across the network.
8. Servlets also support the multithreaded feature of java.
9. Servlets are protocol independent .
Q7. What is a distributed object System ? How RMI provides distributed object
mechanism.
Ans. The Distributed object system is a technology that combines networking and object-
oriented programming.
A distributed system includes nodes that perform compilations . A node may be a pc,a
mainframe computer. The nodes of a distributed system are scattered. The node in use is the
local node any other node is the remote node. A distributed system can not be established
without a network that connects nodes and allow the exchange of data.
RMI FOR DISTRIBUTED COMPUTING.
RMI is a simple method used for developing and deploying distributed object application in
java environment. In RMI an object oriented application creation is as simple as writing a
stand alone java application. It enables a programmer to create distributed java application, in
which the methods of the remote java object can be called from other java virtual machines
running either on the same host or on the different host scattered across a network..
Remote object call is identical from the local objects with the following exceptions
1. An object passed as a parameter to a remote method or returned from the method
must be serialzable or be another Remote object.
2. method passed by the remote objects are called by value and not by reference
3. a client always refers tp remote object through one of the Remote interface must be
implements.
The java.rmi and java.rmi.server package contain the interfaces and classes that defines the
functionality of java RMI system..
Q8. How does JSP differ from Servlets?
Ans. Java Server Pages (JSP) is a technology that lets you mix regular, static HTML with
dynamically-generated HTML. Servlets, make you generate the entire page via your program,
even though most of it is always the same. JSP lets you create the two parts separately. Java
Server Pages (JSP) is a Sun Microsystems specification for combining Java with HTML to
provide dynamic content for Web pages. When you create dynamic content, JSPs are more
convenient to write than HTTP servlets because they allow you to embed Java code directly
into your HTML pages, in contrast with HTTP servlets, in which you embed HTML inside
Java code. JSP is part of the Java 2 Enterprise Edition (J2EE).
JSP enables you to separate the dynamic content of a Web page from its presentation. It
categories to two different types of developers: HTML developers, who are responsible for
the graphical design of the page, and Java developers, who handle the development of
software to create the dynamic content. Example of JSP
Client 3
SUBJECT: ADVANCE JAVA (MCA – 5) 43/47
Database server maintains database after all condition checks or business logics handled by
Application server. And client send request to application server then after all checks it
transfer to the database server.
Application Clients
Application Client
Application
Differences
2-tier 3-tier
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Advantages of servlet
1. Capable of running in the same process space as the Web server.
2. Compiled. Program
3. Cross platform –program created on one platform can used to any platform because
java provide platform independently.
4. Durable
5. Dynamically loadable accross the network
6. Extensible
7. Multi threaded
8. Protocol independent
9. Written java
User.HTML
<HTML>
<BODY>
<Form name + f1 method = Post .8080
action= “http:// Localhost:8080/servlet/user.java”
<center>
<username <Input type = text name = “Un”>
<BR>
Password <input type = Password
Node = “PW”>
<BR>
<Input type = submit value = send >
<BR>
</center>
</BODY>
</HTML>
</FORM>
user. Java
import java.servlet. *;
import java.io. *;
public class user extends servelet {
public void service (Servelet Request rq. ServletResponse throws servelet &Exception,
IOException.
{
rs.setContentType (“Ext / HTML”);
PrintWriter PW = is.getWriter ();
PW.Printer “HTML> <BODY> “);
PW.Printer (“<H2> your email ID is: <I> “)
PW.printer (“<B>” + rq.getprintwriter (“un”) + “< /0>”);
PW.printer (“yahoo.com”);
PW.close ();
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
}
}
Q15. What are the various server side technologies? Explain.
Ans. There are numbers of server side technologies that helps to create response for the client from
the server. Like Common Gateway Interface(CGI), Active Server Pages(ASP), Servlet, Java
Server Pages(JSP) etc. These technologies are used to create dynamic web pages.
COMMON GATEWAY INTERFACE :- an interface used to create communication with web
server in early days. In this technology a server could dynamically construct a page by
creating a separate process to handle each client request allow the separate process to read
data from HTTP request and write data to the HTTP response. A variety of languages were
used to build CGI programs, including C, C++ and Perl.
ACTIVE SERVER PAGES :- another server side technology introduced by Microsoft to
create server side response for clients. Having very high performance with a draw back i.e.,
can only accessible on Microsoft based platform.
SERVLET :- the server side technology introduced by java to create server side response
with Java security manager provide platform independence by reducing traffic to network
because of handling all the client request on single address space.
JAVA SERVER PAGES :- technology allows web developers and designers to rapidly
develop and easily maintain, information-rich , dynamic web pages that leverage existing
business system. JSP enables rapid development of web based application that platform
independent. Create response for client with servlet.
Q16. Explain RMI Architecture with layer reference.
Ans. RMI architecture consist of four layers
1 Application 2. Stub/skeleton , Remote Reference and Transport Layer
1. Application Layer : - This layer contains the actual implementation of the client and sever
application. It is in this layers that high – level calls are made to access and export remote
objects.
2. The Proxy Layer : - This layer contains the client stub and server skeleton objects. The
application layer communicates with this proxy layer directly. All calls to remote objects
and marshaling of parameters and return objects are done through these proxies.
3. The Remote Reference Layer – The RRL(Remote Reference Layer ) handles packaging
of a method call and its parameters and its return values for transport over the network.
The RRL uses a server side and the client-side component to communicate via the network
layer.
4. Transport Layer :- The transport layer sets up connections, manages existing connections
and handles remote objects residing in its address space.
Q17. How a servlet is Destroyed Explain?
Ans. The servlet engine is not required to keep a servlet loaded for nay period of time or for the life
of the server. Servlet engines are free to use servlets or retire them at any time. Threrefor,
class or instance variables should not be used to store state information.
When the servlet engine determines that a servlet should be destroyed , the engine must allow
the servlet to release any resource it is using. To do this, the engine calls the servlet’s destroy
method.
The servlet engine must allow any calls to the service method either to complete or to end
with a time out before the engine can destroy the servlet. Once the engine destroys a servlet,
the engine coannot route any more requests to the servlet. The engine must release the servlet
and make it eligible for garbase collection.
Q18. Define HttpServletRequest and HttpServletResponseInterface?
Ans. The HttpServletRequest Interface encapsulates information of the request made to a servlet.
This interface gets information form the client to the servlet for use in the service() method .
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
It allows HTTP protocol specified header information to be accessed form the service()
method.
Following methods are provided by HttpServletRequest
1. getMethod() :- Returns the HTTP method (GET, POST) with which the request was
made.
2. getQueryString() :- Returns anyQuery String that is part of the HTTP REQUEST.
3. getRemoteUser() :- Returns the name of the ser making the HTTP request.
4. getRequested SessionId() :- To returns the Session Id specified with the HTTP request.
5. getSession(Boolean) :- If Boolean is FALSE, It return s the current valid session associated
with the HTTP request. If Boolean is TRUE, it creates a new session.
6.isRequestedSessionIdValid() :- Checks whether the HTTP request is associated with a
sessionthat is valid in the current session context
7. getCookies() : :- Returns the array of cookies found in the HTTP request.
The HttpServletResponse :- encapsulates information of the response sent by a servlet to a
client. This interface allows a servlet’s service() method to maniputlate HTTP protocol
specified header information and return data to its clients.
Methods of HttpServletResponse
addCookie(Cookies): Adds the specified cookie to the response.
encodeUrl(String) :- Encodes the specified URL by adding the sessionId to it. If encoding is
not required , it returnsthe URL unchanged.
sendRedirect(String) :- Sends a temporary redirect response to a client using the specified
redirect location URL.
Q19. What is Object Serialization also explain its criteria?
Ans. Object Serialization is the capability to write a Java object to a stream in such a way that the
definition and current state of object are preserved. When a serialized object is read from a
stream, the object initialized and in exactly the same state it was written to the stream.
Any Java class and its objects can be serialized as long as that class meets the following
criteria.
The class, or one of its superclasses, must implement the java.io.Serializable interface.
The class must participate with the writeObject() method to control data that is being saved or
append new data to existing saved data.
The class must participate with the readObject() method to read the data that has been written
by the corresponding writeObject() method.
If a serializable class has variables that should not be serialized, those variables Fmust be
marked with transient keyword. The serialization process then ignores them.
Q20. Explain all the methods provided by the Cookie class.
Ans. The Cookie class is used for session management with HTTP and HTTPS protocol . Cookies
are used to get Web Browsers to hold small amounts of state data associated with a a user’s
web browsing. Common applications for cookies include storing user preferences, automating
low security user sign on facilities.
Cookie class provide the following methods
1. Cookie(String,String) :- This the constructor of the class. It defines a cookie with an
initial name/ value pair.
2. setDomain(String) :- Specifies the domain, which this cookie belongs to . This cookie
will be visinble only to the specified domain.
3. setMaxAge(int) >- Sets the maximum age of the cookie. The unit of measurement is
seconds. A value of zero will cause the cookie to be deleted.
4. getValue() :- Returns the value of the cookie.
5. getName() :- returns the name of the cookie. The name of the cookie cannot be changed
after it is created.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019