Interview question on thread in Java

Q: What is a Thread?

Ans) In Java, “thread” means two different things: An instance of class java.lang.Thread. A thread of execution.
An instance of Thread is just…an object. Like any other object in Java, it has variables and methods, and lives and dies on the heap. But a thread of execution is an individual process (a “lightweight” process) that has its own call stack. In Java, there is one thread per call stack—or, to think of it in reverse, one call stack per thread. Even if you don’t create any new threads in your program, threads are back there running.

The main() method, that starts the whole ball rolling, runs in one thread, called (surprisingly) the main thread. If you looked at the main call stack (and you can, any time you get a stack trace from something that happens after main begins, but not within another thread), you’d see that main() is the first method on the stack— the method at the bottom. But as soon as you create a new thread, a new stack materializes and methods called from that thread run in a call stack that’s separate from the main() call stack.

Q: What is difference between thread and process?

Ans) Differences between threads and processes are:-
1. Threads share the address space of the process that created it; processes have their own address.

2. Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.

3. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.

4. Threads have almost no overhead; processes have considerable overhead.

5. New threads are easily created; new processes require duplication of the parent process.

6. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.

7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process do not affect child processes.

Q: What are the advantages or usage of threads?

Ans)
Threads support concurrent operations. For example,
• Multiple requests by a client on a server can be handled as an individual client thread.
• Long computations or high-latency disk and network operations can be handled in the background without disturbing foreground computations or screen updates.

Threads often result in simpler programs.
• In sequential programming, updating multiple displays normally requires a big while-loop that performs small parts of each display update. Unfortunately, this loop basically simulates an operating system scheduler. In Java, each view can be assigned a thread to provide continuous updates.
• Programs that need to respond to user-initiated events can set up service routines to handle the events without having to insert code in the main routine to look for these events.

Threads provide a high degree of control.
• Imagine launching a complex computation that occasionally takes longer than is satisfactory. A “watchdog” thread can be activated that will “kill” the computation if it becomes costly, perhaps in favor of an alternate, approximate solution. Note that sequential programs must muddy the computation with termination code, whereas, a Java program can use thread control to non-intrusively supervise any operation.

Threaded applications exploit parallelism.
• A computer with multiple CPUs can literally execute multiple threads on different functional units without having to simulating multi-tasking (“time sharing”).
• On some computers, one CPU handles the display while another handles computations or database accesses, thus, providing extremely fast user interface response times.

Q:  What are the two ways of creating thread?

Ans) There are two ways to create a new thread.

1)Extend the Thread class and override the run() method in your class. Create an instance of the subclass and invoke the start() method on it, which will create a new thread of execution. e.g.

public class NewThread extends Thread{

public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
c.start();
}

}

2)Implements the Runnable interface.The class will have to implement the run() method in the Runnable interface. Create an instance of this class. Pass the reference of this instance to the Thread constructor a new thread of execution will be created. e.g. class

public class NewThread implements Runnable{

public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
Thread t = new Thread(c);
t.start();
}

}

Q: What are the different states of a thread’s lifecycle?

Ans) The different states of threads are as follows:

1) New – When a thread is instantiated it is in New state until the start() method is called on the thread instance. In this state the thread is not considered to be alive.
2) Runnable – The thread enters into this state after the start method is called in the thread instance. The thread may enter into the Runnable state from Running state. In this state the thread is considered to be alive.
3) Running – When the thread scheduler picks up the thread from the Runnable thread’s pool, the thread starts running and the thread is said to be in Running state.
4) Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not runnable. The thread switches to this state because of reasons like wait method called or sleep method has been called on the running thread or thread might be waiting for some i/o resource so blocked. 5) Dead – When the thread finishes its execution i.e. the run() method execution completes, it is said to be in dead state. A dead state can not be started again. If a start() method is invoked on a dead thread a runtime exception will occur.

Q: What is use of synchronized keyword?

Ans) synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition. E.g.

public void synchronized method(){}
public void synchronized staticmethod(){}
public void myMethod(){

synchronized (this){ // synchronized keyword on block of code
}

}

Q: What is the difference when the synchronized keyword is applied to a static method or to a non static method?

Ans) When a synch non static method is called a lock is obtained on the object. When a synch static method is called a lock is obtained on the class and not on the object. The lock on the object and the lock on the class don’t interfere with each other. It means, a thread accessing a synch non static method, then the other thread can access the synch static method at the same time but can’t access the synch non static method.

Q: What is a volatile keyword?

Ans) In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased so the count variable is declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.

Q: What is the difference between yield() and sleep()?

Ans) yield() allows the current the thread to release its lock from the object and scheduler gives the lock of the object to the other thread with same priority.
sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock.

Q: What is the difference between wait() and sleep()?

Ans)

1) wait() is a method of Object class. sleep() is a method of Object class.

2) sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock. wait() allows thread to release the lock and goes to suspended state. The thread is only active when a notify() or notifAll() method is called for the same object.

Q: What is difference between notify() and notfiyAll()?

Ans) notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. The
highest priority thread will run first.

Q: What happens if a start method is not invoked and the run method is directly invoked?

Ans) If a thread has been instantiated but not started its is said to be in new state. Unless until a start() method is invoked on the instance of the thread, it will not said to be alive. If you do not call a start() method on the newly created thread instance thread is not considered to be alive. If the start() method is not invoked and the run() method is directly called on the Thread instance, the code inside the run() method will not run in a separate new thread but it will start running in the existing thread.

Q: What happens when start() is called?

Ans) A new thread of execution with a new call stack starts. The state of thread changes from new to runnable. When the thread gets chance to execute its target run() method starts to run.

Q: If code running is a thread creates a new thread what will be the initial priority of the newly created thread?

Ans) When a code running in a thread creates a new thread object , the priority of the new thread is set equal to the priority of the thread which has created it.

Q: When jvm starts up, which thread will be started up first?

Ans) When jvm starts up the thread executing main method is started.

Q: What are the daemon threads?

Ans) Daemon thread are service provider threads run in the background,these not used to run the application code generally.When all user threads(non-daemon threads) complete their execution the jvm exit the application whatever may be the state of the daemon threads. Jvm does not wait for the daemon threads to complete their execution if all user threads have completed their execution.

To create Daemon thread set the daemon value of Thread using setDaemon(boolean value) method. By default all the threads created by user are user thread. To check whether a thread is a Daemon thread or a user thread use isDaemon() method.

Example of the Daemon thread is the Garbage Collector run by jvm to reclaim the unused memory by the application. The Garbage collector code runs in a Daemon thread which terminates as all the user threads are done with their execution.

Q: What all constructors are present in the Thread class?

Ans) Thread()
Thread(Runnable target)
Thread(Runnable target, String name)
Thread(String name)

Q: Can the variables or classes be Synchronized?

Ans) No. Only methods can be synchronized.

Q: How many locks does an object have?

Ans) Each object has only one lock.

Q: Can a class have both Synchronized and non-synchronized methods?

Ans) Yes a class can have both synchronized and non-synchronized methods.

Q: If a class has a synchronised method and non-synchronised method, can multiple threads execute the non-synchronised methods?

Ans) Yes. If a class has a synchronised and non-synchronised methods, multiple threads can access the non-synchronised methods.

Q: If a thread goes to sleep does it hold the lock?

Ans) Yes when a thread goes to sleep it does not release the lock.

Q: Can a thread hold multiple locks at the same time?

Ans) Yes. A thread can hold multiple locks at the same time. Once a thread acquires a lock and enters into the synchronized method / block, it may call another synchronized method and acquire a lock on another object.

Q: Can a thread call multiple synchronized methods on the object of which it hold the lock?

Ans) Yes. Once a thread acquires a lock in some object, it may call any other synchronized method of that same object using the lock that it already holds.

Q : Can static methods be synchronized?

Ans) Yes. As static methods are class methods and have only one copy of static data for the class, only one lock for the entire class is required. Every class in java is represented by java.lang.Class instance. The lock on this instance is used to synchronize the static methods.

Q: Can two threads call two different static synchronized methods of the same class?

Ans) No. The static synchronized methods of the same class always block each other as only one lock per class exists. So no two static synchronized methods can execute at the same time.

Q : Does a static synchronized method block a non-static synchronized method?

Ans)No As the thread executing the static synchronized method holds a lock on the class and the thread executing the non-satic synchronized method holds the lock on the object on which the method has been called, these two locks are different and these threads do not block each other.

Q: Once a thread has been started can it be started again?

Ans) No. Only a thread can be started only once in its lifetime. If you try starting a thread which has been already started once an IllegalThreadStateException is thrown, which is a runtime exception. A thread in runnable state or a dead thread can not be restarted.

Q: When does deadlock occur and how to avoid it?

Ans) When a locked object tries to access a locked object which is trying to access the first locked object. When the threads are waiting for each other to release the lock on a particular object, deadlock occurs .

Q: What is a better way of creating multithreaded application? Extending Thread class or implementing Runnable?

Ans) If a class is made to extend the thread class to have a multithreaded application then this subclass of Thread can not extend any other class and the required application will have to be added to this class as it can not be inherited from any other class. If a class is made to implement Runnable interface, then the class can extend other class or implement other interface.

Q: Can the start() method of the Thread class be overridden? If yes should it be overridden?

Ans) Yes the start() method can be overridden. But it should not be overridden as it’s implementation in thread class has the code to create a new executable thread and is specialised.

Q: What are the methods of the thread class used to schedule the threads?

Ans) The methods are as follows:

public static void sleep(long millis) throws InterruptedException

public static void yield()

public final void join() throws InterruptedException

public final void setPriority(int priority)

public final void wait() throws InterruptedException

public final void notify()

public final void notifyAll()

Q: Which thread related methods are available in Object class?

Ans) The methods are:

public final void wait() throws Interrupted exception

public final void notify()

public final void notifyAll()

Q: Which thread related methods are available in Thread class?

Ans) Methods which are mainly used :

public static void sleep(long millis) throws Interrupted exception

public static void yield() public final void join() throws Interrupted exception

public final void setPriority(int priority)

public void start()

public void interrupt()

public final void join()

public void run()

public void resume()

Q: List the methods which when called the thread does not release the locks held?

Ans) Following are the methods.

notify()

join()

sleep()

yield()

Q: List the methods which when called on the object the thread releases the locks held on that object?

Ans) wait()

Q: Does each thread has its own thread stack?

Ans) Yes each thread has its own call stack. For eg

Thread t1 = new Thread();
Thread t2 = new Thread();
Thread t3 = t1;

In the above example t1 and t3 will have the same stack and t2 will have its own independent stack.

Q: What is thread starvation?

Ans) In a multi-threaded environment thread starvation occurs if a low priority thread is not able to run or get a lock on the resoruce because of presence of many high priority threads. This is mainly possible by setting thread priorities inappropriately.

Q: What is threadLocal variable?

Ans) ThreadLocal is a class. If a variable is declared as threadLocal then each thread will have a its own copy of variable and would not interfere with the other’s thread copy. Typical scenario to use this would be giving JDBc connection to each thread so that there is no conflict.

ThreadLocal class by JAVA API
public class ThreadLocal {
public Object get();
public void set(Object newValue);
public Object initialValue();
}

Implementation of ThreadLocal
public class ConnectionDispenser {
private static class ThreadLocalConnection extends ThreadLocal {
public Object initialValue() {
return DriverManager.getConnection(ConfigurationSingleton.getDbUrl());
}
}

private static ThreadLocalConnection conn = new ThreadLocalConnection();

public static Connection getConnection() {
return (Connection) conn.get();
}
}

Q: What’s the difference between Thread and Runnable types?

A: A Java Thread controls the main path of execution in an application. When you invoke the Java Virtual Machine with the java command, it creates an implicit thread in which to execute the main method. The Thread class provides a mechanism for the first thread to start-up other threads to run in parallel with it.

The Runnable interface defines a type of class that can be run by a thread. The only method it requires is run, which makes the interface very easy to fulfil by extending existing classes. A runnable class may have custom constructors and any number of other methods for configuration and manipulation.

Q: How does the run() method in Runnable work?

A: It may help to think of the run method like the main method in standard single threaded applications. The run method is a standard entry point to run or execute a class. The run method is normally only executed in the context of an independent Thread, but is a normal method in all other respects.

Q: Why not override Thread to make a Runnable?

A: There is little difference in the work required to override the Thread class compared with implementing the Runnable interface, both require the body of the run() method. However, it is much simpler to make an existing class hierarchy runnable because any class can be adapted to implement the run() method. A subclass of Thread cannot extend any other type, so application-specific code would have to be added to it rather than inherited.

Separating the Thread class from the Runnable implementation also avoids potential synchronization problems between the thread and the run() method. A separate Runnable generally gives greater flexibility in the way that runnable code is referenced and executed.

Q: When could I adapt the Thread class though?

A: It is always best to implement a Runnable type rather than extend a Thread. On that basis, the extension of the Thread class should only be considered in exceptional circumstances when the application is very simple, composed of few classes, where the interaction of threads is minimal and requires only minimal control over thread execution.

Q: What’s the difference between a thread’s start() and run() methods?

A: The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.

The Thread class’ run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread’s run() method executes the run() method of the Runnable object in the new thread instead.

Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.

Q: Can I implement my own start() method?

A: The Thread start() method is not marked final, but should not be overridden. This method contains the code that creates a new executable thread and is very specialised. Your threaded application should either pass a Runnable type to a new Thread, or extend Thread and override the run() method.

Multi-threaded design questions

Q: If all methods are synchronized, is a class thread safe?

A: Even if all the methods of a class are synchronized, it may still be vulnerable to thread safety problems if it exposes non-final fields or its methods return mutable objects that could be manipulated by multiple threads. Non-final fields should be declared private and encapsulated with synchronization. Rather than return references to internal object fields, create an independent copy that has no relation to the original, known as a deep copy.

A deep copy of an object duplicates the content and state of the original object and all its constituent fields in such a way that none of its properties refer to instances in the original at any level.

These measures will help prevent uncontrolled access to the internal state of objects, but you must also ensure synchronization techniques are applied in a robust, consistent manner that will not cause deadlock or race conditions. It is generally better to use synchronized blocks than synchronized methods for performance reasons. Limit the extent of synchronized blocks and ensure they all use the same object monitor.

Q: How do I create a Runnable with inheritance?

A: To introduce a Runnable type to an existing class hierarchy, you need to create a sub-class that declares that it implements the Runnable interface, and provide a run method to fulfil the interface. This combination of interface and inheritance means that runnable implementations can be very minor extensions of existing classes

Singleton Pattern – Design Patterns in Java

The Singleton Pattern Ensure a class only has one instance, and provide a global point of access to it.For example ,if we need a connection to single database at one time  or when ever we are referring to to single application.properties file in struts application for showing application in one language at one time.Then we can need of singleton pattern or you can use it to create a connection pool. It’s not wise to create a new connection every time a program needs to write something to a database; instead, a connection or a set of connections that are already a pool can be instantiated using the Singleton pattern.

Need of Singleton Pattern

– Sometimes we want just a single instance of a class to exist in the system

– We need to have that one instance easily accessible

– And we want to ensure that additional instances of the class can not be created

Benefits of Pattern

– Controlled access to sole instance

– Permits a variable number of instances

How we can Implement singleton pattern

We will be using statis method to call the client to get a reference to the

single instance and we’ll use a private constructor

/* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/

public class VinaySingleton {

private static VinaySingleton  VINAYINSTANCE ;

private VinaySingleton() {
}

public static VinaySingleton  getInstance() {
if(VINAYINSTANCE ==null){
VINAYINSTANCE = new VinaySingleton();
}

return VINAYINSTANCE;

}

We will be having private constructor which tells that no other outside classes can directly instantiate this class. The only way to get a reference to the VinaySingleton object is to make a call to the static method VinaySingleton.getInstance ().Similarly create Myconnection class and method as above


Even if client call the VinaySingleton.getInstance multiple time the multiple object will point to same reference.

package techartifact.pattern.singleton;
public class VinayClient {
public static void main(String[] args) {

 VinaySingleton i1 = VinaySingleton.getInstance();
 MyConnection i2 = MyConnection.getInstance();

 if (i1 == i2){
System.out.println("Both the object pointing to same reference");
 }else{
System.out.println("Objects are not equal");
}
 }
}

Interview question of Servlets


1) What is servlet?

Ans: Servlets are modules that extend request/response-oriented  servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database.

2) What are the classes and  interfaces for servlets?

Ans: There are two packages in servlets and they are javax.servlet and javax.servlet.http.

Javax.servlet contains:

Interfaces                       Classes

Servlet                           Generic Servlet

ServletRequest               ServletInputStream

ServletResponse            ServletOutputStream

ServletConfig                 ServletException

ServletContext               UnavailableException

SingleThreadModel

Javax.servlet.http contains:

Interfaces                                          Classes

HttpServletRequest                            Cookie

HttpServletResponse                         HttpServlet

HttpSession                                       HttpSessionBindingEvent

HttpSessionContext                           HttpUtils

HttpSeesionBindingListener

3) What is the difference between an applet and a servlet?

Ans:     a) Servlets are to servers what applets are to browsers.

b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.

4)what is the lifecycle of a servlet.

Ans: Each Servlet has the same life cycle:

a)A server loads and initializes the servlet by init () method.

b)The servlet handles zero / more client’s requests through service()              method.

c)The server removes the servlet through destroy() method.

5) What is the ServletConfig() and why are using ServletConfig ?

Ans: This interface is implemented by services in order to pass

configuration information to a  servlet when it is first loaded.Aservice writer implementing this  interface must write methods

for the servlet to use to get its initialization parameters and the context in which it is running.public interface ServletConfig

6) What is meant by the ServletContext() and use of the method ?

Ans:  The ServletContext interface gives servlets access to information about their environment ,and allows them to log significant events. Servlet writers decide  what data to log. The interface is implemented by services, and used by servlets. Different virtual hosts should have different servlet contexts.

public interface ServletContext

7) What is use of parseQueryString ?

Ans: Parses a query string and builds a hashtable of key-value pairs, where the values are arrays of strings. The query string should have the form of a string packaged by the GET or POST method. (For example, it should have its key-value pairs delimited by ampersands (&) and its  keys separated from its values by equal signs (=).)

Note:

public static Hashtable parseQueryString(String s)

8)what are the types of servlets.

Ans: Genereic Servlets,HttpServlets.

9)what are the different methods in HttpServlet.

Ans: doGet(),doPost(),doHead,doDelete(),deTrace()

10)What is the difference between GET and POST.

Ans: a) doGet() method is used to get information, while doPost( ) method  is used for posting information.

b) doGet() requests can’t send large amount of information and is limited to 240-255 characters. However,doPost( )requests passes all of its data, of unlimited length.

c) A doGet( ) request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part  of its  HTTP request body and the exchange are invisible to the  client.

11) Why do you need both GET and POST method implementations in Servlet?

Ans: A single servlet can be called from differenr HTML pages,so Different method calls can be possible.

12)When init() and Distroy() will be called.

Ans: init() is called whenever the servlet is loaded for the first time into the webserver.destroy() will be called whenever the servlet is removed from the webserver.

13) Who is loading the init() method of servlet?

Ans: Web server

14)If you want to modify the servlet,will the Webserver need to be ShutDown.

Ans:No

15)What is the advantage of Servlets over other serverside technologies.

Ans: PlatForm independent, so once compiled can be used in any webserver.For different processes different threads will execute in-built mutithreaded.

16) What is Server-Side Includes (SSI)?

Ans: Server-Side Includes allows embedding servlets within HTML pages using   a special servlet tag. In many servlets that support servlets, a page  can be processed by the server to include output from servlets at  certain points inside the HTML page. This is accomplished using a  special internal SSINCLUDE, which processes the servlet tags.SSINCLUDE

servlet will be invoked whenever a file with an. shtml extension is  requested.So HTML files that include  server-side includes must be   stored with an .shtml extension.

17)What is Single Threaded Model in Servlets and how is it useful give one practical example.

Ans: For every single user a differnt copy of this servlet is executed.        For  Ex: To do Credit card transactions.

18) What is the uses Sessions ?

Ans: Its a part of the SessionTracking and it is for mainting the client  state at server side.

****19)What are the advantage  of using Sessions over Cookies and URLReWriting?

Ans: Sessions are more secure and fast becasue they are stored at serverside. But Sessions has to be used combindly with Cookies or URLReWriting for mainting the client id that is sessionid at client side.Cookies are stored  at client side so some clients may disable cookies   so we may not sure that the cookies which  we are mainting  may work  or not but in sessions cookies are disable we can maintain our   sessionid using URLReWriting .In URLReWriting we can’t maintain large data because it leads to    network traffic and access may be become slow.Where as in seesions   will not maintain the data which we have to maintain instead we will maintain only the session id.

20) What is session tracking and how do you track a user session in servlets?

Ans: Session tracking is a mechanism that servlets use to maintain state  about a series of  requests from the same user across some period of time.The methods used for session tracking are:

a) User Authentication – occurs when a web server restricts access to      some of its resources to only those clients that log in using a recognized username and password

b) Hidden form fields – fields are added to an HTML form that are not displayed in the client’s browser. When the form containing the  fields is submitted,

the fields are sent back to the server

c) URL rewriting – every URL that the user clicks on is dynamically  modified or rewritten to include extra information. The extra information can be in the form of extra path information, added  parameters or some custom, server-specific URL change.

d) Cookies – a bit of information that is sent by a web server to a browser and which can later be read back from that browser.

e) HttpSession – places a limit on the number of sessions that can        exist in memory. This limit is set in the     session.maxresidents       property

21)What is Cookies and what is the use of Cookies ?

Ans: Cookies are used to get user agents (web browsers etc) to hold small amounts of state associated with a user’s web browsing.Later that  infromation read by server

22) What are cookies and how will you use them?

Ans: Cookies are a mechanism that a servlet uses to have a client hold a   small amount of state-information associated with the user.a) Create a cookie with the Cookie constructor:

public Cookie(String name, String value)

b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of

HttpServletResponse:public void HttpServletResponse.addCookie(Cookie cookie)

c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest:public Cookie[ ] HttpServletRequest.getCookie( ).

23) How many Cookies is supported to the host ?

Ans: User agents excepted to support twenty per host.And its take fourKilobytes each.

24) What is the use of setComment and getComment methods in Cookies ?

Ans:

setComment: If a user agent (web browser) presents this cookie to a user, the cookie’s purpose will be described using this comment. This  is not supported by version zero cookies.

public void setComment(String use)

{

}

getComment:  Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.

25)Why we are used setMaxAge() and getMaxAge() in Cookies ?

Ans:  setMaxAge

public void setMaxAge(int expiry)

Sets the maximum age of the cookie.The cookie will expire after that many seconds have passed.Negative values indicate the default behaviour:the cookie is not stored persistently, and will be deleted when the user agent exits.A zero value causes the cookie to be deleted

getMaxAge():

public int getMaxAge()

Returns the maximum specified age of the cookie. If none was specified, a negative value is returned, indicating the default behaviour described with setMaxAge.

26)What is the use of setSecure() and getSecure() in Cookies ?

Ans: setSecure

Indicates to the user agent that the cookie should only be sent using a secure protocol (https). This should only be set when the cookie’s originating server used a secure protocol to set the cookie’s value.

public void setSecure(boolean flag)

getSecure:

Returns the value of the ‘secure’ flag.

public boolean getSecure()

27)What is meant by Httpsession and what is the use of sessions ?

Ans: The HttpSession interface is implemented by services to provide an

association between an HTTP client and HTTP server. This session,

persists over multiple connections and/or requests during a given time

period. Sessions are used to maintain state and user identity across

multiple page requests.

HttpSession session = req.getSession(true);

28) What are the methods in HttpSession and use of those methods?

Ans:

a)         getCreationTime()

Returns the time at which this session representation was created.

b)         getId()

Returns the identifier assigned to this session.

c)         getLastAccessedTime()

Returns the last time the client sent a request carrying the    identifier assigned to the session.

d)         getSessionContext()

Returns the context in which this session is bound.

e)   getValue(String)

Returns the object bound to the given name in the session’s

application layer data.

f)                       getValueNames()

Returns an array of the names of all the application layer data

objects bound into the session.

g)         invalidate()

Causes this representation of the session to be invalidated and   removed from its context.

h)         isNew()

A session is considered to be “new” if it has been created by the server, but the client has not yet acknowledged joining the session.

j)          putValue(String, Object)

Binds the specified object into the session’s application layer data   with the given name.

k)         removeValue(String)

Removes the object bound to the given name in the session’s application layer data.

29) How do you communicate between the servlets.

Ans: a)servlet chaning

b)Servlet context(RequestDespatcher interface)

30)Can you send the mail from a servlet ,if yes tell how?

Ans:yes.using mail API

31)How do you access variables across the sessions.

Ans:Through ServletContext.

32)where the session data will store?

ans: session objects

33)What is Servlet Context?

Ans:This object represents resources shared by a group of servlets like

servlet’s environment,Application attributes shared in the context

level.

34)How do you trap the debug the errors in servlets.

Ans:error log file

35)How do you debug the Servlet?

Ans:through servlet log();

36)How do u implement threads in servlet?

Ans:Intenally implemented

37)How do you handle DataBase access and in which method of the servlet do you like to create connection.

Ans:init()

38)If you want to improve the performance how do you create connections for multiple users?

A.Connection Pooling.

39)what is connection pooling?

Ans:Class which manages no of user requests for connections to improve the

performance.

40) What are the different servers available for developing and deploying Servlets?

Ans:                    a)    JRun2.0–Allaire

b)    Apache—jserv

c)    jwsdk2.0 –sun

d)    servletexec

e)    Tomcat webserver—tomcat

f)     Weblogic AS—BEA Systems

g)    NetDynamics5.0–sun

h)    Iplanet—sun&netscape

i)     Netscape—netscape

g)    IBM websphere—IBM

h)    oracle—oracle

i)     Proton-Pramati technologies

41) Is it possible to communicate from an applet to servlet and how many ways and how?

Ans: Yes, there are three ways to communicate from an applet to servlet and

they are:

a)                 HTTP Communication(Text-based and object-based)

b)                 Socket Communication

c)                 RMI Communication

(You can say, by using URL object open the connection to server

and get the InputStream from URLConnection  object).

Steps involved for applet-servlet communication:

step: 1               Get the server URL.

URL url = new URL();

step: 2               Connect to the host

URLConnection Con = url.openConnection();

step: 3               Initialize the connection

Con.setUseCatches(false):

Con.setDoOutput(true);

Con.setDoInput(true);

step: 4               Data will be written to a byte array buffer so that we can tell the server the length of the data.

ByteArrayOutputStream byteout  = new ByteArrayOutputStream();

step: 5               Create the OutputStream to be used to write the data to the                 buffer.

DataOutputStream out = new DataOutputStream(byteout);

42) Why should we go for interservlet communication?

Ans: Servlets running together in the same server communicate with each

other in several ways.The three major reasons to use interservlet communication are:

a)Direct servlet manipulation – allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object)

b)Servlet reuse – allows the servlet to reuse the public methods of another servlet.

c)Servlet collaboration – requires to communicate with each other by sharing specific information (through method invocation)

43) Is it possible to call servlet with parameters in the URL?

Ans: Yes. You can call a servlet with parameters in the syntax as

(?Param1 = xxx || m2 = yyy).

44) What is Servlet chaining?

Ans: Servlet chaining is a technique in which two or more servlets can  cooperate in servicing a single request.In servlet chaining, one  servlet’s output is piped to the next servlet’s input. This process continues until the last servlet is reached. Its output is then sent back to the client.

45) How do servlets handle multiple simultaneous requests?

Ans: The server has multiple threads that are available to handle requests.  When a request comes in, it is assigned to a thread, which calls a  service method (for example: doGet(), doPost( ) and service( ) ) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

46) How are Servlets and JSP Pages related?

Ans: JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.Servlets:

47).How do servlets handle multiple simultaneous requests?

Ans: Using Threads

48).How do I automatically reload servlets?

Ans:depends upon the server’s servlet reload properites.

48).My servlet, which ran correctly under the Servlet 2.0 APIs (Java Web Server 1.1.3) is  not running under the Servlet 2.1 APIs (Java Web Server 2.0). What’s wrong?

Ans:You might have used servlet to servlet communication by usingservletcontext methods like getServlet(),getServlets() which are  depricated and returns null from new release that is from servlet2.1 API.

49) What are the types of ServletEngines?

Standalone ServletEngine: A standalone engine is a server that includes built-in support for servlets.

Add-on ServletEngine: Its a plug-in to an existing server.It adds servlet support to a server that was not originally designed with servlets in mind.Embedded ServletEngine: it is a lightweight servlet deployment platform that can be embedded in another application.that application become true server.

****50)what is httptunneling?

ans: it is mechanism of performing both write and read operations using http protocol.it is extending the functionality of htp protocol.

51).How do I use native code in a servlet?

Ans:

49)What’s with the javax.servlet package naming?

Ans:

50. List out Differences between CGI Perl and Servlet?

Servlet                                                                                      CGI

Platform independent                                        Platform dependent.

Language dependent                                         Language independent.

Pin it