Q) What is a "Singleton" class - DOC SERVE

grapedraughtΛογισμικό & κατασκευή λογ/κού

2 Δεκ 2013 (πριν από 3 χρόνια και 6 μήνες)

72 εμφανίσεις


Page
1







Core Java


Q) What is difference between Java and C++?

A) (i) Java does not support pointers. Pointers are inherently insecure and troublesome. Since pointers do not exist in
Java. (ii) Java does not support operator overloading. (iii) Java does not
perform any automatic type conversions that
result in a loss of precision (iv) All the code in a Java program is encapsulated within one or more classes. Therefore,
Java does not have global variables or global functions. (v) Java does not support multiple

inheritance.

Java does not support destructors, but rather, add the finalize() function. (vi) Java does not have the delete operator.
(vii) The << and >> are not overloaded for I/O operations


Q)
OOPs concepts

Polymorphism

Ability to take more than one fo
rm, in java we achieve this using Method Overloading (compile time polymorphism),
Method overriding (runtime polymorphism)


Inheritance

Is the process by which one object acquires the properties of another object. The advantages of inheritance are
reusabil
ity of code and accessibility of variables and methods of the super class by subclasses.



Encapsulation

Wrapping of data and function into a single unit called encapsulation. Ex:
-

all java programs.

(Or)

Nothing but data hiding, like the variables declare
d under private of a particular class are accessed only in that class
and cannot access in any other the class. Or Hiding the information from others is called as Encapsulation. Or
Encapsulation is the mechanism that binds together code and data it manipul
ates and keeps both safe from outside
interference and misuse.


Abstraction

Nothing but representing the essential futures without including background details.


Dynamicbinding


Code associated with a given procedural call is not known until the time of th
e call at runtime. Dynamic binding
is nothing but late binding.


Q) class & object?


class


class is a blue print of an object


Object



instance of class.


Q)
Object creation?


Object is constructed either on a memory heap or on a stack.

Mem
ory heap

Generally the objects are created using the
new

keyword. Some heap memory is allocated to this newly created
object. This memory remains allocated throughout the life cycle of the object. When the object is no more referred,
the memory allocated t
o the object is eligible to be back on the heap.

Stack

During method calls, objects are created for method arguments and method variables. These objects are created
on stack.


Q)
System.out.println()




println() is a methd of java.io.printWriter.





“out” is an instance variable of java.lang.System class.


Q)
Transient

&
volatile

Transient
--
>
The transient modifier applies to variables only,

the object are variable will not persist.
Transient
variables are not serialized.


Volatile
--
> value
will be changed unexpectedly by the other part of the program,

"it tells the compiler a variable may
change asynchronously due to threads"


Q)

Access Specifiers & Access modifiers?

Access Specifiers



A.S gives access privileges to outside of applicatio
n

(or)
others
,
they are

Public, Protected,
Private, Defaults.


Page
2

Access Modifiers


A⹍.睨wc栠hiv敳⁡ 摩tio湡l敡湩湧⁴ ⁤ t愬am整e潤s⁡湤⁣l慳s敳Ⱐ,i湡l⁣慮湯琠扥潤ifi敤⁡ 慮y
灯i湴n潦⁴ m攮



Private

Public

Protected

No modifier

Same class

No

Yes

Yes

Yes

Same package Subclass

No

Yes

Yes

Yes

Same package non
-
subclass

No

Yes

Yes

Yes

Different package subclass

No

Yes

Yes

No

Different package non
-
subclass

No

Yes

No

No


Q)
Default Values



long

-
2^63 to 2^63

1


0L

double

0.0d

Int

-
2^31 to 2^31

1


0

float

0.0f

Short

-
2^15 to 2^15

1


0

Boolean

false

Byte

-
2^7 to 2^7

1


0

char

0 to 2^7

1


null character (or) ‘
\
u 0000’



Q)
Byte code

&
JIT compiler

&
JVM

&
JRE
&
JDK



Byte code is a highly optimized set of instructions. JVM is an

interpreter for byte code. Translating a java program
into byte code helps makes it much easier to run a program in a wide variety of environment.



JVM is an interpreter for byte code



JIT (Just In Time) is a part of JVM, it compiles byte code into ex
ecutable code in real time, will increase the
performance of the interpretations.



JRE
is an implementation of the Java Virtual Machine, which actually executes Java programs.



JDK is bundle of software that you can use to develop Java based software, To
ols provided by JDK is

(i) javac


compiler

(ii) java


interpretor

(iii) jdb


debugger

(iv) javap
-

Disassembles

(v) appletviewer


Applets

(vi) javadoc
-

documentation generator

(vii) javah
-

'C' header file generator


Q)
Wrapper classes

Primitive data
types can be converted into objects by using wrapper classes. These are java.lang.package.


Q) Does Java pass method arguments by value or by reference?

Java passes all arguments by value, not by reference


Q)
Arguments

&
Parameters

While defining method,
variable passed in the method are called parameters. While using those methods, values
passed to those variables are called arguments.


Q)
Public static void main (String [] args)



We can overLoad the main() method.



What if the main method is declared a
s “
Private
”?


The program compiles properly but at runtime it will give "Main method not public." Message



What if the static modifier is removed from the signature of the main method?


Program compiles. But at runtime throws an error "NoSuchMethodE
rror".



We can write “
static public void
” instead of “
public static void
” but not “
public void static
”.



Protected
static void main(), static void main(), private static void main()
are also valid.




If I do not provide the String array as the argument
to the method?


Program compiles but throws a runtime error "NoSuchMethodError".



If no arguments on the command line, String array of Main method will be empty or null?


It is empty. But not null.



V
ariables can have the same name as a method or a

class


Q)

Can an application have multiple classes having main() method?

A) Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main
method only in the class whose name you have mentioned. Henc
e there is not conflict amongst the multiple classes
having main method.


Q)
Can I have multiple main methods in the same class?

A) No the program fails to compile. The compiler says that the main method is already defined in the class.



Page
3

Q)
Constructor


Th
e automatic initialization is performed through the constructor, constructor has same name has class name.
Constructor has no return type not even void. We can pass the parameters to the constructor. this() is used to invoke a
constructor of the same class
. Super() is used to invoke a super class constructor. Constructor is called immediately
after the object is created before the new operator completes.




C
onstructor
can use

the access modifiers
public, protected, private

or
have no access modifier




䍯C
s瑲畣瑯爠
can not

use the modifiers
abstract, static, final, native, synchronized

or
strictfp



Constructor
can be

overloaded
, we
cannot override
.



You cannot use
this()
and
Super()

in the same constructor.


Class A(

A(){


System.out.println(“hello”);

}}


Class B extends A {

B(){


System.out.println(“friend”);

}}


Class print {

Public static void main (String args []){

B b = new B();

}

o/p:
-

hello friend


Q) Diff
Constructor

&
Method


Constructor

Method

Use to instance of a class

Grouping java stat
ement

No return type

Void (or) valid return type

Same name as class name

As a name except the class method name, begin with
lower case.

“This”
refer to another constructor in the same
class

Refers to instance of class

“Super”
to invoke the super class
constructor

Execute an overridden method in the super class


䥮f敲楴慮捥
” cannot be inherited

Can be inherited

We can “
overload”

but we cannot “
ov敲r楤i敮


Can be inherited

Will automatically invoke when an object is created

Method has called explicitly


Q)

Garbage collection


G.C is also called automatic memory management as JVM automatically removes the unused variables/objects
(value is null) from the memory. User program cann't directly free the object from memory, instead it is the job of the
garba
ge collector to automatically free the objects that are no longer referenced by a program. Every class inherits
finalize()

method from
java.lang.Object
, the finalize() method is called by garbage collector when it determines no
more references to the objec
t exists. In Java, it is good idea to explicitly assign
null

into a variable when no more in use,
calling
System.gc()

and
Runtime.gc(),
JVM tries to recycle the unused objects, but there is no guarantee when all the
objects will garbage collected. Garbage
collection is a

low
-
priority thread.


G.C is a low priority thread in java, G.C cannot be forced explicitly. JVM may do garbage collection if it is running short
of memory. The call System.gc() does NOT force the garbage collection but only suggests that t
he JVM may make an
effort to do garbage collection.


Q)
How an object becomes eligible for Garbage Collection?

A) An object is eligible for garbage collection when no object refers to it, An object also becomes eligible when its
reference is set to null.
The objects referred by method variables or local variables are eligible for garbage collection
when they go out of scope.

Integer i = new Integer(7);

i =
null;



Page
4

Q)
Final, Finally, Finalize

Final:
-

When we declare a sub class a final the compiler will gi
ve error as “cannot subclass final class” Final to prevent
inheritance and method overriding. Once to declare a variable as final it cannot occupy memory per instance basis.






Final class cannot have static methods






Final class cannot have a
bstract methods (
Because of final class never allows any class to inherit it)




Final class can have a final method.


Finally:
-

Finally create a block of code that will be executed after try catch block has completed.

Finally block will
execute whet
her or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch
statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an
uncaught exception or an exp
licit return statement, the finally clause is also execute.





Using System.exit() in try block will not allow finally code to execute


Finalize:
-

some times an object need to perform some actions when it is going to destroy, if an object holding some

non
-
java resource such as file handle (or) window character font, these resources are freed before the object is going to
destroy.


Q)

Can we declare abstract method in final class?

A) It indicates an error to declare abstract method in final class. Becau
se of final class never allows any class to inherit
it.


Q) Can we declare final method in abstract class?

A) If a method is defined as final then we can’t provide the reimplementation for that final method in it’s derived classes
i.e overriding is not pos
sible for that method. We can declare final method in abstract class suppose of it is abstract too,
then there is no used to declare like that.


Q)
Superclass

&
Subclass


A super class is a class that is inherited whereas subclass is a class that does the

inheriting


Q) How will u implement 1) polymorphism 2) multiple inheritance 3) multilevel inheritance in java?

A)
Polymorphism


overloading and overriding



Multiple inheritances


interfaces.


Multilevel inheritance


extending class.


Q) Overloading & Overriding?

Overloading (Compile time polymorphism)


Define t
wo or more methods within the same class (or) subclass that share the

same name

and their
number
of parameter
,
order of parameter & return type
are different then the methods ar
e said to be overloaded.



Overloaded methods do not have any restrictions on what
return type of Method (
Return type

are different
)

(or)

exceptions
can be thrown. That is something to worry about with overriding.




Overloading is used while implementing

several methods that implement similar behavior but for different data
types.


Overriding (Runtime polymorphism)

When a method in a subclass has the
same name, return type & parameters

as the method in the super
class then the method in the subclass is ov
erride the method in the super class.




The
access modifier

for the overriding method may not be more restrictive than the access modifier of the
superclass method.




If the superclass method is
public
, the overriding method must be
public
.



If the sup
erclass method is
protected
, the overriding method may be
protected

or
public
.



If the superclass method is
package
, the overriding method may be
packagage
,
protected
, or
public
.



If the superclass methods is
private
, it is
not inherited

and overriding i
s not an issue.



Methods declared as
final

cannot be overridden.




The
throws

clause of the overriding method may only include exceptions that can be thrown by the superclass
method, including its subclasses.




Page
5



Only member method can be overriden, n
ot member variable



class Parent{


int i = 0;


void amethod(){




System.out.println("in Parent");




}


}



class Child extends Parent{


int i = 10;


void amethod(){




System.out.println("in Child");


}

}



class Test{

public static void main(String[] args){

Parent p = new Child();

Child c = new Child();

System.out.print("i="+p.i+" ");

p.amethod ();

System.out.print("i="+c.i+" ");

c.amethod();

}

}

o/p
:
-

i=0 in Child


i=10 in Child


Q) Final

variable


Once to declare a variable as final it cannot occupy memory per instance basis.


Q)
Static block


Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the
main method the static block will

be

execute.


Q)
Static variable & Static method

Static variables & methods are instantiated only once per class. In other words they are class variables, not
instance variables. If you change the value of a static variable in a particular object, the value

of that variable changes
for all instances of that class.

Static methods can be referenced with the name of the class. It may not access the instance variables of that
class, only its static variables. Further it may not invoke instance (non
-
static) meth
ods of that class unless it provides
them with some object.




When a member is declared a static it can be accessed before any object of its class are created.



Instance variables declared as static are essentially global variables.



If you do not speci
fy an initial value to an instance & Static variable a default value will be assigned automatically.



Methods declared as static have some restrictions they can access only static data, they can only call other
static data, they cannot refer
this

or
super
.



Static methods cant be overriden to non
-
static methods.



Static methods is called by the static methods only, an ordinary method can call the static methods, but static
methods cannot call ordinary methods.



Static methods are implicitly

"final", because overriding is only done based on the type of the objects



They cannot refer “this” are “super” in any way.


Q) C
lass variable

&
Instance variable

&
Instance methods

&
class methods

Instance variable



variables defined inside a class a
re called instance variables with multiple instance of class, each
instance has a variable stored in separate memory location.


Class variables


you want a variable to be common to all classes then we crate class variables. To create a class
variable put
the “static” keyword before the variable name.


Class methods


we create class methods to allow us to call a method without creating instance of the class. To
declare a class
method uses

the “static” key
word.



Page
6

Instance methods



we define a method in a c
lass, in order to use that methods we need to first create objects of the
class.


Q) Static methods cannot access instance variables why?


Static methods can be invoked before the object is created; Instance variables are created only when the new
object
is created. Since there is no possibility to the static method to access the instance variables. Instance variables
are called called as non
-
static variables.


Q)
String

&
StringBuffer


String is a fixed length of sequence of characters, String is immutabl
e

object
.




StringBuffer represent growable and writable character sequence, StringBuffer is mutable which means that its
value can be changed. It allocates room for 16
-
addition character space when no specific length is specified.
Java.lang.StringBuffer
is also a final class hence it cannot be sub classed. StringBuffer cannot be overridden the
equals() method.


Q)
Conversions


String to Int Conversion
:
-



int I = integer.valueOf(“24”).intValue();





int x = integer.parseInt(“433”);





float f = float.valueOf(23.9).floatValue();




Int to String Conversion :
-




String arg = String.valueOf(10);


Q)
Super()


Super() always calling the constructor of immediate super class, super() must always be the first statements
executed inside a subclass constructor.


Q)

What are different types of inner classes?

A)

Nested top
-
level classes
-

If you declare a class within a class and specify the static modifier, the compiler treats the
class just like any other top
-
level class. An
y class outside the declaring class accesses the nested class with the
declaring class name acting similarly to a package. e.g., outer.inner. Top
-
level inner classes implicitly have access only
to static variables. There can also be inner interfaces. All o
f these are of the nested top
-
level variety.


Member classes

-

Member inner classes are just like other member methods and member variables and access to the
member class is restricted, just like methods and variables. This means a public member class acts

similarly to a nested
top
-
level class. The primary difference between member classes and nested top
-
level classes is that member classes
have access to the specific instance of the enclosing class.


Local classes

-

Local classes are like local variables,
specific to a block of code. Their visibility is only within the block
of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more
publicly available interface. Because local classes are not mem
bers the modifiers public, protected, private and static
are not usable.


Anonymous classes

-

Anonymous inner classes extend local inner classes one level further. As anonymous classes
have no name, you cannot provide a constructor.




Inner class inside
method cannot have static members or blocks


Q) Which circumstances you use Abstract Class & Interface?

--
> If you need to change your design make it an interface.

--
> Abstract class provide some default behaviour, A.C are excellent candidates inside of ap
plication framework. A.C
allow single inheritance model, which should be very faster.


Q)
Abstract Class


Any class that contain one are more abstract methods must also be declared as an abstract, there can be no
object of an abstract class, we cannot dire
ctly instantiate the abstract classes. A.C can contain concrete methods.


Any⁳u戠bl慳s ⁡ A扳瑲慣琠tl慳s畳琠ti瑨tr⁩m灬em敮琠tll⁴ 攠e扳瑲慣琠t整e潤s⁩渠n桥⁳u灥r⁣l慳s爠 攠摥cl慲a搠
i瑳敬f⁡ ⁁扳瑲慣琮



Compile time error occur if an attempt to c
reate an instance of an Abstract class.


Page
7



You cannot declare “abstract constructor” and “abstract static method”.



A
n “
abstract method
” also declared
private, native, final, synchronized, strictfp, protected.



Abstract class can have
static, final

method

(but there is no use).



Abstract class have visibility
public, private, protected
.



By default the methods & variables will take the access
modifiers is <default>
, which is accessibility as package.



An
abstract

method declared in a non
-
abstract class.



An abstract class can have instance methods that implement a default behavior.



A class can be declared
abstract

even if it does not actually have any
abstract

methods. Declaring such a class
abstract

indicates that the implementation is somehow incom
plete and is meant to serve as a super class for one or
more subclasses that will complete the implementation.



A class with an abstract method. Again note that the class itself is declared
abstract
, otherwise a compile time error
would have occurred.


Ab
stract class A{


Public abstract callme();


Void callmetoo(){


}

}


class B extends A(


void callme(){


}

}


class AbstractDemo{

public static void main(string args[]){


B b = new B();


b.callme();


b.callmetoo();

}

}


Q) When we use Abstract class?

A)
Let

us take the behaviour of animals, animals are capable of doing different things like flying, digging,

Walking. But these are some common operations performed by all animals, but in a different way as well. When an
operation is performed in a different wa
y it is a good candidate for an abstract method.


Public Abstarctclass Animal{


Public void eat(food food) {


}


public void sleep(int hours) {


}


public abstract void makeNoise()

}


public Dog extends Animal

{


public void makeNoise() {



System
.out.println(“Bark! Bark”);


}

}


public Cow extends Animal

{


public void makeNoise() {



System.out.println(“moo! moo”);


}

}





Page
8


Q)
Interface



Interface is similar to class but they lack instance variable, their methods are declared with out an
y body.
Interfaces are designed to support dynamic method resolution at run time. All methods in interface are implicitly

abstract
, even if the
abstract

modifier is omitted. Interface methods have no implementation;


Interfaces are useful for?

a) Declari
ng methods that one or more classes are expected to implement

b) Capturing similarities between unrelated classes without forcing a class relationship.

c) Determining an object's programming interface without revealing the actual body of the class.


Why In
terfaces?

“ one interface multiple methods “ signifies the polymorphism concept.




Interface has visibility
public.



䥮I敲e慣攠e慮⁢ ⁥ 瑥湤e搠d im灬敭敮瑥t.



A
渠n湴nrf慣攠eodyay⁣潮瑡i渠no湳瑡t琠摥cl慲慴a潮sⰠ,扳瑲慣琠t整e潤⁤ cl慲慴i潮sⰠi湮敲⁣l慳s
敳⁡ 搠d湮敲e
i湴nrf慣敳.



All
methods
of an interface are implicitly
Abstract
,
P
ublic
, even if the
public

modifier is omitted.



An interface
methods

cannot be declared
protected,

private
,
strictfp, native

or
synchronized
.



All
Variables
are implicitly
final, public, static fields.



A compile time error occurs if an interface has a simple name the same as any of it's enclosing classes or interfaces.



A渠nn瑥牦慣攠e慮湬y⁤ecl慲攠a潮s瑡湴n⁡ 搠d湳瑡tc攠e整e潤sⰠ,畴uca湮潴oim灬敭敮琠t敦慵l琠扥h慶i潲o



top
-
level

interfaces may only be declared
public,
inner interfaces may be declared
private

and
protected

but only if
they are defined in a class.




A⁣l慳s⁣慮湬y 數瑥td 潮攠潴o敲⁣l慳s.



A⁣l慳say im灬敭敮瑳潲攠瑨o渠nn攠e湴nrf慣攮



䥮I敲e慣攠e慮
數瑥湤潲攠瑨on 攠e湴nrf慣攮


Interface A

{


final static float pi = 3.14f;

}


class B implements A

{


public float compute(float x, float y) {



return(x*y);


}

}


class test{

public static void main(String args[])

{


A a = new B();


a.compute();

}

}



Q) Diff Interface & Abstract Class?



A.C may have some executable methods and methods left unimplemented. Interface contains no implementation
code.



An A.C can have nonabstract methods. All methods of an Interface are abstract.



An A.C can have instan
ce variables. An Interface cannot.



An A.C must have subclasses whereas interface can't have subclasses



An A.C can define constructor. An Interface cannot.



An A.C can have any visibility: public, private, protected. An Interface visibility must be pub
lic (or) none.



An
A.C

can have instance methods that implement a default behavior. An Interface can only declare constants and
instance methods, but cannot implement default behavior.



Page
9

Q)
What is the difference between Interface and class?



A class has
instance variable and an Interface has no instance variables.



Objects can be created for classes where as objects cannot be created for interfaces.



All methods defined inside class are concrete. Methods declared inside interface are without any body.


Q) What is the difference between Abstract class and Class?



Classes are fully defined. Abstract classes are not fully defined (incomplete class)



Objects can be created for classes, there can be no objects of an abstract class.


Q)

What are some alterna
tives to inheritance?


A)

Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an
instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to

think
about each message you forward, because the instance is of a known class, rather than a new class, and because it
doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make
sense. On the other h
and, it makes you write more code, and it is harder to re
-
use (because it is not a subclass).


Q)

Serializable

&

Externalizable

Serializable
--
> is an interface that extends serializable interface and sends data into streams in compressed
format. It has
2 methods
writeExternal(objectOutput out), readExternal(objectInput in).


Externalizable


is an Interface that extends Serializable Interface. And sends data into Streams in
Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExt
ernal(ObjectInput in)


Q)
Internalisation

&
Localization


Internalisation
--

Making a programme to flexible to run in any locale called internalisation.


Localization
--

Making a programme to flexible to run in a specific locale called Localization.


Q
)
Serialization


Serialization is the process of writing the state of the object to a byte stream, this is useful when ever you want
to save the state of your programme to a persistence storage area.



Q)
Synchronization


Synchronization is a p

rocess of c
ontrolling the access of shared resources by the multiple threads in such a
manner that only one thread can access one resource at a time.
(Or)

When 2 are more threads need to access the
shared resources they need to some way ensure that the resources will

be used by only one thread at a time. This
process which is achieved is called synchronization.


(i) Ex:
-

Synchronizing a function:

public synchronized void Method1 () {

}


(i) Ex:
-

Synchronizing a block of code inside a function:

public myFunction (){


synchronized (this) {



}

}


(iii) Ex:
-

public Synchronized void main(String args[])


But this is not the right approach because it means servlet can handle one request at a time.


(iv) Ex:
-

public Synchronized void service()


Servlet handle

one request at a time in a
serialized manner


Q) Different level of locking using Synchronization?

A)
Class level, Object level, Method level, Block level


Q)
Monitor


A monitor is a mutex, once
a thread enters

a monitor, all other threads must wait until

that thread exist the
monitor.



Page
10

Q) Diff = = and .equals()?

A)

==


Compare object references whether they refer to the sane instance are not.


equals ()


method compare the characters in the string object.



StringBuffer sb1 = new Str
ingBuffer("Amit");


StringBuffer sb2= new StringBuffer("Amit");


String s1 = "Amit";


String s2 = "Amit";


String s3 = new String("abcd");


String s4 = new String("abcd");


String ss1 = "Amit";



(sb1==sb2);


F

(sㄮ1煵als(s㈩2㬠


T

(s戱.
敱u慬s(s戲))㬠


F

((sㄽ=s㈩2㬠


T

(s戱⹥.u慬s(ssㄩ1㬠


F

(s㌮3煵als(s㐩4㬠


T


((s㌽=s㐩4㬠


F



String s1 = "abc";


String s2 = new String("abc");


s1 == s2


F


s1.equals(s2))


T



Q)
Marker Interfaces (or) Tagged Interfaces

:
-


An Inte
rface with no methods. Is called marker Interfaces, eg. Serializable, SingleThread Model, Cloneable.


Q)
URL Encoding

&
URL Decoding



URL Encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex
Characters

and URL Decoding is the reverse process converting all Hex Characters back their normal form.


Q)
URL

&
URLConnection


URL is to identify a resource in a network, is only used to read something from the network.

URL url = new URL(protocol name, host name,

port, url specifier)


URLConnection can establish communication between two programs in the network.


URL hp = new URL(“www.yahoo.com”);


URLConnection con = hp.openConnection();


Q)
Runtime class



Runtime class encapsulate the run
-
time environment. You
cannot instantiate a
Runtime
object. You can get a
reference to the current Runtime object by calling the static method
Runtime.getRuntime()


Runtime r = Runtime.getRuntime()

Long mem1;

Mem1 = r.freeMemory();

Mem1 = r.totalMemory();


Q)
Execute other prog
rams


You can use java to execute other heavy weight process on your multi tasking operating system, several form
of exec() method allow you to name the programme you want to run.


Runtime r = Runtime.getRuntime();


Process p = null;


Try{



p = r.exce(“no
tepad”);



p.waiFor()



}


Q)
System class



System class hold a collection of static methods and variables. The standard input, output, error output of the
java runtime are stored in the
in, out, err
variables.



Page
11

Q)
Native Methods


Native methods are u
sed to call subroutine that is written in a language other than java, this subroutine exist as
executable code for the CPU.


Q)
Cloneable Interface


Any class that implements the cloneable interface can be cloned, this interface defines no methods. It is u
sed to
indicate that a class allow a bit wise copy of an object to be made.


Q)
Clone


Generate a duplicate copy of the object on which it is called. Cloning is a dangerous action.


Q)
Comparable Interface


Classes that implements comparable contain object
s that can be compared in some meaningful manner. This
interface having one method compare the invoking object with the object. For sorting comparable interface will be used.

Ex:
-

int compareTo(Object obj)



Q)
Class


Class encapsulate the run
-
time state o
f an object or interface. Methods in this class are


static Class forName(String name) throws
ClassNotFoundException

getClass()

getClassLoader()

getConstructor()

getField()

getDeclaredFields()

getMethods()

getDeclearedMethods()

getInterface()

getSuper
Class()


Q)
java.jlang.Reflect (package)


Reflection is the ability of software to analyse it self, to obtain information about the field, constructor, methods
& modifier of class. You need this information to build software tools that enables you to work

with java beans
components.


Q)
InstanceOf


Instanceof means by which your program can obtain run time type information about an object.

Ex:
-

A a = new A();


a.instanceOf A;


Q) Java pass arguments by value are by reference?

A)
By value


Q) Java lac
k pointers how do I implements classic pointer structures like linked list?

A)
Using object reference.


Q)
java. Exe

Micro soft provided sdk for java, which includes “jexegentool”. This converts class file into a “.Exec” form. Only
disadvantage is user ne
eds a M.S java V.M installed.


Q) Bin & Lib in jdk?

Bin contains all tools such as javac, appletviewer and awt tool.

Lib contains API and all packages.














Page
12





Collections Frame Work



Q)


Collection classes

Collection Interfaces

Legacy classes

L
egacy interface

Abstract collection

Collection

Dictionary

Enumerator

Abstract List

List

Hash Table


Abstract Set

Set

Stack


Array List

Sorted Set

Vector


Linked List

Map

Properties


Hash set

Iterator



Tree Set




Hash Map




Tree Map




Abstrac
t Sequential List






Collection Classes



Abstract collection


Implements most of the collection interfaces.




Abstract List


Extends Abstract collection & Implements List Interface. A.L allow “random access”.


Methods>> void add

(int

index,
Object

element), boolean
add
(
Object

o), boolean
addAll
(
Collection

c),

boolean
addAll
(int

index,
Collection

c), Object remove(int index), void clear(), Iterator iterator().



Abstract Set


Extends Abstract collection & Implements Set interface.


Array List


Array
List extends AbstractList and implements the List interface. ArrayList is a variable length of
array of object references, ArrayList support dynamic array that grow as needed. A.L allow rapid random access to
element but slow for insertion and deletion
from the middle of the list. It will
allow duplicate elements.
Searching is
very faster.

A.L internal node traversal from the start to the end of the collection is significantly faster than Linked List traversal.




A.L

is a replacement for
Vector.



Meth
ods>>void add

(int

index,
Object

element), boolean
add
(
Object

o), boolean
addAll
(
Collection

c),

boolean
addAll
(
int

index,
Collection

c), Object remove(int index), void clear(), object get(int index), int indexOf(Object
element), int latIndexOf(Object eleme
nt), int size(), Object [] toArray().



Linked List


Extends AbstactSequentialList and implements List interface. L.L provide optimal sequence access,
in expensive insertion and deletion from the middle of the list, relatively slow for random access. Whe
n ever there is
a lot of
insertion & deletion

we have to go for L.L. L.L is accessed via a reference to the first node of the list. Each
subsequent node is accessed via a reference to the first node of the list. Each subsequent node is accessed via the
lin
k
-
reference number stored in the previous node.



Methods>> void addFirst(Object obj), addLast(Object obj), Object getFirst(), Object getLast(),void add

(int

index,
Object

element), boolean
add
(
Object

o), boolean
addAll
(
Collection

c),

boolean
addAll
(int

index,
Collection

c), Object
remove(int index), Object remove(Object o), void clear(), object get(int index), int indexOf(Object element), int
latIndexOf(Object element), int size(), Object [] toArray().


Hash Set


Extends AbstractSet & Implements Set int
erface, it creates a collection that uses HashTable for
storage, H.S does not guarantee the order of its elements, if u need storage go for TreeSet. It will not allow
duplicate elements




Methods>>boolean add(Object o), Iterator iterator(), boolean remove
(Object o), int size().


Tree Set


Extends Abstract Set & Implements Set interface. Objects are stored in sorted, ascending order.
Access and retrial times are quite fast. It will not allow duplicate elements


Page
13



Methods>> boolean add(Object o),
boolean
addAll
(
Collection

c), Object first
(), Object last(), Iterator iterator(),
boolean remove(Object o).


Hash Map


Extends Abstract Map and implements Map interface. H.M does not guarantee the order of elements,
so the order in which the elements are added to a H.M is not necessary the order
in which they are ready by the
iterate. H.M permits
only one null values
in it while H.T does not






HashMap

is similar to
Hashtable
.



Tree Map


implements Map interface, a TreeMap provides an efficient means of storing key/value pairs in sorted
order
and allow
rapid retrieval
.




Abstract Sequential List


Extends Abstract collection; use sequential access of its elements.


Collection Interfaces




Collection


Collection is a group of objects, collection
does not allow duplicate

elements.



M
ethods >> boolean add(Object obj), boolean addAll(c), int Size(), Object[] toArray(), Boolean isEmpty(), Object []
toArray(), void clear()
.
Collection c), Iterator iterator(),

boolean remove(Object obj), boolean removeAll(Collection


Exceptions >> UnSuppor
tedPointerException, ClassCastException.


List


List will extend Collection Interface, list stores a
sequence of elements

that
can contain

duplicates
,
elements can be accessed their position in the list using a zero based index, (
it can access objects by

index
).


Methods >> void add(int index, Object obj), boolean addAll(int index, Collection c), Object get(int index), int
indexOf(Object obj), int lastIndexOf(Object obj), ListIterator iterator(), Object remove(int index), Object
removeAll(
Collection c
),
Object set(int index, Object obj).



Set


Set

will extend Collection Interface, Set cannot contain duplicate elements. Set stored elements in an
unordered way. (
it can access objects by value
).




Sorted Set


Extends Set

to handle sorted sets, Sorted S
et elements will be in ascending order.


Methods >> Object last(), Object first(), compactor compactor().


Exceptions >> NullPointerException, ClassCastException, NoSuchElementException.



Map


Map maps unique key to value in a map for every key ther
e is a corresponding value and you will lookup the
values using keys. Map
cannot contain duplicate

“key” and “value”. In map both the “
key
” & “
value

are objects
.



Methods >>

Object
get(
Object k
),
Object
put(
Object k, Object v
),
int size(), remove(O
bject object), boolean
isEmpty()


Iterator


Iterator

makes it easier to traverse through the elements of a collection. It also has an extra feature not
present in the older Enumeration interface
-

the ability to
remove elements
. This makes it easy to per
form a search
through a collection, and strip out unwanted entries.


Before accessing a collection through an iterator you must obtain one if the collection classes provide an
iterator()

method

that returns an iterator to the start of the collection. By us
ing iterator object you can access each
element in the collection, one element at a time.


Methods >> boolean hasNext(), object next(),void remove()


Ex:
-

ArayList arr = new ArrayList();



Arr.add(“c”);




Iterator itr = arr.iterator();



While(itr.hash
Next())



{



Object element = itr.next();



}


Page
14



List Iterator


List Iterator gives the ability to access the collection, either forward/backward direction



Legacy Classes



Dictionary


is an abstract class that represent key/value storage reposito
ry and operates much like “Map” once
the value is stored you can retrieve it by using key.



Hash Table


HashTable stores key/value pairs in hash table, HashTable is
synchronized

when using hash table
you have to specify an
object that is used as a key
, a
nd the value that you want to linked to that key. The key is
then hashed, and the resulting hash code is used as the index at which the value is stored with the table. Use H.T
to store large amount of data, it will search as fast as vector. H.T store the d
ata in sequential order.


Methods>> boolean containsKey(Object key), boolean containsValue(Object value), Object get(Object key), Object
put(Object key, Object value)


Stack


is a sub class of vector, stack includes all the methods defined by vector and a
dds several of its own.



Vector


Vector holds any type of objects, it is not fixed length and vector is
synchronized
. We can
store
primitive data types as well as objects
. Default length of vector is up to 10.


Methods>> final void addElement(Object elem
ent), final int size(), final int capacity(), final boolean
removeElementAt(int index), final void removeAllElements().


Properties


is a subclass of HashTable, it is used to maintain the list of values in which
the
“key/value” is
String.



Legacy Interfa
ces



Enumeration


Define methods by which you can enumerate the elements in a collection of objects. Enumeration
is synchronized.

Methods>>

hasMoreElements(),Object nextElement().


Q) Which is the preferred collection class to use for storing databa
se result sets?

A)

LinkedList is the best one, benefits include:

1. Retains the original retrieval order. 2. Has quick insertion at the head/tail 3. Doesn't have an internal size limitation
like a Vector where when the size is exceeded a new internal stru
cture is created. 4. Permits user
-
controlled
synchronization unlike the pre
-
Collections Vector which is always synchronized

ResultSet result = stmt.executeQuery("...");

List list = new LinkedList();

while(result.next()) {



list.add(result.getString("co
l"));

}

If there are multiple columns in the result set, you'll have to combine them into their own data structure for each row.
Arrays work well for that as you know the size, though a custom class might be best so you can convert the contents to
the pr
oper type when extracting from databse, instead of later.



Q) Efficiency of HashTable
-

If hash table is so fast, why don't we use it for everything?

A)

One reason is that in a hash table the relations among keys disappear, so that certain operations (ot
her than search,
insertion, and deletion) cannot be easily implemented. For example, it is hard to traverse a hash table according to the
order of the key. Another reason is that when no good hash function can be found for a certain application, the time a
nd
space cost is even higher than other data structures (array, linked list, or tree).


Hashtable has two parameters that affect its efficiency: its capacity and its load factor. The load factor should be
between 0.0 and 1.0. When the number of entries in

the hashtable exceeds the product of the load factor and the
current capacity, the capacity is increased by calling the
rehash

method. Larger load factors use memory more
efficiently, at the expense of larger expected time per lookup.


If many entries are

to be put into a Hashtable, creating it with a sufficiently large capacity may allow the entries to
be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.


Q)
How does a Hashtable internally maintain the key
-
value pairs?


Page
15

A)
The Hashtable class uses an internal (private) class named Entry to hold the key
-
value pairs. All entries of the
Hashtable are stored in an array of Entry objects with the hash value of the key serving as the index. If two or more
different

keys have the same hash value these entries are stored as a linked list under the same index.


Q)
Array


Array of fixed length of same data type; we can store primitive data types as well as class objects.



A
rrays are initialized to the default value of
their type when they are created, not declared, even if they are local
variables


Q) Diff
Iterator

&
Enumeration

&
List Iterator


Iterator is not synchronized and enumeration is synchronized. Both are interface, Iterator is collection interface
that extend
s from ‘List’ interface. Enumeration is a legacy interface, Enumeration having 2 methods ‘Boolean
hasMoreElements()’ & ‘Object NextElement()’. Iterator having 3 methods ‘boolean hasNext()’, ‘object next()’, ‘void
remove()’.
Iterator also has an extra featu
re not present in the older Enumeration interface
-

the ability to
remove
elements
there is one method “void remove()”.


List Iterator


It is an interface, List Iterator extends Iterator to allow bi
-
directional traversal of a list and modification of the
e
lements. Methods are ‘hasNext()’, ‘ hasPrevious()’.


Q) Diff
HashTable

&
HashMap



Both provide key/value to access the data. The H.T is one of the collection original collection classes in java. H.P is
part of new collection framework.



H.T is synchron
ized and H.M is not.



H.M permits null values in it while H.T does not.



Iterator in the H.P is fail
-
safe while the enumerator for the H.T is not.


Q)
Converting from a Collection to an array
-

and back again?

The collection interface define the toArray(
) method, which returns an array of objects. If you want to convert back to a
collection implementation, you could manually traverse each element of the array and add it using the
add(Object)
method.



// Convert from a collection to an array

Object[] arra
y = c.toArray();


// Convert back to a collection

Collection c2 = new HashSet();

for(int i = 0; i < array.length; i++)

{


c2.add(array[i]);

}


Q)
How do I look through each element of a HashMap?

A)
<select id="swf" name="swf" onChange="showStandardWF(
)" style="width:175px;">


<option value="">&lt;Select Standard WorkFlow&gt;</option>

<%



hmap =(HashMap)request.getAttribute("stdwf");



if
( hmap.size() != 0){




int
len = hmap.size();



Set set = hmap.keySet();



Iterator it = set.iterator();



while
(it
.hasNext())



{




Integer key = (Integer)it.next();



%>




<option value="<%=key%>"><%=(String)hmap.get(key)%></option>



<%



}



}

%>



Page
16

</select>




Q) Retrieving data from a collection?

public class IteratorDemo

{


public static void main(String ar
gs[])


{


Collection c = new ArrayList();



// Add every parameter to our array list


for (int indx = 0; indx < args.length; indx++)


{


c.add(args[indx]);


}



// Examine only those parameters that s
tart with
-


Iterator i = c.iterator();



// PRE : Collection has all parameters


while (i.hasNext())


{


String param = (String) i.next();



// Use the remove method of iterator


if (! param.sta
rtsWith("
-
") )


i.remove();


}


// POST: Collection only has parameters that start with
-



// Demonstrate by dumping collection contents


Iterator i2 = c.iterator();


while (i2.hasNext())


{



System.out.println ("Param : " + i2.next());


}


}

}


Q)

How do I sort an array?

A)


Arrays class provides a series of sort() methods for sorting arrays. If the array is an array of primitives (or) an array
of a class that implements Compara
ble then you can just call the method directly:

Arrays.sort(theArray);


If, however, it is an array of
objects

that don't implement the Comparable interface then you need to provide a
custom Comparator to help you sort the elements in the array.

Arrays.sor
t(theArray, theComparator);


===============================================================================














Page
17





Exception Handling








Object














Throwable









Error





Exception










AWT Error Virtual Machine Error
















Compile time.Ex Runtime Exception







(checked)


(Unchecked)



OutOfMemory.E StackOverFlow.E EOF.E


FilenotFound.E











Arithmetic.
E NullPointer.E Indexoutof














Bound.E


























ArrayIndexoutOfBound.E StirngIndexoutOfBound


Q) Diff
Exception

&
Error


Exception and Error both are subclasses of the Thr
owable class.



Exception

Exception is generated by java runtime system (or) by manually. An exception is a abnormal condition that
transfer program execution from a thrower to catcher.

Error

Will stop the program execution, Error is a abnormal sys
tem condition we cannot handle these.


Q)
Can an exception be rethrown?

A) Yes, an exception can be rethrown.


Q)
try
,
catch
,
throw
,
throws

try


This is used to fix up the error, to prevent the program from automatically terminating, try
-
catch is

used to
catching an exception that are thrown by the java runtime system.

Throw


is used to throw an exception explicitly.

Throws


A Throws clause list the type of exceptions that a methods might through.


Q)

What happens if an exception is not caugh
t?

A) An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which
eventually results in the termination of the program in which it is thrown.


Q)

What happens if a try
-
catch
-
finally statement does not ha
ve a catch clause to handle an exception that is
thrown within the body of the try statement?

The exception propagates up to the next higher level try
-
catch statement (if any) or results in the program's termination.


Q)
Checked

&
UnChecked Exception
:
-

Ch
ecked exception is some subclass of Exception. Making an exception checked forces client programmers to
deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read()
method∙



Unchecked
exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are
unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the
exception or declare it in a throws clause
. In fact, client programmers may not even know that the exception could be
thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method∙ Checked exceptions must be
caught at compile time. Runtime exceptions do not need to be. Errors ofte
n cannot be.


Checked Exceptions

Un checked exception

ClassNotFoundException

ArithmeticException


Page
18

NoSuchMethod
Exception

ArrayIndexOutOfBoundException

NoSuchFieldException

ClasscastException

InterruptedException

IllegalArgumentException

IllegalAccessEx
ception

IllegalMonitorSateException

CloneNotSupportedException

IllegalThreadStateException


IndexOutOfBoundException


NullPointerException


NumberFormatException


StringIndexOutOfBounds


OutOfMemoryError
--
>
Signals that JVM has run out of memory and

that the garbage collector is unable to claim
any more free memory.

StackOverFlow
--
>
Signals that a stack O.F in the interpreter.

ArrayIndexOutOfbound
--
>
For accessing an array element by providing an index values <0 or > or equal to the
array size.

Str
ingIndexOutOfbound
--
>
For accessing character of a string or string buffer with index values <0 or > or
equal to the array size.

Arithmetic Exception
--
>
such as divide by zero.

ArrayStore Exception
--
>
Assignment to an array element of an incompatible ty
pes.

ClasscastException
--
>
Invalid casting.

IllegalArgument Exception
--
>
Illegal argument is used to invoke a method.

Nullpointer Exception
--
>
If

a
ttempt to made to use a null object.

NumberFormat Exception
--
>
Invalid conversition of string to numeric
format.

ClassNotfound Exception
--
>
class not found.

Instantion Exception
--
>
Attempt to create an object of an Abstract class or Interface.

NosuchField Exception
--
>
A request field does not exist.

NosuchMethod Exception
--
>
A request method does not exis
t.


Q) Methods in Exceptions?

A)
getMessage(), toString(), printStackTrace(), getLocalizedMessage(),


Q) What is exception chaining?

A)

An exception chain is a list of all the exceptions generated in response to a single root exception. As

each exception
is caught and converted to a higher
-
level exception for rethrowing, it's added to the chain.

This provides a complete record of how an exception is handled The chained exception API was introduced in 1.4. Two
methods and two constructors were added to Thr
owable.

Throwable getCause()

Throwable initCause(Throwable)

Throwable(String, Throwable)

Throwable(Throwable)


The Throwable argument to initCause and the Throwable constructors is the exception that caused the current
exception. getCause returns the excep
tion that caused the current exception, and initCause returns the current
exception.


Q)
Primitive multi tasking



If the threads of different priorities shifting the control depend on the priority i.e.; a thread with higher priority is
executed first tha
n the thread with lower priority. This process of shifting control is known as primitive multi tasking.


Q)
Http Status Codes


To inform the client of a problem at the server end, you call the “sendError” method. This causes the server to
respond with stat
us line, with protocol version and a success or error code.

The first digit of the status code defines the class of response, while the last two digits do not have categories

Number

Type

Description

1xx

Informational

Requested received, continuing to pro
cess

2xx

Success

The action was successfully received, understood, and accepted

3xx

Redirection

Further action must be taken in order to complete the request

4xx

Client Error

The request contains bad syntax or cannot be fulfilled

5xx

Server Error

The s
erver failed to fulfil valid request



Page
19





All Packages


Q)
Thread Class

Methods:
-

getName()

run()

getPriority()

Sleep()

isAlive()

Start()

join()



Q)
Object class


All other classes are sub classes of object class, Object class is a super class of al
l other class.

Methods:
-

void notify()

void notifyAll()

Object clone()

Sting toString()

boolean equals(Object object)

void wait()

void finalize()

void wait(long milliseconds, int nanoseconds)

int hashcode()



Q)
throwable class

Methods:
-

String getM
essage()

Void printStackTrace()

String toString()

Throwable fillInStackTrace()


Q)
Javax.servlet

Package

Interfaces

Classes

Exceptions

Servlet

GenericServlet

ServletException

ServletConfig

ServletInputStream

UnavaliableException

ServletContext

Servlet
OutputStream


ServletRequest

ServletContextAttributeEvent


ServletResponse



SingleThreadModel



ServletContextListener



ServletContextAttributeListener



ServletContextInitialization parameters



ServletRequestAttributeListener



ServletRequestLi
stner



Filter



FilterChain



FilterConfig



RequestDispatcher




GenericServlet (C)


public void destroy();

public String getInitParameter(String name);

public Enumeration getInitParameterNames();

public ServletConfig getServletConfig();

public Ser
vletContext getServletContext();

public String getServletInfo();

public void init(ServletConfig config) throws ServletException;

public void log(String msg);

public abstract void service(ServletRequest req, ServletResponse res)


ServletInputStream (C)


pub
lic int readLine(byte b[], int off, int len)


ServletOutputStream (C)


public void print(String s) throws IOException;


public void println() throws IOException;


Page
20


ServletContextAttributeEvent (C)


public void
attributeAdded
(
ServletContextAttributeEvent

scab)


public void
attributeRemoved
(
ServletContextAttributeEvent

scab)





public void
attributeReplaced
(
ServletContextAttributeEvent

scab
)


Servlet (I)


public abstract void destroy();


public abstract ServletConfig getServletConfig();


public abstract String getServletInfo();


public abstract void init(ServletConfig config) throws ServletException;


public abstract void service(ServletReq
uest req, ServletResponse res)


ServletConfig (I)


public abstract String getInitParameter(String name);


public abstract
Enumeration

getInitParameterNames();


public abstract ServletContext getServletContext();


Se
rvletContext (I)


public abstract Object getAttribute(String name);

public abstract String getRealPath(String path);

public abstract String getServerInfo();

public abstract Servlet getServlet(String name) throws ServletException;

public abstract Enumerat
ion getServletNames();

public abstract Enumeration getServlets();

public abstract void log(Exception exception, String msg);


ServletRequest (I)


public abstract Object getAttribute(String name);


public abstract String getP
arameter(String name);


public abstract
Enumeration

getParameterNames();


public abstract String[] getParameterValues(String name);


public abstract String getRealPath(String path);


public abstract String getRemoteAddr();


public abstract String getRemote
Host();


public abstract String getServerName();


public abstract int getServerPort();


RequestDispatcher getRequestDispatcher(String path);


public int getLocalPort();
//

servlet 2.4


public int getRemotePort();
//

servlet 2.4


public String
getLocalName();
//

servlet 2.4


public String getLocalAddr();
//

servlet 2.4


ServletResponse (I)


public abstract String getCharacterEncoding();


public abstract PrintWriter getWriter() throws IOException;


public abstract void setCont
entLength(int len);


public abstract void setContentType(String type);


Q)
Javax.servlet.Http

Package

Interfaces

Classes

Exceptions

HttpServletRequest

Cookies

ServletException

HttpServletResponse

HttpServlet (Abstarct Class)

UnavaliableException

HttpSe
ssion

HttpUtils


HttpSessionListener

HttpSessionBindingEvent


HttpSessionActivationListener



HttpSessionAttributeListener



HttpSessionBindingListener



HttpSessionContext (deprecated)



Filter




ServletContextListener (I)


pub汩l⁶o楤⁣int數t䥮I
t楡i楺敤eServ汥瑃lnt數tEvent⁥ 敮e)

††††
pub汩l⁶o楤⁣int數t䑥獴牯祥d(Serv汥瑃lnt數tEv敮e⁥ 敮e)



ServletContextAttributeListener (I)


public void attributeAdded(ServletContextAttributeEvent scab)







public void attributeRemoved(ServletC
ontextAttributeEvent scab)


Page
21






public void attributeReplaced(ServletContextAttributeEvent scab)


ServletContextInitilazation parameters




Cookies (C)


public Object clone();

public int getMaxAge();

public String getName();

public String getPa
th();

public String getValue();

public int getVersion();

public void setMaxAge(int expiry);

public void setPath(String uri);

public void setValue(String newValue);

public void setVersion(int v);


HttpServlet
(C)



public void service(ServletRequest

req, Se
rvletResponse res)


protected void doDelete (HttpServletRequest req, HttpServletResponse res)


protected void doGet (HttpServletRequest req, HttpServletResponse res)


protected void doOptions(HttpServletRequest req, HttpServletResponse res)


protected void doPost(HttpServletRequest req, HttpServletResponse res)


protected void doPut(HttpServletRequest req, HttpServletResponse res)


protected void doTrace(HttpServletRequest req, HttpServletResponse res)


protected long getL
astModified(HttpServletRequest req);


protected void service(HttpServletRequest req, HttpServletResponse res)


HttpSessionbindingEvent (C)


public String getName();


public HttpSession getSession();


HttpServletRequest (I)



public abstract Cooki
e[] getCookies();


public abstract String getHeader(String name);


public abstract Enumeration getHeaderNames();


public abstract String getQueryString();


public abstract String getRemoteUser();


public abstract String getRequestedSes
sionId();


public abstract String getRequestURI();


public abstract String getServletPath();


public abstract HttpSession getSession(boolean create);


public abstract boolean isRequestedSessionIdFromCookie();


public abstract boolean isRequestedSessio
nIdFromUrl();


public abstract boolean isRequestedSessionIdValid();


HttpServletResponse (I)


public abstract void addCookie(Cookie cookie);


public abstract String encodeRedirectUrl(String url);


public abstract String encodeUrl(Str
ing url);


public abstract void sendError(int sc, String msg) throws IOException;


public abstract void sendRedirect(String location) throws IOException;


public abstract void addIntHeader(String header, int value);


public abstract void addDa
teHeader(String header, long value);


public abstract void setHeader(String name, String value);


public abstract void setIntHeader(String header, int value);


public abstract void setDateHeader(String header, long value);


public void setStatus();


HttpSe
ssion (I)


public abstract long getCreationTime();


public abstract String getId();


public setAttribute(String name, Object value);


public getAttribute(String name, Object value);


public remove Attribute(String name, Object value);


public abstrac
t long getLastAccessedTime();


public abstract HttpSessionContext getSessionContext();


public abstract Object getValue(String name);


Page
22


public abstract String[] getValueNames();


public abstract void invalidate();


public abstract boolean isNew();


pu
blic abstract void putValue(String name, Object value);


public abstract void removeValue(String name);


public setMaxInactiveIntervel();


HttpSessionListener (I)


public void sessionCreated(HttpSessionEvent event)






public void
s
essi
onDestroyed(HttpSessionEvent event)


HttpSessionAttributeListener (I)


public void attributeAdded(ServletContextAttributeEvent scab)







public void attributeRemoved(ServletContextAttributeEvent scab)






public void attributeReplaced(Ser
vletContextAttributeEvent scab)


HttpSessionBindingListener (I)





public void HttpSessionBindingListener.valueBound(HttpSessionBindingEvent event)



public void HttpSessionBindingListener.valueUnbound(HttpSessionBindingEvent event)


HttpSessionActivatio
nListener (I)





public void sessionDidActivate(HttpSessionEvent event)



public void sessionWillpassivate(HttpSessionEvent event)


Filter (i)




public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain)




public FilterConfig getFilterConfig()



public void setFilterConfig (FilterConfig filterConfig)


Q)
java.sql

Package

Interfaces

Classes

Exceptions

Connection


DriverManager


CallableStatement

Date

ClassNotFoundException

Driver


TimeStamp

Instantiation Exception

PreparedStatement

Time


ResultSet


Types


ResultSetMetaData


SQL Exception, SQL
Warnings


Statement




DatabaseMetaData



Array



ParameterMetaData



Clob, Blob



SQLInput, SQLOutput, SQLPermission



Savepoint




Q)
javax.sql

Package

Interfaces

Classes

Exceptions

ConnectionEventListener

ConnectionEvent


ConnectionPoolDataSource

RowsetEvent


DataSource



PooledConnection



RowSet



RowSetListener



RowSetMetaDate



RowSetReader/Writer



XAConnection



XADataSource




Q) j
ava.lang

Package

Interfaces

Classes

Exceptions


Page
23

Cloneable

Double, Float, Long, Integer, Short,
Byte, Boolean, Character,

ArithmeticException,
ArrayIndexOutOfBoundOf.E,
ClassCast.E, ClassNotFound.E

Runnable

Class, ClassLoader

IlleAce
ss.E, IllegalArgument.E

Comparable

Process, RunTime, Void

IllegalSate.E, NullPointer.E


String, StringBuffer

NoSuchField.E, NoSuchMethod.E


Thread, ThreadGroup

NumberFormat.E


Q)
java.IO

Package

Interfaces

Classes

Exceptions

DataInputstream

BufferInpu
tstream, BufferOutputStream


DataOutputstream

BufferReader, BufferWriter


ObjectInputStream

ByteArrayInputStream, ByteArrayOutputstream


ObjectOutputstream

CharacterarrayReader, CharacterArayWriter


Serializable

DataInputStream, DataOutputStream


Exte
rnializable

Filereader, FileWriter



ObjectInputStream, ObjectOutputStream











































Page
24





SERVLET Questions


Class path
:
-


set path= c:
\
j2sdk1.4.2
\
bin


set classpath= c:
\

j2sdk1.4.2
\
lib
\
tools.jar;c:
\
servlet.jar


C:
\
Tomcat5
\
bin
\
startup.bat


shortcut


Q)
Servlet


Servlet is server side component, a servlet is small plug gable extension to the server and servlets are used to
extend the functionality of the java
-
enabled server. Servlets are durable objects means that they rema
in in memory
specially instructed to be destroyed. Servlets will be loaded in the

Address space of web server.



Servlet are loaded 3 ways 1) When the web sever starts 2) You can set this in the configuration file 3) Through an
administration interface.


Q
) What is Temporary Servlet?

A)

When we sent a request to access a JSP, servlet container internally creates a 'servlet' & executes it. This servlet is
called as 'Temporary servlet'. In general this servlet will be deleted immediately to create & execute a

servlet base on a
JSP we can use following command.

Java weblogic.jspc

keepgenerated *.jsp


Q) What is the difference between Server and Container?

A)

A server provides many services to the clients, A server may contain one or more containers such as ejb
containers,
servlet/jsp container. Here a container holds a set of objects.


Q)
Servlet Container


The servlet container is a part of a Web server (or) Application server that provides the network services over
which requests and responses are sent, decode
s MIME
-
based requests, and formats MIME
-
based responses. A servlet
container also contains and manages servlets through their lifecycle.

A servlet container can be built into a host Web server, or installed as an add
-
on component to a Web Server via that
s
erver’s native extension API. All servlet containers must support HTTP as a protocol for requests and

responses, but additional request/response
-
based protocols such as HTTPS (HTTP over SSL) may be supported.


Q) Generally Servlets are used for complete HT
ML generation. If you want to generate partial HTML's that
include some static text as well as some dynamic text, what method do you use?

A)

Using 'RequestDispather.include(“xx.html”) in the servlet code we can mix the partial static HTML Directory page.

E
x:
-

RequestDispatcher rd=ServletContext.getRequestDispatcher(“xx.html”);


rd.include(request,response);


Q)
Servlet Life cycle


Public void
init

(ServletConfig config) throws ServletException

public void
service

(ServletRequest req, ServletResponse res) t
hrows ServletException, IOException

public void
destroy

()




The Web server when loading the servlet calls the init method once. (The init method typically establishes database
connections.)



Any request from client is handled initially by the
service (
)

method before delegating to the
doXxx ()

methods in the
case of HttpServlet. If u put “
Private”

modifier for the service() it will give compile time error.




When your application is stopped (or) Servlet Container shuts down, your Servlet's
destroy ()

m
ethod will be called.
This allows you to free any resources you may have got hold of in your Servlet's
init ()

method, this will call only once.


ServletException



Signals that some error occurred during the
processing

of the request and the container sho
uld
take appropriate measures to clean up the request.



Page
25


IOException