Вы находитесь на странице: 1из 17

Interview Questions: JSP

Question: what are the types of exceptions in java?

a) There are two types of exceptions in java

1> checked exceptions

Checked exceptions are also known as compile time exceptions as they are identified
during compile time of the program. Exception and all the subclasses of Exception
class are checked exceptions

2> Unchecked exceptions

Unchecked Exceptions are also known as runtime exceptions as they are


identified during the runtime of the program. class RuntimeException and all the
subclasses of RuntimeException are unchecked Exceptions

b) There are 2 types of exception in Java (1) check like an network failure or any
database problem showes this types of excepton.(2 ) Uncheked exception that is at
run time exceptions.

Question: What's the different forward and sendRedirect?

a) forward will just forward the request to next page where as sendRedirect will first
come back to the page where its been generated and the redirect to next page

b) forward will just forward the request to next page where as sendRedirect will first
come back to the page where its been generated and the redirect to next page

c) RequestDispatcher.forward() is completely handled on serverside while


HttpServletResponse.sendRedirect() sends a redirect message to the browser.

RequestDispatcher.forward() is transparent to the browser while


HttpServletResponse.sendRedirect() is not.

d) When u Goes in to the forward() , here request and response may not be available
to u. i,e u cannot say req.getParameter().

Where as in sednRedirect() u can get Request and Response Objects.

e) there are a lot of difference between RequestDispatcher.forward() and


HttpServletResponse.sendRedirect() ==>1) The forward() works within your
application while sendRedirect() can also work outside of the application.2)
SendRedirect() is slower then the forward().3) if you use sendRedirect() then no
request-response will be available to you on forwarded page while it can be available
through forward().3) if we use sendRedirect(), the url of the browser has been
changed while it has not been changed by forward()4) sendRedirect() is on the client
side while forward() is on the server side

Question: can we implement an interface in jsp?if yes how ?if no why?

1
Interview Questions: JSP

a)No we cant implement interface in jsp

b) So also jsp cannot implement an interface

<%@ page
[ language="java" ]
[ extends="package.class" ]
[ import="{package.class | package.*}, ..." ]
[ session="true | false" ]
[ buffer="none | 8kb | sizekb" ]
[ autoFlush="true | false" ]
[ isThreadSafe="true | false" ]
[ info="text" ]
[ errorPage="relativeURL" ]
[ contentType="mimeType [ ;charset=characterSet ]" | "text/html ;
charset=ISO-8859-1" ]
[ isErrorPage="true | false" ]
%>

c) In "Page" directive you have "extends" attribute which allows you to extend you
class by jsp.
They why i can not implement my interface......??????
First solution:: i can do it by implementing my interface by my class and then i
can use "Page" directive which have "extends" attribute which allows me to extend
my class by jsp.

Question: What is the difference between a uri and a url?

a)uri--uniform resource identifier,

url--uniform resource locator,

uri provides only the name of the resource, like in web.xml, in url-pattern you would
be specifying the uri for identification of the servelt when the request is made in the
url.

url gives the path of the resource where it was located.url identifies the path where
the uri is located.

Question: How to call method in Jsp from servlet

2
Interview Questions: JSP

a) Even though we call a jsp page from servlet through request dispatcher,we can
not call a perticular method of a jsp from servlet.there is no such mechanism in
servlet API.but iam not sure.

b) RequestDispatcher reqDis = request.getRequestDispatcher("Jspfile.jsp");

reqDis.forward(request, response);

This will work ... :)

You can get RequestDispatcher from ServletConetext object, then you should give
the path to resouce with reference to context path, as

RequestDispatcher reqDis =
getServletContext().getRequestDispatcher("/Jspfile.jsp");

//Observer '/' infront of the filename. It is must!!

Question: what is Thread independent and garbage collection independent?

Thread Independent:

There is no thread involve in executing program. Each time we execute


program it create a separate process.

Garbage Independent:

Each and every object involves garbage collection.

Question: what is the use of immutable String class in java?

a)String Objects are immutable where as String references are not.

ex : String s="abc";// here two objects are created and one reference s

// where one is copied in the pool and another in non pool

s.concat("def"); // here s refernces still to abc since it is not refrenced to any


value.

s1=s.replace('a','x'); // here s1 value is xbc ... s still refers to abc ..

b) String Objects are immutable .They cant be changed. StringBuffers are


mutable.they can be altered as per the users wish.

c) If your value is not going to change and if u don't want to multiple threads to
access...then strings come into picture

3
Interview Questions: JSP

d) Immutable means not changeable. when a string is declared and initiated with
some values.

Afterwards whenever we will concat that string or change that string. if we r going to
add more characters in that string object. it will not allow dynamic size change. to
cater such problem when any change will occur in string object the object will be
recreated and previous object will be destroyed and new will be created with new
size to accomodate change. thats y strings are immutable in java.

e) String are made immutable because

1. better memory management.Generally thousands of string literals objects are


created in any of the application.To avoid the individual memory allocation to all the
string objects ,JVM creates the string literal objects in a dedicated string constants
memory pool and allots the a same reference to all the string having the same value.

String s1 = "abc";

String s1 = "abc"; //here both s1 , s2 point to the same object abc,rather than 2
different objects with same value.

And so the String class is made final to support this functionality.

f) String is final class, so we can not extends to any other class.

Question: Can we implement the printable interface in jsp? if yes, how?

Very easy, just define a class that implement the Printable interface and then import
that class and use the print() method.

public class myPrintable implement Printable {

public int print(Graphics gr, PageFormat pf, int pageIndex) throws Exception {

super(gr, pf, pageIndex);

Question: What is difference between abstract class and interface

Abstract Class means Blueprint of the model.

Interface means functionality of the model(Blueprint) if the class implements one(an


interface).

Using Abstract class we can take n number of instances. Like using the Blueprint of a
Car
we can take n number of similar cars. But we cannot use the Bluprint or model to
drive the
car.That is the meaning of abstract. So, Car is the Blueprint and Ford Car is the

4
Interview Questions: JSP

derived class from car which uses all the


properties of class and some more properties which is specific to Ford.

Frog is a derived class from Mammal.

When it lives on land it implements the function of hopping.

when it lives on water it implements the function of swimming.

So we find that frog uses both methods hopping and swimming. So it is better to
declare
in some interface so that any frog which implements the interface will define its own
way of transportation.

So let me create an Interface called Amphibian and give two method Swimming()
and hopping().
It looks like

public interface Amphibian{

public void swim();


public void hop();
}

Let we define the Frog class as

public class Frog implements Amphibian{

public void swim(){

//Define your words


}

public void hop(){

//Define your words


}

The above class Frog when implements the interface Amphibian it has to define the
methods
declared in the interface Amphibian. It can be an empty method. But it should be
defined.

The use of an interface is any class which wants to use some remote functionality
can
implement that particular interface and can perform the task like man using
Parachute to
fly in air.

5
Interview Questions: JSP

What is ClassLoader?

Class loaders are one of the cornerstones of the Java virtual machine (JVM)
architecture. They enable the JVM to load classes without knowing anything about
the underlying file system semantics, and they allow applications to dynamically load
Java classes as extension modules.A class loader is an object that is responsible for
loading classes. The class ClassLoader is an abstract class. Given the name of a
class, a class loader should attempt to locate or generate data that constitutes a
definition for the class. A typical strategy is to transform the name into a file name
and then read a "class file" of that name from a file system.

Question: What is the significance of wait() method with respect to Object


class, not in Thread class?

a) the wait() method is defined in the java.lang.OBject() class and not in the
java.lang.Thread()class. it's signature is public static void wait(). we do have some
overloaded versions of the wait() method. when an wait method is called by an
thread on a object it release the lock on the object and goes to an WAIT/BLOCKED
state inorder to let the other threads to enter the RUNNING state. However it regains
the Lock on the object after sometime when it moves from the WAIT/BLOCKED state
to RUNNABLE state . that can happen due to the call of notify(),notifyAll() methods
by other threads holding of the respective objects Lock.

b) According to the Java Specification, the four methods related to threading is


defined in the Object class rather than the Thread Class, because of the Java
Concurrency and Synchronised construct. As we start the JDK, there are different
therad runs under backgound and it may not be possible to all that object to extends
the thread class. So, by definging this method in the Object class, any one can
access without extending the Thread Class and ensure synchronisation.

Question: Is there other way to prevent next thread to access the resource
with out using "synchronized" blocks?

a)singleton class is used to create a single object for a class and is most secured
class, but it do not support siglethreaded model

you can block the next thread without using sinchronize method by implementing
single threaded model interface.

Question: Can we call destroy() method on servlets from service method?

a) We can call the destroy() method. But it works like normal method, for example, if
u have one method in ur servlet class like show(), it acts like show() method.
Whenever we click on the stop link in manager page of that particular application,
then only application will be stopped and it calls the destory method. At that time
only the application objects permanently destroyed. Sample code: Try it out..

public class TestServlet extends HttpServlet implements SingleThreadModel{

public void init(){

6
Interview Questions: JSP

System.out.println("hello in init"); }

public void doGet(HttpServletRequest request,HttpServletResponse response)throws


ServletException,IOException{

PrintWriter out=response.getWriter();

out.println("Selected Button Name :"+request.getParameter("button")); }

public void destroy(){ System.out.println("Hello in destroy"); }}

b) Yes, we can call destroy() method from service() method but it will be treated as
any other normal method rather lifecycle method. Also destroy() method called from
service() method can do any deinitialization task etc but the servlet container will not
unload the servlet, that can only be done by the lifecycle destroy() method.

c) Destroy method is a method where we can provide the actions (to free up the
resources)Â to be performed while the servlet is getting unloaded. In general when a
servlet is getting destroyed the servlet container calls this method and also does
many other things. So if you want to unload a servlet you have to do all the things
the servlet container does including calling the servlet method.

When you directly call the destroy method from service method the method will be
successfully called as you are calling the method from same object but you are not
doing all the other things the servlet does to unload the servlet. So the servlet will
not be unloaded but the destroy method will be called as any other non life cycle
method (like display()).

Question: When we increase the buffer size in our project using page
directive attribute ‘buffer’ what changes we observe?

a) The effect will be only that the caching of pages in the memory will increase and if
it is increase upto much extends, it will consume the more memory of the system. It
may increase or decrease the performance of an application.

b) the default buffer size is 8k and when we increase the buffer size of the page
using the buffer attribute of the page directive then the storage capacity will be
increased .if the buffer size is too large then the performance will degrade.

instead of increasing the buffer size use autoFlush=true ,bydefault the autoFlush is
true only.so even the content i.e to be send to the client crosses

8k the jsp doesnot throws exception.

Question: Servlet is Java class. Then why there is no constructor in Servlet?


Can we write the constructor in Servlet

a) It is a java class only but it does not support Constructor becuase Servlet is
loaded by servlet container not through normally we initilized the java class

like X x = new X();

7
Interview Questions: JSP

b) If there is no constructore in the Servlet , then it does not mean that we can not
write the constructore in the servlet. Offcourse we can write. As we know that the
constructore only instantiate the normal java class and servlet is not a notmal java
class. To make a object as servlet, a lot of properties has to be defined. and this
property comes by init() method. so, writing the constructore in servlet is worthless.

c) First of all Servlet is not a Java class. Its an interface, interface does not have
constructors. And java servlet container implements servlet creating respective
servlet classes which are mapped in deployment discriptor.

init method performs the task on normal constructor in servlets as its called by the
actual class taht implements servlet in the container run time by calling the init
method.

d) Servlet is an interface!!!!

So there is no question if having its Constructor. Please refer JavaDocs


http://java.sun.com/j2ee/1.4/docs/api/ for clarification

Question: what is the role of


Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") in my application?

a) when we call forName() method on Class class what happen is1)initially the class
is loaded into the memory2)then it calls the static method forName()3)the static
forName() method contains a static block.That static block regiser the loaded driver
class with the DriverManager class

b) it is used to load the class at runtime and in jdbc it is used to load the driver and
according to specification every driver class must contain a static block in which it
contains the code to instanciate itself and the register itself with the driver manager.

Question: explain details of concept of"object iceland" in garbage collection


(object lifetime) in corejava

Ans):if a composite object becomes unreachable, then its constituent objects also
become unreachable, barring any reachable references to the constituent objects.

ex:objects o1, o2, and o3 form a circular list(object o1 have reference to o2,object
o2 have reference to o3 and object o3 have reference to o1) , and they do not have
any reachable references.These objects are called "object iceland". Thus, these
objects are all eligible.

Question: difference between instanceation & initilization?

a) Instantiation is process of creating object. Initialization is process of initialising


values inside that object.

b) Instance ation will not allocate memory, just a instance will be created.

Initialization will actually allocate memory.

8
Interview Questions: JSP

wht is the difference between reference variables and objects

The reference variable is that one where we r not using the new keyword e.g.
Connection con; But Object is that where we r using new operatore.g Classname
cs1=new classname

Question: why the StringBuffer and the wrapper classes defined as final ?

A class can be declared final if its definition is complete and no subclasses are
desired or required.they are handled in different way by jvm at runtime. so both the
classes are marked as final

b) By defining a class as final we are restricting the one of the main feature of OOP
ie., INHERITANCE. But JavaSoft(SUN) has provided this restricting feature because
Java Developers thought that some methods cannot be modified by the users. Eg.
for those are the methods in String , StringBuffrer ,StringBuilder , all Wrapper
classes. As String is a standard class those methods should be as they are as
developed by Sun. The user can not be permitted to change the functionality of those
methods. If your application needs this type of situation u can decalre your class as
final.

The user can't implement the method toUppercase( ) in String class as that it can
convert only some of the characters into Uppercase.

Question: 1)What is the difference between Throw & Throws?


2)Expain the use of tansient variable with example?

a) when we are using thows when exception coms thatperticular exceptions handle
by JVM.

using throw you can throw the perticular exception.

like:

try {
//..

}catch(xxException e) {
//..
throw new xxxException("xxx");
}catch(Excepiton ee) {
//..
}finally {
try {
//..
}catch(xxException eee) {
//..
}
}

9
Interview Questions: JSP

You use the Transient keyword to indicate to the Java virtual machine that the
indicated variable is not part of the persistent state of the object.

when your serialization that object it can't persistent that value

b) hi there,throws::::(DECLARATION) the way we decalre that exception might


occur...... it is a caution to the JVM so that it prepares to handle the
Exceptionthrow::::: if at any stage of coding we r sure that an exception might occur
and unfortunately if we donot know how to handle that exception then we THROW
the Exception....... so here by we make sure the control is in our
handtransient::::During the process of serialization if u donot want a particular
variable to be serialized then we make that variable TRANSIENT

what is the difference between servlet config and servlet context?

a) Servlet context is used for the persistency of the data for the servlets within the
same web application or within the same servlet engine.

So a particular data is common for all servlets sharing the same web application.

Whereas the servlet config is used to use a particular data for each servlet.

Other servlet in the web application cannot access the data obtained by servlet
config of other user. Servlet config is used to access the data for itself. Other servlet
cant access others servlet config data.

b) A servlet configuration object used by a servlet container used to pass information


to a servlet during initialization.

Servlet context is used to communicated within web container. There is one servlet
context per Application per JVM. Servlet Context is part of ServletConfig.

ServletContext = ServletConfig.getServletContext()

Waht is Request Dispatcher?explaim with application?

rRequest dispatcher whis communciate dirctecly communicate with data which page
destination page .

10
Interview Questions: JSP

example:

ServletContext sc=getServletContext();

RequestDipatcher rc =sc.getRequestDispatcher("1.jsp");

rc.forward(req,res);

here u'r

1.jsp is u'r destntion page

one more think i would u that first

senRedirect() this method which time delay control goes to browser and it again go
to destination page.that is the difference b/e sendRedirect and Requestdispatcher

Question: Which one you will use as key in java.util.HaspMap

a. int a =5;

b. new Object();

c. new Integer(“5”);

d. new Character(‘C’);

HashMap allows any object as a key .So b, c and d are correct.

Question: what will happen when u attempt to compile and run the below
code.

int a = (int) Math.random();

a.0

11
Interview Questions: JSP

b.1

c. compilation fails

d. 0 to Ineteger.MAX_VALUE

3. which two are used to declare the boolean primitive

a. boolean b =0;

b. boolean b = Boolean.TRUE;

c. boolean b = true;

d. boolean b = (3>=0);

4. What is the O/P?

class A

Void get()

Sysout(“A”);

Class B extends A

Void get()

Sysout(“B”);

12
Interview Questions: JSP

Public static void main(String ars[])

A a = new A();

B b = (B) a;

b.get();

a. compilation fails

b. run time exception

c. A

d. B

5. Which two cause a compiler error? (Choose two)

A. float[] = new float(3);

B. float f2[] = new float[];

C. float[] f1 = new float[3];

D. float f3[] = new float[3];

E. float f5[] = { 1.0f, 2.0f, 2.0f };

F. float f4[] = new float[] { 1.0f, 2.0f, 3.0f};

6. Given:

package test1;

13
Interview Questions: JSP

public class Test1

static int x = 42;

package test2;

public class Test2 extends test1.Test1

public static void main(String[] args) {

System.out.println(“x = “ + x);

What is the result?

A. x = 0

B. x = 42

C. Compilation fails because of an error in line 2 of class Test2.

D. Compilation fails because of an error in line 3 of class Test1.

E. Compilation fails because of an error in line 4 of class Test2.

7.

class TestSuper {

TestSuper(int i) { }

class TestSub extends TestSuper{ }

class TestAll {

14
Interview Questions: JSP

public static void main (String [] args) {

new TestSub();

Which is true?

A. Compilation fails.

B. The code runs without exception.

C. An exception is thrown at line 7.

D. An exception is thrown at line 2.

8. O/P?

String s =”abcde”;

Object obj = (Object) s;

If(s.equals(obj))
{
Sysout(“Equal 1”);
}

If(obj.equals(s))

Sysout(“Equal 2”);

a. compilation fails

b. runtime exception

c. Equal 1 Equal 2

9. When is the Float object, created in line 11, eligible for garbage
collection?

15
Interview Questions: JSP

public Object m() {

Object o = new Float(3.14F);

Object [] oa = new Object[1];

oa[0] = o;

o = null;

oa[0] = null;

print 'return

A. Just after line 13.

B. Just after line 14.

C. Just after line 15.

D. Just after line 16 (that is, as the method returns).

10. What is the result?

public class Test {

public static void main(String[] args) {

int x = 0;

assert (x > 0): “assertion failed”;

System.out.println(“finished”);

A. finished

B. Compilation fails.

C. An AssertionError is thrown.

D. An AssertionError is thrown and finished is output.

16
Interview Questions: JSP

a) 1. 0
3. b
4. compliation fails (a)
5. only A
6. b
7. b.
8.c
10. B

b) Answers to these questions should be:


3. b,c
5. A,B
6. Compilation Fail
7. A
10. C

Any dought reply to this post or mail me directly at jssaggu@gmail.com

17

Вам также может понравиться