Tuesday, December 17, 2013

All In One



1.            Can there be an abstract class with no abstract methods in it?  
Ø   Yes.
2.            Can an Interface be final?
Ø   No.
3.            Can an Interface have an inner class?  
Ø   Yes
public interface abc {
          static int i=0;
          void dd();
          class a1 {
                   a1() {
                             int j;
                             System.out.println("in interfia");
                   };
                   public static void main(String a1[]) {
                             System.out.println("in interfia");
                   }
          }
 }

4.            Can we define private and protected modifiers for variables in interfaces?  
Ø   No

5.            What is Externalizable?  
Ø   Externalizable is an Interface that extends Serializable Interface and sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal (ObjectInput in)

6.            What modifiers are allowed for methods in an Interface?  
Ø   Only public and abstract modifiers are allowed for methods in interfaces.

7.            What is a local, member and a class variable?  
Ø   Variables declared within a method are "local" variables. Variables declared within the class i.e. not within any methods are "member" variables (global variables).Variables declared within the class i.e. not within any methods and are defined as "static" are class variables

8.            I made my class Cloneable but I still get 'Can't access protected method clone. Why?  
Ø   you have to implement your own public clone() method, even if it doesn't do anything special and just calls super.clone().

9.            Can we overload main method in java?  
Ø   Yes. But the main method with String args[] is called when you call the program (java Test1) Have a look at this demo.
 public class Test1{
          public static void main(String[] args){
                   System.out.println("in main method");
          }
          public static void main(String args[],String arg){
                   System.out.println("in overload method");
          }
}
10.        What are some alternatives to inheritance?  
Ø   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 hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

11.        Why isn't there operator overloading?  
Ø   Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn't even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().

12.        What does it mean that a method or field is "static"?  
Ø   Static variables and 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 rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work. out is a static field in the java.lang.System class.

13.        Difference between JRE And JVM AND JDK  

Java Development Kit (JDK)
A software development environment for writing applets and applications in the Java programming language. Technically, the JDK is the correct name for all versions of the Java platform.
Java virtual machine
A software "execution engine" that safely and compatibly executes the byte codes in Java class files on a microprocessor (whether in a computer or in another electronic device
A subset of the Java Development Kit (JDK) for end-users and developers who want to redistribute the runtime environment alone. The Java runtime environment consists of the Java virtual machine1, the Java core classes, and supporting files.

14.        Why do threads block on I/O?  
Ø   Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed

15.        What is synchronization and why is it important?  
Ø   With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.

16.        Is null a keyword?  
Ø   The null value is not a keyword.

17.        Which characters may be used as the second character of an identifier, but not as the first character of an identifier?  
Ø   The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

18.        What modifiers may be used with an inner class that is a member of an outer class?  
Ø   A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

19.        How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?  
Ø   Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

20.        What are wrapped classes?  
Ø   Wrapped classes are classes that allow primitive types to be accessed as objects.

21.        What restrictions are placed on the location of a package statement within a source code file?  
Ø   A package statement must appear as the first line in a source code file (excluding blank lines and comments).

22.        What is the difference between preemptive scheduling and time slicing?  
Ø   Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

23.        What is a native method?  
Ø   A native method is a method that is implemented in a language other than Java.

24.        What is order of precedence and Associativity, and how are they used?  
Ø   Order of precedence determines the order in which operators are evaluated in expressions. Associativity determines whether an expression is evaluated left-to-right or right-to-left

25.        What is the catch or declare rule for method declarations?  
Ø   If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

26.        Can an anonymous class be declared as implementing an interface and extending a class?  
Ø   An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

27.        What is the range of the char type?  
Ø   The range of the char type is 0 to 2^16 - 1.

28.        What is the purpose of finalization?  
Ø   The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

29.        What is the difference between the Boolean & operator and the && operator?  
Ø   If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

30.        How many times may an object's finalize() method be invoked by the garbage collector?  
Ø   An object's finalize() method may only be invoked once by the garbage collector.

31.        What is the purpose of the finally clause of a try-catch-finally statement?  
Ø   The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

32.        What is the argument type of a program's main() method?  
Ø   A program's main() method takes an argument of the String[] type.

33.        Which Java operator is right associative?  
Ø   The = operator is right associative.

34.        Can a double value be cast to a byte?  
Ø   Yes, a double value can be cast to a byte.

35.        What is the difference between a break statement and a continue statement?  
Ø   A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.

36.        What must a class do to implement an interface?  
Ø   It must provide all of the methods in the interface and identify the interface in its implements clause.

37.        What is the advantage of the event-delegation model over the earlier event-inheritance model?  
Ø   The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.

38.        How are commas used in the intialization and iteration parts of a for statement?  
Ø   Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.

39.        What is an abstract method?  
Ø   An abstract method is a method whose implementation is deferred to a subclass.

40.        What value does read() return when it has reached the end of a file?  
Ø   The read() method returns -1 when it has reached the end of a file.

41.        Can a Byte object be cast to a double value?  
Ø   No, an object cannot be cast to a primitive value.

42.        What is the difference between a static and a non-static inner class?  
Ø   A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.

43.        If a variable is declared as private, where may the variable be accessed?  
Ø   A private variable may only be accessed within the class in which it is declared.

44.        What is an object's lock and which object's have locks?  
Ø   An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

45.        What is the % operator?  
Ø   It is referred to as the “modulo” or “remainder” operator. It returns the remainder of dividing the first operand by the second operand.

46.        When can an object reference be cast to an interface reference?  
Ø   An object reference can be cast to an interface reference when the object implements the referenced interface.

47.        Which class is extended by all other classes?  
Ø   The Object class is extended by all other classes.

48.        Can an object be garbage collected while it is still reachable?  
Ø   A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.

49.        Is the ternary operator written x : y ? z or x ? y : z ?  
Ø   It is written x ? y : z.

50.        How is rounding performed under integer division?  
Ø   The fractional part of the result is truncated. This is known as rounding toward zero.

51.        What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?  
Ø   The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

52.        What classes of exceptions may be caught by a catch clause?  
Ø   A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

53.        If a class is declared without any access modifiers, where may the class be accessed?  
Ø   A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

54.        Does a class inherit the constructors of its superclass?  
Ø   A class does not inherit constructors from any of its superclasses.

55.        What is the purpose of the System class?  
Ø   The purpose of the System class is to provide access to system resources.

56.        Name the eight primitive Java types.  
Ø   The eight primitive types are byte, char, short, int, long, float, double, and boolean.

57.        Which class should you use to obtain design information about an object?  
Ø   The Class class is used to obtain information about an object's design.

58.        Is "abc" a primitive value?  
Ø   The String literal "abc" is not a primitive value. It is a String object.

59.        What restrictions are placed on the values of each case of a switch statement?  
Ø   During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.

60.        What modifiers may be used with an interface declaration?  
Ø   An interface may be declared as public or abstract.

61.        Is a class a subclass of itself?  
Ø   A class is a subclass of itself.

62.        What is the difference between a while statement and a do statement?  
Ø   A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

63.        What modifiers can be used with a local inner class?  
Ø   A local inner class may be final or abstract.

64.        What is the purpose of the File class?  
Ø   The File class is used to create objects that provide access to the files and directories of a local file system.

65.        Can an exception be rethrown?  
Ø   Yes, an exception can be rethrown.

66.        When does the compiler supply a default constructor for a class?  
Ø   The compiler supplies a default constructor for a class if no other constructors are provided.

67.        If a method is declared as protected, where may the method be accessed?  
Ø   A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

68.        Which non-Unicode letter characters may be used as the first character of an identifier?  
Ø   The non-Unicode letter characters $ and _ may appear as the first character of an identifier

69.        What restrictions are placed on method overloading?  
Ø   Two methods may not have the same name and argument list but different return types.

70.        What is casting?  
Ø   There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

71.        What is the return type of a program's main() method?  
Ø   A program's main() method has a void return type.

72.        What class of exceptions is generated by the Java run-time system?  
Ø   The Java runtime system generates RuntimeException and Error exceptions.

73.        What class allows you to read objects directly from a stream?  
Ø   The ObjectInputStream class supports the reading of objects from input streams.

74.        What is the difference between a field variable and a local variable?  
Ø   A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.

75.        How are this() and super() used with constructors?  
Ø   this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

76.        What is the relationship between a method's throws clause and the exceptions that can be thrown during the method's execution?  
Ø   A method's throws clause must declare any checked exceptions that are not caught within the body of the method.

77.        Why are the methods of the Math class static?  
Ø   So they can be invoked as if they are a mathematical code library.

78.        What are the legal operands of the instanceof operator?  
Ø   The left operand is an object reference or null value and the right operand is a class, interface, or array type.

79.        What an I/O filter?  
Ø   An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

80.        If an object is garbage collected, can it become reachable again?  
Ø   Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.

81.        What are E and PI?  
Ø   E is the base of the natural logarithm and PI is mathematical value pi.

82.        Are true and false keywords?  
Ø   The values true and false are not keywords.

83.        What is the difference between the File and RandomAccessFile classes?  
Ø   The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

84.        What happens when you add a double value to a String?  
Ø   The result is a String object.

85.        What is your platform's default character encoding?  
Ø   If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.

86.        Which package is always imported by default?  
Ø   The java.lang package is always imported by default.

87.         What interface must an object implement before it can be written to a stream as an object?  
Ø   An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

88.        What’s the difference between notify() and notifyAll()?  
Ø   notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when releasing a "writer" lock on a file might permit all "readers" to resume).

89.        Why can't I say just abs() or sin() instead of Math.abs() and Math.sin()?  
Ø   The import statement does not bring methods into your local name space. It lets you abbreviate class names, but not get rid of them altogether. That's just the way it works, you'll get used to it. It's really a lot safer this way. <br> However, there is actually a little trick you can use in some cases that gets you what you want. If your top-level class doesn't need to inherit from anything else, make it inherit from java.lang.Math. That *does* bring all the methods into your local name space. But you can't use this trick in an applet, because you have to inherit from java.awt.Applet. And actually, you can't use it on java.lang.Math at all, because Math is a "final" class which means it can't be extended.

90.        What is the output from System.out.println("Hello"+null);  
Ø   Hellonull

91.        Why are there no global variables in Java?  
Ø   Global variables are considered bad form for a variety of reasons:
·         Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables).
·         State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of Object-Oriented programming is to break up global state into more easily understood collections of local state.
·         When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once.
For these reasons, Java decided to ban global variables.

92.        What does it mean that a class or member is final?  
Ø   A final class can no longer be sub classed. Mostly this is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. Methods may be declared final as well. This means they may not be overridden in a subclass. Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be changed after it's initialized, and it must include an initializer statement where it's declared. For example,
public final double c = 2.998;
It's also possible to make a static field final to get the effect of C++'s const statement or some uses of C's #define, e.g.
public static final double c = 2.998;

93.        What does it mean that a method or class is abstract?  
Ø   An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this:
public abstract class Container extends Component {
Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has no body. For example,
public abstract float price();
Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract.

94.        what is a transient variable?  
Ø   transient variable is a variable that may not be serialized.

95.        How are Observer and Observable used?  
Ø   Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

96.        Can a lock be acquired on a class?  
Ø   Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

97.        What state does a thread enter when it terminates its processing?  
Ø   When a thread terminates its processing, it enters the dead state.

98.        How does Java handle integer overflows and underflows?  
Ø   It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

99.        What is the difference between the >> and >>> operators?  
Ø   The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

100.    Is sizeof a keyword?  
Ø   The sizeof operator is not a keyword.

101.    Does garbage collection guarantee that a program will not run out of memory?  
Ø   Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection

102.    Can an object's finalize() method be invoked while it is reachable?  
Ø   An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects.

103.    What value does readLine() return when it has reached the end of a file?  
Ø   The readLine() method returns null when it has reached the end of a file.

104.    Can a for statement loop indefinitely?  
Ø   Yes, a for statement can loop indefinitely. For example, consider the following:
for(;;) ;

105.    To what value is a variable of the String type automatically initialized?  
Ø   The default value of an String type is null.

106.    What is a task's priority and how is it used in scheduling?  
Ø   A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.

107.    What is the range of the short type?  
Ø   The range of the short type is -(2^15) to 2^15 - 1.

108.    What is the purpose of garbage collection?  
Ø   The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused.

109.    What do you understand by private, protected and public?  
Ø   These are accessibility modifiers. Private is the most restrictive, while public is the least restrictive. There is no real difference between protected and the default type (also known as package protected) within the context of the same package, however the protected keyword allows visibility to a derived class in a different package.

110.    What is down casting?  
Ø   Down casting is the casting from a general to a more specific type, i.e. casting down the hierarchy

111.    Can a method be overloaded based on different return type but same argument type?  
Ø   No, because the methods can be called without using their return type in which case there is ambiguity for the compile

112.    What happens to a static var that is defined within a method of a class ?  
Ø   Can't do it. You'll get a compilation error

113.    How many static init can you have?  
Ø   As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope.

114.    What is the difference amongst JVM Spec, JVM Implementation, JVM Runtime?  
Ø   The JVM spec is the blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM implementation

115.    Describe what happens when an object is created in Java?  
Ø   Several things happen in a particular order to ensure the object is constructed properly:
1.      Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its super classes. Implementation-specific data includes pointers to class and method data.
2.      The instance variables of the objects are initialized to their default values.
3.      The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its super classes. This process continues until the constructor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java.
4.      Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

116.    What does the "final" keyword mean in front of a variable? A method? A class?  
Ø   FINAL for a variable : value is constant
FINAL for a method: cannot be overridden
FINAL for a class: cannot be derived

117.    What is the difference between instanceof and isInstance?  
Ø   instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class exception.
isInstance()
Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.

118.    Why is not recommended to have instance variables in Interface  
Ø   By Default, All data members and methods in an Interface are public. Having public variables in a class that will be implementing it will be violation of the Encapsulation principal. I hope that's pretty ok. If anybody has a better framed answer. U r welcome at reema_gupta@intersolutions.stpn.soft.net

119.    What is the difference between inner class and nested class?  
Ø   When a class is defined within a scope of another class, then it becomes inner class. If the access modifier of the inner class is static, then it becomes nested class.

120.    How the private constructor is called in the main java program?  
Ø   Have a look at this demo.
public class Test2 {
          private Test2(){
                   System.out.println("Test2class");
          }
          class Subclass extends Test2{
                   public Subclass(){
                             System.out.println("Subclass");
                   }
          }
          public static void main(String[] args){
                   Subclass s = new Test2().new Subclass();
          }
}
This works because an inner class is allowed to access private members of its enclosing instance, including the private constructor.

121.    Which is garbage collected first: Normal variables or static variables?  
Ø   Normal variables will be collected first. Lets take a simple example:
Class A is having a static variable s which is used by obj1, obj2 and obj3 of Class B. Each object of class B is having instance variables a and b (normal variables). Lets say if obj1 is not being in use since long time, then automatically the garbage collector will collect the space occupied by obj1. It will not destroy the static variable S as it is being used by the other two objects obj2 and obj3. Therefore only normal variables will be destroyed first.
We can say it in a simple statement that "Variables having less scope will be destroyed first"

122.    Difference between JRE And JVM AND JDK   
Ø   The "JDK" is the Java Development Kit. I.e., the JDK is bundle of software that you can use to develop Java based software. The "JRE" is the Java Runtime Environment. I.e., the JRE is an implementation of the Java Virtual Machine which actually executes Java programs. Typically, each JDK contains one (or more) JRE's along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc.

123.    Is it necessary to initialize a final variable at the time of declaration?  
Ø   NO, it's not necessary.
Many text books say like this but that’s not true. Value of a final variable can be instance specific also, but in this case we have to initialize the variable in all the constructors. If we want to have a common final value of a variable for all the instances then there are two ways.
·         Initialize the variable at class level (at the time of declaration) or
·         just declare variable at class level and initialize it in any one of the instance blocks i.e.
¨             class A { final int a; {a=5;}}
¨             class A { final int a = 5;}

124.    What is the output of the following line? System.out.println(-5<<-2);  
Ø   At This point of time I am not sure about the answer. If anybody knows, please tell me at
raja8top@yahoo.com OR raja_choudhary@rediffmail.com I shall be highly thankful to you.

125.    What is a compilation unit?  
Ø   A compilation unit is a Java source code file.

126.    What restrictions are placed on method overriding?  
Ø   Overridden methods must have the same name, argument list, and return type.
The overriding method may not limit the access of the method it overrides.
The overriding method may not throw any exceptions that may not be thrown by the overridden method.

127.    How can a dead thread be restarted?  
Ø   A dead thread cannot be restarted.

128.    What happens if an exception is not caught?  
Ø   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.

129.    Which arithmetic operations can result in the throwing of an ArithmeticException?  
Ø   Integer / and % can result in the throwing of an ArithmeticException

130.    Can an abstract class be final?  
Ø   An abstract class may not be declared as final

131.    What happens if a try-catch-finally statement does not have 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

132.    What is numeric promotion?  
Ø   Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required

133.    What is the difference between a public and a non-public class?  
Ø   A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package.

134.    To what value is a variable of the boolean type automatically initialized?  
Ø   The default value of the boolean type is false

135.    Can try statements be nested?  
Ø   Yes

136.    What is the difference between the prefix and postfix forms of the ++ operator?  
Ø   The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value.

137.    What is the purpose of a statement block?  
Ø   A statement block is used to organize a sequence of statements as a single statement group

138.    What is a Java package and how is it used?  
Ø   A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.

139.    What modifiers may be used with a top-level class?  
Ø   A top-level class may be public, abstract, or final.

140.    What are the Object and Class classes used for?  
Ø   The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

141.    How does a try statement determine which catch clause should be used to handle an exception?  
Ø   When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.

142.    What are synchronized methods and synchronized statements?  
Ø   Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

143.    What is the difference between an if statement and a switch statement?  
Ø   The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.

144.    What gives java it's "write once and run anywhere" nature?  
Ø   Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platform specific and hence can be fed to any platform. After being fed to the JVM, which is specific to a particular operating system, the code platform specific machine code is generated thus making java platform independent.

145.    What are the four corner stones of OOP?  
Ø   Abstraction, Encapsulation, Polymorphism and Inheritance

146.    Difference between a Class and an Object?  
Ø   A class is a definition or prototype whereas an object is an instance or living representation of the prototype

147.    What is the difference between method overriding and overloading?   
Ø   Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments

148.    What is a "stateless" protocol?  
Ø   Without getting into lengthy debates, it is generally accepted that protocols like HTTP are stateless i.e. there is no retention of state between a transaction which is a single request response combination

149.    What is constructor chaining and how is it achieved in Java?  
Ø   A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In Java it is done via an implicit call to the no-args constructor as the first statement.

150.    What is passed by ref and what by value?  
Ø   All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references

151.    You can create a String object as String str = "abc"; Why can’t a button object be created as Button bt = "abc";? Explain  
Ø   The main reason you cannot create a button by Button bt1= "abc"; is because "abc" is a literal string (something slightly different than a String object, by-the-way) and bt1 is a Button object. The only object in Java that can be assigned a literal String is java.lang.String. Important to note that you are NOT calling a java.lang.String constructor when you type String s = "abc";

152.    What does the "abstract" keyword mean in front of a method? A class?  
Ø   Abstract keyword declares either a method or a class. If a method has an abstract keyword in front of it, it is called abstract method. Abstract method has no body. It has only arguments and return type. Abstract methods act as placeholder methods that are implemented in the subclasses.
Abstract classes can't be instantiated. If a class is declared as abstract, no objects of that class can be created. If a class contains any abstract method it must be declared as abstract

153.    How many methods do u implement if implement the Serializable Interface?  
Ø   The Serializable interface is just a "marker" interface, with no methods of its own to implement. Other 'marker' interfaces are
java.rmi.Remote
java.util.EventListener

154.    What are the practical benefits, if any, of importing a specific class rather than an entire package (e.g. import java.net.* versus import java.net.Socket)?  
Ø   It makes no difference in the generated class files since only the classes that are actually used are referenced by the generated class file. There is another practical benefit to importing single classes, and this arises when two (or more) packages have classes with the same name. Take java.util.Timer and javax.swing.Timer, for example. If I import java.util.* and javax.swing.* and then try to use "Timer", I get an error while compiling (the class name is ambiguous between both packages). Let's say what you really wanted was the javax.swing.Timer class, and the only classes you plan on using in java.util are Collection and HashMap. In this case, some people will prefer to import java.util.Collection and import java.util.HashMap instead of importing java.util.*. This will now allow them to use Timer, Collection, HashMap, and other javax.swing classes without using fully qualified class names in.

155.    What is the difference between logical data independence and physical data independence?  
Ø   Logical Data Independence - meaning immunity of external schemas to changes in conceptual schema. Physical Data Independence - meaning immunity of conceptual schema to changes in the internal schema.

156.    What is user defined exception?  
Ø   Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class.

157.    Difference Between Abstraction and Encapsulation  
Ø   Abstraction is removing some distinctions between objects, so as to show their commonalities.
Encapsulation is hiding the details of the implementation of an object so that there are no external dependencies on the particular implementation.

158.    What are Checked and Un-Checked Exceptions? Explain.  
Ø   Throwable extends Object (checked)
Exception extends Throwable (checked)
RuntimeException extends Exception (un-checked)
Error extends Throwable (un-checked)
So anything that extends Throwable or Exception (except RuntimeException) will be checked. Anything that extends Error or RuntimeException will be un-checked
Checked exceptions are problems that arise in correct code and may be due to technical problems such as IO problems or user mistakes such as opening a socket when the remote machine does not exist. Because these problems can occur at anytime, say due to network outage, you must have code that can handle and recover from these. In fact, the Java compiler checks that you have trapped them hence checked exceptions.
Runtime exceptions are typically bugs in the program. Errors are severe problems such as out of memory and sufficiently rare, that you are not required to handle them as they are usually unrecoverable.

159.    Can we sort a Hashtable?  
Ø   Yes. Here is an example
import java.util.*;
public class SortHashtable {
          public static void main (String [] args) {
// Create and populate hashtable
Hashtable ht = new Hashtable ();
ht.put("abc",new Double(3445.23));
ht.put("xyz",new Double(2333.56));
ht.put("pqr",new Double(3900.88));
ht.put("mno",new Double(2449.00));

// Sort hashtable.
Vector v = new Vector(ht.keySet());
Collections.sort(v);

// Display (sorted) hashtable.
for (Enumeration e = v.elements(); e.hasMoreElements();) {
String key = (String)e.nextElement();
System.out.println(key+":"+ht.get(key));
System.out.println();
                   }
          }
}

160.    What is the exact difference between Abstract classes and Interfaces?  
Ø   Interfaces provide a form of multiple inheritance -- any number of interfaces can be implemented A class can extend only one other class. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.

161.    Garbage collector thread belongs to which priority?  
Ø   Garbage collector thread belongs to low priority (MIN_PRIORITY)

162.    What is the difference between ArrayList and Vector  
Ø   Methods in Vectors are synchronized

163.    Can we have inner class in the interface ?  
Ø   Yes. We can have inner class in the interface.
164.    How to get values from a Vector  
Ø   Vector v = new Vector(10,2) v.add(3); v.add(4); int i= v.get(1);

165.    What is meant by Instance Variables and Class Variables  
Ø   instance variables Any item of data that is associated with a particular object. Each instance of a class has its own copy of the instance variables defined in the class. Also called a field. class variables A data item associated with a particular class as a whole--not with particular instances of the class. Class variables are defined in class definitions. Also called a static field

166.    What is difference between JSP and Servlet?  
Ø   The main diff between JSP and Servlet is code and content presentation in JSP, it is not possible in Servlet.

167.    Does the code in finally block get executed if there is an exception and a return statement in a catch block?  
Ø   If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.

168.    What are the Object and Class classes used for?  
Ø   The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

169.    What interface must an object implement before it can be written to a stream as an object?  
Ø   An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

170.    What is an I/O filter?  
Ø   An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

171.    What class allows you to read objects directly from a stream?  
Ø   The ObjectInputStream class supports the reading of objects from input streams.

172.    If a class is declared without any access modifiers, where may the class be accessed?  
Ø   A class that is declared without any access modifiers is said to have package or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

173.    If class A does not implement Serializable but a subclass B implements Serializable, will the fields of class A be serialized when B is serialized?  
Ø   Only the fields of Serializable objects are written out and restored. The object may be restored only if it has a no-arg constructor that will initialize the fields of non-serializable supertypes. If the subclass has access to the state of the superclass it can implement writeObject and readObject to save and restore that state.

174.    When a Serializable object is written with writeObject, then modified and written a second time, why is the modification missing when the stream is deserialized?  
Ø   The ObjectOutputStream class keeps track of each object it serializes and sends only the handle if the object is written into the stream a subsequent time. This is the way it deals with graphs of objects. The corresponding ObjectInputStream keeps track of all of the objects it has created and their handles so when the handle is seen again it can return the same object. Both output and input streams keep this state until they are freed.
Alternatively, the ObjectOutputStream class implements a reset method that discards the memory of having sent an object, so sending an object again will make a copy.

175.    How do I get the serialVersionUID of a class?  
Ø   Run the serialver tool, supplying the name of the class, as shown in the example that follows:
serialver java.lang.String

176.    The object serialization classes are stream oriented. How do I write objects to a random access file?  
Ø   Currently there is no direct way to write objects to a random access file.
You can use the ByteArray I/O streams as an intermediate place to write and read bytes to/from the random access file and create Object I/O streams from the byte streams to write/read the objects. You just have to make sure that you have the entire object in the byte stream or reading/writing the object will fail.
For example, java.io.ByteArrayOutputStream can be used to receive the bytes of ObjectOutputStream. From it you can get a byte[] of the result which, in turn, can be used with ByteArrayInputStream as input to ObjectInput.

177.    Can I compress the serial representation of my objects using my own zip/unzip methods?  
Ø   ObjectOutputStream produces an OutputStream. If your zip object extends the OutputStream class, there is no problem compressing it.

178.    When a local object is serialized and passed as a parameter in an RMI call, are the byte codes for the local object's methods also passed? What about object coherency, if the remote VM application "keeps" the object handle?  
Ø   The bytecodes for a local object's methods are not passed directly in the ObjectOutputStream, but the object's class may need to be loaded by the receiver if the class is not already available locally. (The class files themselves are not serialized, just the names of the classes.) All classes must be able to be loaded during deserialization using the normal class loading mechanisms. For applets this means they are loaded by the AppletClassLoader.
There are no coherency guarantees for local objects passed to a remote VM, since such objects are passed by copying their contents (a true pass-by-value).

179.    Explain about Singleton Class  
In general, you use a singleton to enforce the notion that there will be only one instance of a given class. Singletons should be used in situations where creating more than one of something would be a logical error.
For example, a ConnectionPool would be a good place to use a singleton. If clients could arbitrarily create ConnectionPools without regard to what already exists, you would have a waste of resources. So you limit the possible number of connection pools to 1 (per JVM), and you then know that all clients are getting their connections from a single source.
Another example of Singleton use is for Object Factories. Say you have a class called FooFactory that is responsible for fetching/saving Foo objects to/from a database. You want to ensure that for each Foo record in the db, there is only one corresponding Foo object floating around your application. By centralizing all the creation logic in a single class, and making that class a Singleton, you eliminate the possibility of duplicate objects.
The code that uses a connection obtained from the connection pool is another matter. If all it does is do a getData() type operation, there is no harm in having more than one of them.

180.    Strings are immutable, how are we able to perform concatenation on String object?  
Ø   Yes. Strings are immutable. That’s why while concatenating, it always returns a new string object.
If we take this example :
String s1 = "psn";
s1 = s1.concat("prasad");
            // Here you are reassigning the new object to the older reference s1
System.out.println(s1);
String s1 = "psn";
String s2 = s1.concat("prasad");
System.out.println(s1); // will remain same . no change. it prints "psn" only
System.out.println(s2); // as you have assigned the newly created object to s2

181.    what is j2EE?  
Ø   J2EE means Java 2 Enterprise Edition.. it follows certain rules and regulations to develop web technologies. and certain technologies are under comes i this category like EJB/JSP/Servlets/JMS/Web Servers/App Servers/Struts and Oracle-9.0i

182.    Can an Interface have an inner class? "Comment by Manoj Dudhe"  
Ø   Yes. Interface can have an inner class. The possible use of this is to provide multiple inheritance in java. A class "abc1" can extend normal class "abc2" and can implement an Interface "abc" having an inner class "abc3". This way class "abc1" can get the functionality of both "abc2" and "abc3" classes.

183.    what is tunneling?  
Ø   Tunneling is a route to somewhere. For example, RMI tunneling is a way to make RMI application get through firewall. In CS world, tunneling means a way to transfer data.

184.    What is the difference between the File and RandomAccessFile classes?  
Ø   The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

185.    How are this() and super() used with constructors?  
Ø   this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor

186.    What is casting?  
Ø   There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

187.    What is the purpose of the Runtime class?  
Ø   The purpose of the Runtime class is to provide access to the Java runtime system

188.    Does object serialization support encryption?  
Ø   Object serialization does not contain any encryption/decryption in itself. It writes to and reads from Java Streams, so it can be coupled with any available encryption technology. Object serialization can be used in many different ways from simple persistence, writing and read to/from files, or for RMI to communicate across hosts.

189.    Why is OutOfMemoryError thrown after writing a large number of objects into an ObjectOutputStream?  
Ø   The ObjectOutputStream maintains a table mapping objects written into the stream to a handle. The first time an object is written to a stream, its contents are written into the stream; subsequent writes of the object result in a handle to the object being written into the stream. This table maintains references to objects that might otherwise be unreachable by an application, thus, resulting in an unexpected situation of running out of memory. A call to the ObjectOutputStream.reset() method resets the object/handle table to its initial state, allowing all previously written objects to be eligible for garbage collection.

190.    Why is UTFDataFormatException thrown by DataOutputStream.writeUTF() when serializing a String?  
Ø   DataOutputStream.writeUTF() does not support writing out strings larger than 64K. The first two bytes of a UTF string in the stream are the length of the string. If a java.lang.String can be larger than 64K, it needs to be stored in the stream by an alternative method rather than depending on the default method of storing a String in the stream, writeUTF.

191.    How can I create an ObjectInputStream from an ObjectOutputStream without a file in between?  
Ø   ObjectOutputStream and ObjectInputStream work to/from any stream object. You could use a ByteArrayOutputStream and then get the array and insert it into a ByteArrayInputStream. You could also use the piped stream classes as well. Any java.io class that extends the OutputStream and InputStream classes can be used.
Alternatively, the ObjectOutputStream> class implements a reset method that discards the memory of having sent an object, so sending an object again will make a copy.

192.    Why a file that contains multiple appended ObjectOutputStreams can’t be deserialized by one ObjectInputStream?  
Ø   Using the default implementation of serialization, there must be a one-to-one mapping between ObjectOutputStream construction and ObjectInputStream construction. ObjectOutputStream constructor writes a stream header andObjectInputStream reads this stream header. A workaround is to subclass ObjectOutputStream and override writeStreamHeader(). The overriding writeStreamHeader() should call the super writeStreamHeader method if it is the first write to the file and it should call ObjectOutputStream.reset() if it is appending to a pre-existing ObjectOutputStream within the file.

193.    What is a platform?
Ø   A platform is the hardware or software environment in which a program runs. Most platforms can be described as a combination of the operating system and hardware, like Windows 2000/XP, Linux, Solaris, and MacOS.

194.    What is the main difference between Java platform and other platforms?
Ø   The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms.
The Java platform has two components:
The Java Virtual Machine (Java VM)
The Java Application Programming Interface (Java API)

195.    What is the Java Virtual Machine?
Ø   The Java Virtual Machine is a software that can be ported onto various hardware-based platforms.

196.    What is the Java API?
Ø   The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

197.    What is the package?
Ø   The package is a Java namespace or part of Java libraries. The Java API is grouped into libraries of related classes and interfaces; these libraries are known as packages.

198.    What is native code?
Ø   The native code is code that after you compile it, the compiled code runs on a specific hardware platform.

199.    Is Java code slower than native code?
Ø   Not really. As a platform-independent environment, the Java platform can be a bit slower than native code. However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can bring performance close to that of native code without threatening portability.

200.    What is the serialization?
Ø   The serialization is a kind of mechanism that makes a class or a bean persistence by having its properties or fields and state information saved and restored to and from storage.

201.    How to make a class or a bean serializable?
Ø   By implementing the java.io.Serializable interface

202.    How many methods in the Serializable interface?
Ø   There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable.

203.    What is a transient variable?
Ø   A transient variable is a variable that may not be serialized. If you don't want some field to be serialized, you can mark that field transient or static.

204.    Which containers use a border layout as their default layout?
Ø   The Window, Frame and Dialog classes use a border layout as their default layout.

205.    What is synchronization and why is it important?
Ø   With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often causes dirty data and leads to significant errors.

206.    What are synchronized methods and synchronized statements?
Ø   Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

207.    What are three ways in which a thread can enter the waiting state?
Ø   A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

208.    Can a lock be acquired on a class?
Ø   Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

209.    What's new with the stop(), suspend() and resume() methods in JDK 1.2?
Ø   The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

210.    What is the preferred size of a component?
Ø   The preferred size of a component is the minimum component size that will allow the component to display normally.

211.    What method is used to specify a container's layout?
Ø   The setLayout() method is used to specify a container's layout.

212.    Which containers use a FlowLayout as their default layout?
Ø   The Panel and Applet classes use the FlowLayout as their default layout.

213.    What is thread?
Ø   A thread is an independent path of execution in a system.

214.    What is multithreading?
Ø   Multithreading means various threads that run in a system.

215.    How does multithreading take place on a computer with a single CPU?
Ø   The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

216.    How to create multithread in a program?
Ø   You have two ways to do so. First, making your class "extends" Thread class. Second, making your class "implements" Runnable interface. Put jobs in a run() method and call start() method to start the thread.

217.    Can Java object be locked down for exclusive use by a given thread?
Ø   Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.

218.    Can each Java object keep track of all the threads that want to exclusively access to it?
Ø   Yes.

219.    What state does a thread enter when it terminates its processing?
Ø   When a thread terminates its processing, it enters the dead state.

220.    What invokes a thread's run() method?
Ø   After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

221.    What is the purpose of the wait(), notify(), and notifyAll() methods?
Ø   The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate each other.

222.    What are the high-level thread states?
Ø   The high-level thread states are ready, running, waiting, and dead.

223.    What is the Collections API?
Ø   The Collections API is a set of classes and interfaces that support operations on collections of objects.

224.    What is the List interface?
Ø   The List interface provides support for ordered collections of objects.

225.    How does Java handle integer overflows and underflows?
Ø   It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

226.    What is the Vector class?
Ø   The Vector class provides the capability to implement a growable array of objects

227.    What modifiers may be used with an inner class that is a member of an outer class?
Ø   A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

228.    If a method is declared as protected, where may the method be accessed?
Ø   A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

229.    What is an Iterator interface?
Ø   The Iterator interface is used to step through the elements of a Collection.

230.    How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Ø   Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

231.    What is the difference between yielding and sleeping?
Ø   When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.

232.    Is sizeof a keyword?
Ø   The sizeof operator is not a keyword.

233.    What are wrapped classes?
Ø   Wrapped classes are classes that allow primitive types to be accessed as objects.

234.    Does garbage collection guarantee that a program will not run out of memory?
Ø   No, it doesn't. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection

235.    What is the difference between preemptive scheduling and time slicing?
Ø   Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

236.    Name Component subclasses that support painting.
Ø   The Canvas, Frame, Panel, and Applet classes support painting.

237.    What is a native method?
Ø   A native method is a method that is implemented in a language other than Java.

238.    How can you write a loop indefinitely?
Ø   for(;;)--for loop; while(true)--always true, etc.

239.    Can an anonymous class be declared as implementing an interface and extending a class?
Ø   An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

240.    What is the purpose of finalization?
Ø   The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

241.    Which class is the superclass for every class.
Ø   Object

242.    What is the difference between the Boolean & operator and the && operator?
Ø   If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above.

243.    What is the GregorianCalendar class?
Ø   The GregorianCalendar provides support for traditional Western calendars.

244.    What is the SimpleTimeZone class?
Ø   The SimpleTimeZone class provides support for a Gregorian calendar.

245.    Which Container method is used to cause a container to be laid out and redisplayed?
Ø   validate()

246.    What is the Properties class?
Ø   The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.

247.    What is the purpose of the Runtime class?
Ø   The purpose of the Runtime class is to provide access to the Java runtime system.

248.    What is the purpose of the System class?
Ø   The purpose of the System class is to provide access to system resources.

249.    What is the purpose of the finally clause of a try-catch-finally statement?
Ø   The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

250.    What is the Locale class?
Ø   The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

251.    What must a class do to implement an interface?
Ø   It must provide all of the methods in the interface and identify the interface in its implements clause.

252.    What is an abstract method?
Ø   An abstract method is a method whose implementation is deferred to a subclass. Or, a method that has no implementation (an interface of a method).

253.    What is a static method?
Ø   A static method is a method that belongs to the class rather than any object of the class and doesn't apply to an object or even require that any objects of the class have been instantiated.

254.    What is a protected method?
Ø   A protected method is a method that can be accessed by any method in its package and inherited by any subclass of its class.

255.    What is the difference between a static and a non-static inner class?
Ø   A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.

256.    What is an object's lock and which object's have locks?
Ø   An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

257.    When can an object reference be cast to an interface reference?
Ø   An object reference be cast to an interface reference when the object implements the referenced interface.

258.    What is the difference between a Window and a Frame?
Ø   The Frame class extends Window to define a main application window that can have a menu bar.

259.    What do heavy weight components mean?
Ø   Heavy weight components like Abstract Window Toolkit (AWT), depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button. In this relationship, the Motif button is called the peer to the java.awt.Button. If you create two Buttons, two peers and hence two Motif Buttons are also created. The Java platform communicates with the Motif Buttons using the Java Native Interface. For each and every component added to the application, there is an additional overhead tied to the local windowing system, which is why these components are called heavy weight.

260.    Which package has light weight components?
Ø   javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.

261.    What are peerless components?
Ø   The peerless components are called light weight components.

262.    What is the difference between the Font and FontMetrics classes?
Ø   The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

263.    What happens when a thread cannot acquire a lock on an object?
Ø   If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

264.    What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
Ø   The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

265.    What classes of exceptions may be caught by a catch clause?
Ø   A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

266.    What is the difference between throw and throws keywords?
Ø   The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy.
The throws keyword is a modifier of a method that designates that exceptions may come out of the mehtod, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw.

267.    If a class is declared without any access modifiers, where may the class be accessed?
Ø   A class that is declared without any access modifiers is said to have package or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

268.    What is the Map interface?
Ø   The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

269.    Does a class inherit the constructors of its superclass?
Ø   A class does not inherit constructors from any of its superclasses.

270.    Name primitive Java types.
Ø   The primitive types are byte, char, short, int, long, float, double, and boolean.

271.    Which class should you use to obtain design information about an object?
Ø   The Class class is used to obtain information about an object's design.

272.    How can a GUI component handle its own events?
Ø   A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

273.    How are the elements of a GridBagLayout organized?
Ø   The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

274.    What advantage do Java's layout managers provide over traditional windowing systems?
Ø   Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.

275.    What are the problems faced by Java programmers who don't use layout managers?
Ø   Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.

276.    What is the difference between static and non-static variables?
Ø   A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

277.    What is the difference between the paint() and repaint() methods?
Ø   The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

278.    What is the purpose of the File class?
Ø   The File class is used to create objects that provide access to the files and directories of a local file system.

279.    What restrictions are placed on method overloading?
Ø   Two methods may not have the same name and argument list but different return types.

280.    What restrictions are placed on method overriding?
Ø   Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.

281.    What is casting?
Ø   There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

282.    Name Container classes.
Ø   Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

283.    What class allows you to read objects directly from a stream?
Ø   The ObjectInputStream class supports the reading of objects from input streams.

284.    How are this() and super() used with constructors?
Ø   this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

285.    How is it possible for two String objects with identical values not to be equal under the == operator?
Ø   The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.

286.    What an I/O filter?
Ø   An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

287.    What is the Set interface?
Ø   The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

288.    What is the List interface?
Ø   The List interface provides support for ordered collections of objects.

289.    What is the purpose of the enableEvents() method?
Ø   The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.

290.    What is the difference between the File and RandomAccessFile classes?
Ø   The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

291.    What interface must an object implement before it can be written to a stream as an object?
Ø   An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

292.    What is the ResourceBundle class?
Ø   The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.

293.    What is the difference between a Scrollbar and a ScrollPane?
Ø   A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

294.    What is a Java package and how is it used?
Ø   A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.

295.    What are the Object and Class classes used for?
Ø   The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

296.    What is Serialization and deserialization?
Ø   Serialization is the process of writing the state of an object to a byte stream.
Deserialization is the process of restoring these objects.

297.    what is tunneling?
Ø   Tunneling is a route to somewhere. For example, RMI tunneling is a way to make RMI application get through firewall. In CS world, tunneling means a way to transfer data.

298.    Does the code in finally block get executed if there is an exception and a return statement in a catch block?
Ø   If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.

299.    How you restrict a user to cut and paste from the html page?
Ø   Using JavaScript to lock keyboard keys. It is one of solutions.

300.    Is Java a super set of JavaScript?
Ø   No. They are completely different. Some syntax may be similar.

301.    What is a Container in a GUI?
Ø   A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determine where components should go as a function of the size of the container.

302.    How the object oriented approach helps us keep complexity of software development under control?
Ø   We can discuss such issue from the following aspects:
Objects allow procedures to be encapsulated with their data to reduce potential interference.
Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places.
The well-defined separations of interface and implementation allow constraints to be imposed on inheriting classes while still allowing the flexibility of overriding and overloading.

303.    What is polymorphism?
Ø   Polymorphism allows methods to be written that needn't be concerned about the specifics of the objects they will be applied to. That is, the method can be specified at a higher level of abstraction and can be counted on to work even on objects of yet unconceived classes.

304.    What is design by contract?
Ø   The design by contract specifies the obligations of a method to any other methods that may use its services and also theirs to it. For example, the preconditions specify what the method required to be true when the method is called. Hence making sure that preconditions are. Similarly, postconditions specify what must be true when the method is finished, thus the called method has the responsibility of satisfying the post conditions.
In Java, the exception handling facilities support the use of design by contract, especially in the case of checked exceptions. The assert keyword can be used to make such contracts.

305.    What are use cases?
Ø   A use case describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance. It is part of the analysis of a program. The collection of use cases should, ideally, anticipate all the standard circumstances and many of the extraordinary circumstances possible so that the program will be robust.

306.    What is the difference between interface and abstract class?
Ø    
Interface
Abstract class
interface contains methods that must be abstract
abstract class may contain concrete methods.
interface contains variables that must be static and final
abstract class may contain non-final and final variables.
members in an interface are public by default
abstract class may contain non-public members.
interface is used to "implements"
whereas abstract class is used to "extends".
interface can be used to achieve multiple inheritance
abstract class can be used as a single inheritance.
interface can "extends" another interface
abstract class can "extend" another class and "implements" multiple interfaces.
interface is absolutely abstract
abstract class can be invoked if a main() exists.
interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces.

If given a choice, use interface instead of abstract class.




JDBC

307.    How many types of JDBC Drivers are present and what are they?  
Ø   There are 4 types of JDBC Drivers
Type 1: JDBC-ODBC Bridge Driver
Type 2: Native API Partly Java Driver
Type 3: Network protocol Driver
Type 4: JDBC Net pure Java Driver

308.    What is the fastest type of JDBC driver?  
Ø   JDBC driver performance will depend on a number of issues:
(a) the quality of the driver code,
(b) the size of the driver code,
(c) the database server and its load,
(d) network topology,
(e) the number of times your request is translated to a different API.
In general, all things being equal, you can assume that the more your request and response change hands, the slower it will be. This means that Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at least three translations versus two), and Type 4 drivers are the fastest (only one translation).

309.    What Class.forName will do while loading drivers?  
Ø   It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.
310.    How to Retrieve Warnings?  
Ø   SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object. E.g.
SQLWarning warning = stmt.getWarnings();
if (warning != null) {
  while (warning != null) {
            System.out.println("Message: " + warning.getMessage());
            System.out.println("SQLState: " + warning.getSQLState());
            System.out.print("Vendor error code: ");
            System.out.println(warning.getErrorCode());
            warning = warning.getNextWarning();       }}

311.    What are stored procedures? How is it useful?  
Ø   A stored procedure is a set of statements/commands which reside in the database. The stored procedure is precompiled and saves the database the effort of parsing and compiling sql statements everytime a query is run. Each Database has it's own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db's support writing stored procs in Java and Perl too.
Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kinds of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases.

312.    How to call a Stored Procedure from JDBC?  
Ø   The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure.
E.g.
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
313.    Is the JDBC-ODBC Bridge multi-threaded?  
Ø   No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won't get the advantages of multi-threading.

314.    Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?  
Ø   No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.

315.    What is the advantage of using PreparedStatement?  
Ø   If we are using PreparedStatement the execution time will be less.The PreparedStatement object contains not just an SQL statement,but the SQL statement that has been precompiled.This means that when the PreparedStatement is executed,the RDBMS can just run the PreparedStatement's Sql statement without having to compile it first.

316.    What is a "dirty read"?  
Ø   Quite often in database processing, we come across the situation wherein one transaction can change a value, and a second transaction can read this value before the original change has been committed or rolled back. This is known as a dirty read scenario because there is always the possibility that the first transaction may rollback the change, resulting in the second transaction having read an invalid value. While you can easily command a database to disallow dirty reads, this usually degrades the performance of your application due to the increased locking overhead. Disallowing dirty reads also leads to decreased system concurrency.

317.    What is Metadata and why should I use it?  
Ø   Metadata ('data about data') is information about one of two things: Database information (java.sql.DatabaseMetaData), or Information about a specific ResultSet (java.sql.ResultSetMetaData).
Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns

318.    How do you handle your own transaction ?  
Ø   Connection Object has a method called setAutocommit ( Boolean istrue)
- Default is true
Set the Parameter to false , and begin your transaction

319.    What is the normal procedure followed by a java client to access the db.?  
Ø   The database connection is created in 3 steps:
1.         Find a proper database URL (see FAQ on JDBC URL)
2.         Load the database driver
3.         Ask the Java DriverManager class to open a connection to your database
In java code, the steps are realized in code as follows:
1.         Create a properly formatted JDBR URL for your database. (See FAQ on JDBC                       URL for more information). A JDBC URL has the form
            jdbc:someSubProtocol://myDatabaseServer/theDatabaseName
2. Class.forName("my.database.driver");
3.         Connection conn = DriverManager.getConnection("a.JDBC.URL",                                "databaseLogin","databasePassword");

320.    What is a data source?  
Ø   A DataSource class brings another level of abstraction than directly using a connection object. Data source can be referenced by JNDI. Data Source may point to RDBMS, file System , any DBMS etc.
321.    What are collection pools? What are the advantages?  
Ø   A connection pool is a cache of database connections that is maintained in memory, so that the connections may be reused

322.    Is thin driver provided by Oracle a type 4 driver?  
Ø   YES

323.    What are different types of isolation levels in JDBC and explain where you can use them?  
Ø   If the application needs only committed records, then TRANSACTION_READ_COMMITED isolation is the good choice.
If the application needs to read a row exclusively till you finish your work, then TRANSACTION_REPEATABLE_READ is the best choice.
If the application needs to control all of the transaction problems(dirty read, phantom read and unrepeatable read), you can choose TRANSACTION_SERIALIZABLE for maximum safety. Performance issues have to be taken care with this. E.g Banking applications.
If the application don't have to deal with concurrent transactions, then the best choice is TRANSACTION_NONE to improve performance.
If the application is searching for records from the database then you can easily choose TRANSACTION_READ_UNCOMMITED because you need not worry about other programmes that are inserting records at the same time. It improves performance.

324.    What is the difference between Statement, PreparedStatement and CallableStatemen?  
Ø   Statement is used for static SQL statement with no input and output parameters, PreparedStatement is used for dynamic SQL statement with input parameters and CallableStatement is used for dynamic SQL satement with both input and output parameters, but PreparedStatement and CallableStatement can be used for static SQL statements as well. CallableStatement is mainly meant for stored procedures.
PreparedStatement gives better performance when compared to Statement because it is pre-parsed and pre-compiled by the database once for the first time and then onwards it reuses the parsed and compiled statement. Because of this feature, it significantly improves performance when a statement executes repeatedly, It reduces the overload incurred by parsing and compiling.
CallableStatement gives better performance when compared to PreparedStatement and Statement when there is a requirement for single request to process multiple complex statements. It parses and stores the stored procedures in the database and does all the work at database itself that in turn improves performance. But we loose java portability and we have to depend up on database specific stored procedures.

325.    What is JDBC?
Ø   JDBC may stand for Java Database Connectivity. It is also a trade mark. JDBC is a layer of abstraction that allows users to choose between databases. It allows you to change to a different database engine and to write to a single API. JDBC allows you to write database applications in Java without having to concern yourself with the underlying details of a particular database.

326.    What are the two major components of JDBC?
Ø   One implementation interface for database manufacturers, the other implementation interface for application and applet writers.

327.    What is JDBC Driver interface?
Ø   The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendors driver must provide implementations of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver.

328.    What are the common tasks of JDBC?
Ø   Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers
Register a driver
Specify a database
Open a database connection
Submit a query
Receive results
329.    What interfaces are used by JDBC?
Ø   There are at least 8 packages:
·         Driver
·         Connection
·         Statement
·         PreparedStatement
·         CallableStatement
·         ResultSet
·         ResultSetMetaData
·         DatabaseMetaData

330.    What are the flow statements of JDBC?
Ø   A URL string -->getConnection-->DriverManager-->Driver-->Connection-->Statement-->executeQuery-->ResultSet.

331.    What are the steps involved in establishing a connection?
Ø   This involves two steps: (1) loading the driver and (2) making the connection.

332.    How can you load the drivers?
Ø   Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it: Eg.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

       Another way is to set jdbc.drievers property.

333.    What Class.forName will do while loading drivers?
Ø   It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.

334.    How can you make the connection?
Ø   In establishing a connection is to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea: E.g.
String url = "jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url, "Fernanda", "J8");

335.    How can you create JDBC statements?
Ø   A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. E.g. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object stmt :
Statement stmt = con.createStatement();

336.    How to make a query?
Ø   Create a Statement object and calls the Statement.executeQuery method to select data from the database. The results of the query are returned in a ResultSet object.
Statement stmt = con.createStatement();
ResultSet results = stmt.executeQuery("SELECT data FROM aDatabase ");

337.    How can you retrieve data from the ResultSet?
Ø   Use get methods to retrieve data from returned ResultSet object.
ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
String s = rs.getString("COF_NAME");
The method getString is invoked on the ResultSet object rs , so getString will retrieve (get) the value stored in the column COF_NAME in the current row of rs




338.    How to navigate the ResultSet?
Ø   By default the result set cursor points to the row before the first row of the result set. A call to next() retrieves the first result set row. The cursor can also be moved by calling one of the following ResultSet methods:
·         beforeFirst(): Default position. Puts cursor before the first row of the result set.
·         first(): Puts cursor on the first row of the result set.
·         last(): Puts cursor before the last row of the result set.
·         afterLast() Puts cursor beyond last row of the result set. Calls to previous moves backwards through the ResultSet.
·         absolute(pos): Puts cursor at the row number position where absolute(1) is the first row and absolute(-1) is the last row.
·         relative(pos): Puts cursor at a row relative to its current position where relative(1) moves row cursor one row forward.
339.    What are the different types of Statements?
Ø   Statement (use createStatement method)
Prepared Statement (Use prepareStatement method)
Callable Statement (Use prepareCall)
340.    If you want to use the percent sign (%) as the percent sign and not have it interpreted as the SQL wildcard used in SQL LIKE queries, how to do that?
Ø   Use escape keyword. For example:
          stmt.executeQuery("select tax from sales where tax like '10\%' {escape '\'}");

341.    How to escape ' symbol found in the input line?
Ø   You may use a method to do so:
static public String escapeLine(String s) {
String retvalue = s;
if (s.indexOf ("'") != -1 ) {
  StringBuffer hold = new StringBuffer();
            char c;
            for(int i=0; i < s.length(); i++ ) {
                      if ((c=s.charAt(i)) == '\'' ) {
                               hold.append ("''");
                      }else {
                               hold.append(c);
                      }
  }
  retvalue = hold.toString();
  }
  return retvalue;
}
Note that such method can be extended to escape any other characters that the database driver may interprete another way.

342.    How to make an update?
Ø   Creates a Statement object and calls the Statement.executeUpdate method.
String updateString = "INSERT INTO aDatabase VALUES (some text)";
int count = stmt.executeUpdate(updateString);
343.    How to update a ResultSet?
Ø   You can update a value in a result set by calling the ResultSet.update method on the row where the cursor is positioned. The type value here is the same used when retrieving a value from the result set, for example, updateString updates a String value and updateDouble updates a double value in the result set.
 rs.first();
 rs.updateDouble("balance", rs.getDouble("balance") - 5.00);
The update applies only to the result set until the call to rs.updateRow(), which updates the underlying database.
To delete the current row, use rs.deleteRow().
To insert a new row, use rs.moveToInsertRow().

344.    How can you use PreparedStatement?
Ø   This special type of statement is derived from the more general class, Statement. If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first.

PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");

345.    How to call a Stored Procedure from JDBC?
Ø   The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure; E.g.
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();

346.    How to Retrieve Warnings?
Ø   SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object
SQLWarning warning = stmt.getWarnings();
if (warning != null) {
        while (warning != null) {
        System.out.println("Message: " + warning.getMessage());
        System.out.println("SQLState: " + warning.getSQLState());
        System.out.print("Vendor error code: ");
        System.out.println(warning.getErrorCode());
        warning = warning.getNextWarning();
       }
}

347.    How to set a scroll type?
Ø   Both Statements and PreparedStatements have an additional constructor that accepts a scroll type and an update type parameter. The scroll type value can be one of the following values:
·         ResultSet.TYPE_FORWARD_ONLY Default behavior in JDBC 1.0, application can only call next() on the result set.
·         ResultSet.SCROLL_SENSITIVE ResultSet is fully navigable and updates are reflected in the result set as they occur.
·         ResultSet.SCROLL_INSENSITIVE Result set is fully navigable, but updates are only visible after the result set is closed. You need to create a new result set to see the results.
348.    How to set update type parameter?
Ø   In the constructors of Statements and PreparedStatements, you may use
ResultSet.CONCUR_READ_ONLY The result set is read only.
ResultSet.CONCUR_UPDATABLE The result set can be updated.
You may verify that your database supports these types by calling con.getMetaData().supportsResultSetConcurrency(ResultSet.SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
349.    How to do a batch job?
Ø   By default, every JDBC statement is sent to the database individually. To send multiple statements at one time , use addBatch() method to append statements to the original statement and call executeBatch() method to submit entire statement.
Statement stmt = con.createStatement();
stmt.addBatch("update registration set balance=balance-5.00 where theuser="+theuser);
stmt.addBatch("insert into auctionitems(description, startprice) values("+description+","+startprice+")");
...
int[] results = stmt.executeBatch();
The return result of the addBatch() method is an array of row counts affected for each statement executed in the batch job. If a problem occurred, a java.sql.BatchUpdateException is thrown. An incomplete array of row counts can be obtained from BatchUpdateException by calling its getUpdateCounts() method.
350.    How to store and retrieve an image?
Ø   To store an image, you may use the code:
int itemnumber=400456;
File file = new File(itemnumber+".jpg");
FileInputStream fis = new FileInputStream(file);
PreparedStatement pstmt = con.prepareStatement("update auctionitems set theimage=? where id= ?");
pstmt.setBinaryStream(1, fis, (int)file.length()):
pstmt.setInt(2, itemnumber);
pstmt.executeUpdate();
pstmt.close();
fis.close();

To retrieve an image:
int itemnumber=400456;
byte[] imageBytes;//hold an image bytes to pass to createImage().
 PreparedStatement pstmt = con.prepareStatement("select theimage from auctionitems where id= ?");
pstmt.setInt(1, itemnumber);
ResultSet rs=pstmt.executeQuery();
if(rs.next()) {
    imageBytes = rs.getBytes(1);
}
pstmt.close();
rs.close();
Image auctionimage = Toolkit.getDefaultToolkit().createImage(imageBytes);
351.    How to store and retrive an object?
Ø   A class can be serialized to a binary database field in much the same way as the image. You may use the code above to store and retrive an object.
352.    How to use meta data to check a column type?
Ø   Use getMetaData().getColumnType() method to check data type. For example to retrieve an Integer, you may check it first:
  int count=0;
  Connection con=getConnection();
  Statement stmt= con.createStatement();
  stmt.executeQuery("select counter from aTable");
  ResultSet rs = stmt.getResultSet();
  if(rs.next()) {
      if(rs.getMetaData().getColumnType(1) == Types.INTEGER) {
      Integer i=(Integer)rs.getObject(1);
      count=i.intValue();
      }  }  rs.close();
353.    Why cannot java.util.Date match with java.sql.Date?
Ø   Because java.util.Date represents both date and time. SQL has three types to represent date and time.
java.sql.Date -- (00/00/00)
java.sql.Time -- (00:00:00)
java.sql.Timestamp -- in nanoseconds
Note that they are subclasses of java.util.Date.
354.    How to convert java.util.Date value to java.sql.Date?
Ø   Use the code below:
Calendar currenttime=Calendar.getInstance();
java.sql.Date startdate= new java.sql.Date((currenttime.getTime()).getTime());
or
SimpleDateFormat template = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date enddate = new java.util.Date("10/31/99");
java.sql.Date sqlDate = java.sql.Date.valueOf(template.format(enddate));


Q.      What does setAutoCommit do?
A       When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:
con.setAutoCommit(false);
Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly.
con.setAutoCommit(false);
PreparedStatement updateSales =
          con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50); updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal =
con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);

Q.      How to Make Updates to Updatable Result Sets?
A       Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.
Connection con =
          DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt =
          con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet uprs =
          stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

Q:      What is the difference among "dropping a table", "truncating a table" and "deleting all records" from a table.
 A:     Dropping :  (Table structure  + Data are deleted), Invalidates the dependent objects ,Drops the indexes
Truncating:  (Data alone deleted), Performs an automatic commit, Faster than delete
Delete : (Data alone deleted), Doesn’t perform automatic commit

Q:      What are the Large object types suported by Oracle?
A:      Blob and Clob.
  
Q:      What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?
 A:     Cursors allow row-by-row prcessing of the resultsets.
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.
Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.
Most of the times, set based operations can be used instead of cursors.

Q:      What are triggers? How to invoke a trigger on demand?
A:     Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table.
Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined.
Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster.


Q:      what is a join and explain different types of joins.
A:     Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.
Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

Q:      What is a self join?
A:     Self join is just like any other join, except that two instances of the same table will be joined in the query. 


Servlets

355.    What is the servlet?
Ø   Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet may be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database.

356.    What's the difference between servlets and applets?
Ø   Servlets are to servers; applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

357.    What's the advantages using servlets than using CGI?
Ø   Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. It is efficient, convenient, powerful, portable, secure and inexpensive. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with Java Servlet API, a standard Java extension.

358.    What are the uses of Servlets?
Ø   A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

359.    What's the Servlet Interface?
Ø   The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.
Servlets-->Generic Servlet-->HttpServlet-->MyServlet.
The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

360.    When a servlet accepts a call from a client, it receives two objects. What are they?
Ø   ServletRequest: which encapsulates the communication from the client to the server.
ServletResponse: which encapsulates the communication from the servlet back to the client.
ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

361.    What information that the ServletRequest interface allows the servlet access to?
Ø   Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. The input stream, ServletInputStream. Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods.

362.    What information that the ServletResponse interface gives the servlet methods for replying to the client?
Ø   It Allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

363.    If you want a servlet to take the same action for both GET and POST request, what should you do?
èFrom doGet() call doPost() or vice-versa

364.    What is the servlet life cycle?
Ø   Each servlet has the same life cycle:
A server loads and initializes the servlet (init())
The servlet handles zero or more client requests (service())
The server removes the servlet (destroy()) (some servers do this step only when they shut down)

365.    Which code line must be set before any of the lines that use the PrintWriter?
Ø   setContentType() method must be set before transmitting the actual document.


366.    How HTTP Servlet handles client requests?
Ø   An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

367.    When using servlets to build the HTML, you build a DOCTYPE line, why do you do that?
Ø   I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors.
http://validator.w3.org and
http://www.htmlhelp.com/tools/validator/
are two major online validators

368.    Request parameter How to find whether a parameter exists in the request object?  
Ø   1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));
2. boolean hasParameter = request.getParameterMap().contains(theParameter);
(which works in Servlet 2.3+)


369.    How can I send user authentication information while making URLConnection?  
Ø   You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.
URL url =new URL("http://localhost:8080/examples/servlet/TestServlet1");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; WinNT4.0; en-US; rv:1.1) Gecko/20020826");
conn.setRequestProperty("Accept-Language", "de-at");
conn.setRequestProperty("Accept-Charset", "ISO-8859-1, utf-8;q=0.66, *;q=0.66");…………….

370.    Can we use the constructor, instead of init(), to initialize servlet?  
Ø   Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or ServletContext.

371.    How can a servlet refresh automatically if some new data has entered the database?  
Ø   You can use a client-side Refresh (F5) or Server Push(call internally one more time)

372.    What is Server Side Push and how is it implemented and when is it useful?  
Ø   Server Side push is useful when data needs to change regularly on the clients application or browser, without intervention from client. Standard examples might include apps like Stock's Tracker, Current News etc. As such server cannot connect to client's application automatically. The mechanism used is, when client first connects to Server, (Either through login etc..), then Server keeps the TCP/IP connection open.
It's not always possible or feasible to keep the connection to Server open. So another method used is, to use the standard HTTP protocols ways of refreshing the page, which is normally supported by all browsers.
<META HTTP-EQUIV="Refresh" CONTENT="5;URL=/servlet/stockquotes/">
This will refresh the page in the browser automatically and loads the new data every 5 seconds.

373.    The code in a finally clause will never fail to execute, right?  
Ø   Using System.exit(1); in try block will not allow finally code to execute.

374.    What is HttpTunneling?  
Ø   HTTP tunneling is used to encapsulate other protocols within the HTTP or HTTPS protocols. Normally the intra-network of an organization is blocked by a firewall and the network is exposed to the outer world only through a specific web server port , that listens for only HTTP requests. To use any other protocol, that by passes the firewall, the protocol is embedded in HTTP and send as HttpRequest.
www.http-tunnel.com -: HTTP-Tunnel acts as a socks server, allowing subscribers to use your Internet applications despite of restrictive firewalls anonymously. Your Internet application sends data to the HTTP-Tunnel Client, which in turn tunnels the data over HTTP (port 80) to the HTTP-Tunnel servers. The servers then send the data to the intended destination and forward the responses back to the HTTP-Tunnel client. This forwarding technique effectively bypasses firewalls, permitting the users to successfully use most Internet applications.
375.    What are the phases in JSP?  
Ø   a) Translation phase ? conversion of JSP to a Servlet source, and then Compilation of servlet source into a class file. The translation phase is typically carried out by the JSP engine itself, when it receives an incoming request for the JSP page for the first time
b) init(), service() and destroy() method as usual as Servlets.

376.    How many cookies can one set in the response object of the servlet? Also, are there any restrictions on the size of cookies?  
Ø   If the client is using Netscape, the browser can receive and store 300 total cookies
4 kilobytes per cookie (including name)
20 cookies per server or domain

377.    What’s the difference between sendRedirect( ) and forward( ) methods?  
Ø   A sendRedirect method creates a new request (it’s also reflected in browser’s URL ) where as forward method forwards the same request to the new target(hence the change is NOT reflected in browser’s URL).
The previous request scope objects are no longer available after a redirect because it results in a new request, but it?s available in forward.
SendRedirectis slower compared to forward.

378.    Is there some sort of event that happens when a session object gets bound or unbound to the session?  
Ø   HttpSessionBindingListener will hear the events When an object is added and/or remove from the session object, or when the session is invalidated, in which case the objects are first removed from the session, whether the session is invalidated manually or automatically (timeout).

379.    What do the differing levels of bean storage (page, session, application) mean?  
Ø   page life time - NO storage. This is the same as declaring the variable in a scriptlet and using it from there.
session life time - request.getSession(true).putValue ("myKey", myObj);
application level - getServletConfig().getServletContext().setAttribute("myKey ",myObj )
request level - The storage exists for the lifetime of the request, which may be forwarded between jsp's and servlets.

380.    Is it true that servlet containers service each request by creating a new thread? If that is true, how does a container handle a sudden dramatic surge in incoming requests without significant performance degradation?  
Ø   The implementation depends on the Servlet engine. For each request generally, a new Thread is created. But to give performance boost, most containers, create and maintain a thread pool at the server startup time. To service a request, they simply borrow a thread from the pool and when they are done, return it to the pool.
For this thread pool, upper bound and lower bound is maintained. Upper bound prevents the resource exhaustion problem associated with unlimited thread allocation. The lower bound can instruct the pool not to keep too many idle threads, freeing them if needed.

381.    Can I just abort processing a JSP?  
Ø   Yes. Because your JSP is just a servlet method, you can just put (whereever necessary) a < % return; % >

382.    What is URL Encoding and URL Decoding ?  
Ø   URL encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex Characters and Decoding is the reverse process converting all Hex Characters back their normal form.
For Example consider this URL, /ServletsDirectory/Hello'servlet/
When Encoded using URLEncoder.encode("/ServletsDirectory/Hello'servlet/") the output is
http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2FThis can be decoded back using
URLDecoder.decode("http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F")


383.    Do objects stored in a HTTP Session need to be serializable? Or can it store any object?  
Ø   Yes, the objects need to be serializable, but only if your servlet container supports persistent sessions. Most lightweight servlet engines (like Tomcat) do not support this. However, many EJB-enabled servlet engines do. Even if your engine does support persistent sessions, it is usually possible to disable this feature.

384.    What is the difference between session and cookie?  
Ø   The difference between session and a cookie is two-fold.
1) session should work regardless of the settings on the client browser. even if users decide to forbid the cookie (through browser settings) session still works. there is no way to disable sessions from the client browser.
2) session and cookies differ in type and amount of information they are capable of storing.
Javax.servlet.http.Cookie class has a setValue() method that accepts Strings. javax.servlet.http.HttpSession has a setAttribute() method which takes a String to denote the name and java.lang.Object which means that HttpSession is capable of storing any java object. Cookie can only store String objects.

385.    What is the difference between ServletContext and ServletConfig?  
Ø   Both are interfaces.
The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method.
The ServletContext interface provides information to servlets regarding the environment in which they are running. It also provides standard way for servlets to write events to a log file.

386.    What are the differences between GET and POST service methods?  
Ø   A GET request is a request to get a resource from the server. Choosing GET as the "method" will append all of the data to the URL and it will show up in the URL bar of your browser. The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters. A POST request is a request to post (to send) form data to a resource on the server. A POST on the other hand will (typically) send the information through a socket back to the webserver and it won't show up in the URL bar. You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!

387.    What is the difference between GenericServlet and HttpServlet?  
Ø   GenericServlet is for servlets that might not use HTTP, like for instance FTP service.As of only Http is implemented completely in HttpServlet.
The GenericServlet has a service() method that gets called when a client request is made. This means that it gets called by both incoming requests and the HTTP requests are given to the servlet as they are.

388.    What is the Max amount of information that can be saved in a Session Object ?  
Ø   As such there is no limit on the amount of information that can be saved in a Session Object. Only the RAM available on the server machine is the limitation. The only limit is the Session ID length(Identifier) , which should not exceed more than 4K. If the data to be store is very huge, then it's preferred to save it to a temporary file onto hard disk, rather than saving it in session. Internally if the amount of data being saved in Session exceeds the predefined limit, most of the servers write it to a temporary cache on Hard disk.(if persistent session are allowed)

389.    What is Servlet chaining?  
Ø   response object from one servlet is passed as request to another Servlet. Try this example and you will come to know what servlet chaining is all about.
public class ServletA extends HttpServlet {
  public void init(ServletConfig config) throws ServletException {}
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
            String aValue = request.getParameter("valueA");
            System.out.println("ServletA read: "+aValue);
            request.setAttribute("ReadTheValue","Yes");
            //do other servlet stuff...just don't open a write and output to the page....
            request.getRequestDispatcher("/servletB").forward(req,resp);
  }
}

public class ServletB extends HttpServlet {
  public void init(ServletConfig config) throws ServletException {}
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
            String aValue = request.getParameter("valueA");
            System.out.println("ServletB also got the value: "+aValue);
            System.out.println("ServletB also found attribute: "+request.getAttribute("ReadTheValue"));
            //finish the task and write to the page.
  }
}

Advantages:
1) Chaining reduces the demand on a single servlet
2) Modular design
3) Enables different complex processes to be maintained by more than one person.
4) Allows steps in a process to be modified (eg servlet 1 -> servlet 2 or servlet 1 -> servlet 3 -> servlet 2, etc)
5) Removes the complexity in a single servlet

390.    I am using servlets. I need to store an object NOT a string in a cookie. Is that possible? The help file says BASE64 encoding is suggested for use with binary values. How can I do that?  

Ø   You could serialize the object into a ByteArrayOutputStream and then Base64 encode the resulting byte[]. We must keep in mind the size limitations of a cookie and the overhead of transporting it back and forth between the browser and the server.
Limitations are:
* at most 300 cookies
* at most 4096 bytes per
* at most 20 cookies per unique host or domain name


JSP
Q.      What is JSP? Describe its concept.
A.      JSP is a technology that combines HTML/XML markup languages and elements of Java programming Language to return dynamic content to the Web client, it is normally used to handle Presentation logic of a web application, although it may have business logic.
Q.      What are the lifecycle phases of a JSP?
A.      JSP page looks like a HTML page but is a servlet. When presented with JSP page the JSP engine does the following 7 phases.
1. Page translation: -page is parsed, and a java file which is a servlet is created.
2. Page compilation: page is compiled into a class file
3. Page loading : This class file is loaded.
4. Create an instance :- Instance of servlet is created
5. jspInit() method is called
6. _jspService is called to handle service calls
7. _jspDestroy is called to destroy it when the servlet is not required.

Q.      What is a translation unit?
A.      JSP page can include the contents of other HTML pages or other JSP files. This is done by using the include directive. When the JSP engine is presented with such a JSP page it is converted to one servlet class and this is called a translation unit, Things to remember in a translation unit is that page directives affect the whole unit, one variable declaration cannot occur in the same unit more than once, the standard action jsp:useBean cannot declare the same bean twice in one unit.

Q.      How is JSP used in the MVC model?
A.      JSP is usually used for presentation in the MVC pattern (Model View Controller) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client.

Q.      What are context initialization parameters?
A.      Context initialization parameters are specified by the <context-param> in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or JSP.

Q.      What is an output comment?
A.      A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as un-interpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
JSP Syntax
<!—comment [ <%= expression %> ] -->
Example 1

<!-- This is a comment sent to client on  <%= (new java.util.Date()).toLocaleString() %>
-->

Displays in the page source:
<!-- This is a comment sent to client on January 24, 2004 -->

Q.      What is a Hidden Comment?
A:      A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.
You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>.
JSP Syntax
<%-- comment --%>
Examples
<%@ page language="java" %>
<html>
<head><title>A Hidden Comment </title></head>
<body>
<%-- This comment will not be visible to the colent in the page source --%>
</body>
</html>

 Q:     What is a Expression?
 A:     An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression 
   
Q:      What is a Declaration?
A:      A declaration declares one or more variables or methods for use later in the JSP source file.
A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.
<%! somedeclarations %>
<%! int i = 0; %>
<%! int a, b, c; %>

Q:      What is a Scriptlet?
 A:     A scriptlet can contain any number of language statements, variable or method declarations, or expressions t  hat are valid in the page scripting language. Within scriptlet tags, you can
1.Declare variables or methods to use later in the file (see also Declaration).
2.Write expressions valid in the page scripting language (see also Expression).
3.Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag.

You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.

Q.      What are the implicit objects, List them?
A.      Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects are:
·                    request
·                    response
·                    pageContext
·                    session
·                    application
·                    out
·                    config         
·                    page
·                    exception

Q.      What’s the difference between forward and sendRedirect?
A.      When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container And then returns to the calling method. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

Q.      What are the different scope values for the <jsp:useBean>?
A.      The different scope values for <jsp:useBean> are:
o   page , request,  session,  application

Q.      Why are JSP pages the preferred API for creating a web-based client program?
A.      Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.

Q.      Is JSP technology extensible?
A.      Yes, it is. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

Q.      What is difference between custom JSP tags and beans?
A.      Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. Custom tags and beans accomplish the same goals – encapsulating complex behavior into simple and accessible forms. There are several differences:
·                    Custom tags can manipulate JSP content; beans cannot.
·                    Complex operations can be reduced to a significantly simpler form with custom tags than with beans.
·                    Custom tags require quite a bit more work to set up than do beans.
·                    Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page.
·                    Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.


Q.      How many JSP scripting elements are there and what are they?
A.      There are three scripting language elements: declarations, scriptlets, expressions.

Q.      How do I include static files within a JSP page?
A.      Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. The following example shows the syntax:
            <%@ include file="copyright.html" %>
Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.

Q.      How can I implement a thread-safe JSP page?
A.      You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" % > within your JSP page.

Q.      Can we implement an interface in a JSP?
A.      No

Q.      What is the difference between ServletContext and PageContext?
A.      ServletContext: Gives the information about the container.
PageContext: Gives the information about the Request

Q.      What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
A.      request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource, context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.

Q.      How to pass information from JSP to included JSP?
A.      Using <%jsp:param> tag.

Q.      What is the difference between directive include and jsp include?
A.      <%@ include>: Used to include static resources during translation time.
 JSP include: Used to include dynamic content or static content during runtime.

Q.      What is the difference between RequestDispatcher and sendRedirect?
A.   getServletContext().getRequestDispatcher("/servlet/anyServlet").forward(request,response): server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects.
Q.      How does JSP handle runtime exceptions?
A.      JSP provides a rather elegant mechanism for handling runtime exceptions. Although you can provide your own exception handling within JSP pages, it may not be possible to anticipate all situations. By making use of the page directive's errorPage attribute, it is possible to forward an uncaught exception to an error handling JSP page for processing. For example,
            <%@ page isErrorPage="false" errorPage="errorHandler.jsp" %>
informs the JSP engine to forward any uncaught exception to the JSP page errorHandler.jsp. It is then necessary for errorHandler.jsp to flag itself as a error processing page using the directive:
            <%@ page isErrorPage="true" %>
This allows the Throwable object describing the exception to be accessed within a scriptlet through the implicit exception object.

Q.      How do you delete a Cookie within a JSP?
A.      Cookie mycook = new Cookie("name","value");
          response.addCookie(mycook);
          Cookie killmycook = new Cookie("mycook","value");
          killmycook.setMaxAge(0);
          killmycook.setPath("/");
          killmycook.addCookie(killmycook);

Q.      How do I mix JSP and SSI #include?
A.      If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.
          <!--#include file="data.inc"-->
But it’s a little trickier if you want the server to evaluate any JSP code that’s inside the included file. If your data.inc file contains jsp code you will have to use
          <%@ include="data.inc" %>
The <!--#include file="data.inc"--> is used for including non-JSP files.

Q.      I made my class Cloneable but I still get Can’t access protected method clone. Why?
A.      Some of the Java books imply that all you have to do in order to have your class support clone() is implement the Cloneable interface. Not so. Perhaps that was the intent at some point, but that’s not the way it works currently. As it stands, you have to implement your own public clone() method, even if it doesn’t do anything special and just calls super.clone().

Q.      Why is XML such an important development?
A.      It removes two constraints which were holding back Web developments: dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for; the complexity of full SGML, whose syntax allows many powerful but hard-to-program options. XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for.

Q.      How do I find whether a parameter exists in the request object?
          boolean hasFoo = !(request.getParameter("foo") == null
          || request.getParameter("foo").equals(""));
or
boolean hasParameter =
          request.getParameterMap().contains(theParameter); //(which works in Servlet 2.3+)

Q.      How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
A.      You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>

Q.      How do I use comments within a JSP page?
A.      You can use “JSP-style” comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client. For example:
          <%-- the scriptlet is now commented out
          <%
          out.println("Hello World");
          %>
          --%>
You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:
<!-- (c) 2004 -->
Of course, you can also use comments supported by your JSP scripting language within your scriptlets. For example, assuming Java is the scripting language, you can have:
          <%
          //some comment
          /**
          yet another comment
          **/
          %>

Q.      Response has already been commited error. What does it mean?
A.      This error show only when you try to redirect a page after you already have written something in your page. This happens because HTTP specification force the header to be set up before the lay out of the page can be shown (to make sure of how it should be displayed, content-type="text/html” or “text/xml” or “plain-text” or “image/jpg", etc.) When you try to send a redirect status (Number is line_status_402), your HTTP server cannot send it right now if it hasn’t finished to set up the header. If not starter to set up the header, there are no problems, but if it ’s already begin to set up the header, then your HTTP server expects these headers to be finished setting up and it cannot be the case if the stream of the page is not over… In this last case it’s like you have a file started with <HTML Tag><Some Headers><Body>some output (like testing your variables.) Before you indicate that the file is over (and before the size of the page can be setted up in the header), you try to send a redirect status. It s simply impossible due to the specification of HTTP 1.0 and 1.1

Q.      How do I use a scriptlet to initialize a newly instantiated bean?
A.      A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.
The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.
<jsp:useBean id="foo" class="com.Bar.Foo" >
<jsp:setProperty name="foo" property="today"
value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>"/ >
<%-- scriptlets calling bean setter methods go here --%>
</jsp:useBean >

Q.      How can I enable session tracking for JSP pages if the browser has disabled cookies?
A.      We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the browser, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
          hello1.jsp
          <%@ page session="true" %>
          <%
          Integer num = new Integer(100);
          session.putValue("num",num);
          String url =response.encodeURL("hello2.jsp");
          %>
          <a href='<%=url%>'>hello2.jsp</a>
          hello2.jsp
          <%@ page session="true" %>
          <%
          Integer i= (Integer )session.getValue("num");
          out.println("Num value in session is "+i.intValue());

Q.      How can I declare methods within my JSP page?
A.      You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions. Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare.
For example:
          <%!
                   public String whereFrom(HttpServletRequest req) {
                   HttpSession ses = req.getSession();
                   ...
                   return req.getRemoteHost();
                   }
          %>
          <%
                   out.print("Hi there, I see that you are coming in from ");
          %>
          <%= whereFrom(request) %>
          Another Example:
          file1.jsp:
                   <%@page contentType="text/html"%>
                   <%!
                             public void test(JspWriter writer) throws IOException{
                             writer.println("Hello!");
                             }
                   %>
          file2.jsp
                   <%@include file="file1.jsp"%>
                   <html>
                   <body>
                             <%test(out);% >
                   </body>
                   </html>

Q.      Is there a way I can set the inactivity lease period on a per-session basis?
A.      Typically, a default inactivity lease period for all sessions is set within your JSP engine admin screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis. This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created. For example:
          <%
                   session.setMaxInactiveInterval(300);
          %>
would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.

Q.      How does a servlet communicate with a JSP page?
A.                ……………….              
getServletConfig().getServletContext().getRequestDispatcher
                      ("/jsp/Bean1.jsp").forward(request, response);
                  
Q.      How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default?
A.      One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSP engine. In any case, your new superclass has to fulfill the contract with the JSP engine by:
Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final Additionally, your servlet superclass also needs to do the following:
1. the service() method has to invoke the _jspService() method
2. the init() method has to invoke the jspInit() method
3. the destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may throw a translation error.
Once the superclass has been developed, you can have your JSP extend it as follows:
          <%@ page extends="packageName.ServletName" %>

Q.      How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values?
A.      You could make a simple wrapper function, like
          <%!
                   String blanknull(String s) {
                   return (s == null) ? "" : s;
                   }
          %>
          then use it inside your JSP form, like
          <input type="text" name="shoesize" value="<%=blanknull(shoesize)% >" >

Q.      How can I get to print the stacktrace for an exception occuring within my JSP page?
A.      You cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The following snippet demonstrates how you can print a stacktrace from within a JSP error page:
          <%@ page isErrorPage="true" %>
          <%
                    out.println("        ");
                    PrintWriter pw = response.getWriter();
                    exception.printStackTrace(pw);
                   out.println(" ");
          %>

Q.      How do you pass an InitParameter to a JSP?
A.      The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and prints them to the console.
          <%@ page import="java.util.*" %>
          <%!
                   ServletConfig cfg =null;
                   public void jspInit(){
                   ServletConfig cfg=getServletConfig();
                   for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {
                             String name=(String)e.nextElement();
                             String value = cfg.getInitParameter(name);
                             System.out.println(name+"="+value);
                   }
                    }
          %>

Q.      How can my JSP page communicate with an EJB Session Bean?
A.      The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean:
<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account" %>
          <%!
          //declare a "global" reference to an instance of the home interface of the session bean
          AccountHome accHome=null;
          public void jspInit() {
          //obtain an instance of the home interface
          InitialContext cntxt = new InitialContext( );
          Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
          accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
          }
          %>
          <%
          //instantiate the session bean
          Account acct = accHome.create();
          //invoke the remote methods
          acct.doWhatever(...);
          // etc etc...
          %>

Q:      Explain the life-cycle mehtods in JSP?
A:      The generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. the HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.      

Q:      Explain the life cycle methods of a Servlet.
A:      The javax.servlet.Servlet interface defines the three methods known as life-cycle method.
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
First the servlet is constructed, then initialized wih the init() method.
Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet.
The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.

Q:      Explain the directory structure of a web application?
A:      The directory structure of a web application consists of two parts.
A private directory called WEB-INF
A public resource directory which contains public resource folder.
WEB-INF folder consists of
1. web.xml
2. classes directory
3. lib directory
   
Q:      What are the common mechanisms used for session tracking?
A:      Cookies, SSL sessions, URL- rewriting
   
Q:      What is preinitialization of a servlet?
A:      A container does not initialize the servlet as soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

Q:      What is the difference between Difference between doGet() and doPost()?
A:      A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following:
http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN
doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string. 

Q:      What is the difference between HttpServlet and GenericServlet?
A:     A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.

391.    How can my application get to know when a HttpSession is removed?  
Ø   Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method.
Create an instance of that class and put that instance in HttpSession.

392.    In the Servlet 2.4 specification SingleThreadModel has been deprecates, why?  
Ø   Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.

393.    How do I mix JSP and SSI #include?  
Ø   If you're just including raw HTML, use the #include directive as usual inside your .jsp file.
<!--#include file="data.inc"-->
But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. If your data.inc file contains jsp code you will have to use
<%@ vinclude="data.inc" %>
The <!--#include file="data.inc"--> is used for including non-JSP files.

394.    Can a JSP page process HTML FORM data?  
Ø   Yes. However, unlike servlets, you are not required to implement HTTP-protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression as:
<%
String item = request.getParameter("item");
int howMany = new Integer(request.getParameter("units")).intValue();
%>
or
<%= request.getParameter("item") %>

395.    What JSP lifecycle methods can I override?  
Ø   You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().
The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:
<%!
public void jspInit() {
. . .
}
%>

<%!
public void jspDestroy() {
. . .
}
%>

396.    How do I perform browser redirection from a JSP page?  
Ø   You can use the response implicit object to redirect the browser to a different resource, as:
response.sendRedirect("http://www.foo.com/path/error.html");
You can also physically alter the Location HTTP header attribute, as shown below:
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn = "/newpath/index.html";
response.setHeader("Location",newLocn);
%>
You can also use the: <jsp:forward page="/newpage.jsp" /> Also note that you can only use this before any output has been sent to the client. I beleve this is the case with the response.sendRedirect() method as well.
If you want to pass any paramateres then you can pass using <jsp:forward page="/servlet/login"> <jsp:param name="username" value="jsmith" /> </jsp:forward>>

397.    Can a JSP page instantiate a serialized bean?  
Ø   No problem! The useBean action specifies the beanName attribute, which can be used for indicating a serialized bean. For example:
<jsp:useBean id="shop" type="shopping.CD" beanName="CD" /> <jsp:getProperty name="shop" property="album" />
A couple of important points to note. Although you would have to name your serialized file "filename.ser", you only indicate "filename" as the value for the beanName attribute. Also, you will have to place your serialized file within the WEB-INF\jsp\beans directory for it to be located by the JSP engine.

398.    Can you make use of a ServletOutputStream object from within a JSP page?  
Ø   No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients. A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not. A page author can always disable the default buffering for any page using a page directive as:
<%@ page buffer="none" %>

399.    What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?  
Ø   Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

400.    Can I stop JSP execution while in the midst of processing a request?  
Ø   Yes. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick (asuming Java is your scripting language) is to use the return statement when you want to terminate further processing. For example, consider:
<% if (request.getParameter("foo") != null) {
            // generate some html or update bean property
  } else {
/* output some error message or provide redirection back to the input form after creating a memento bean updated with the 'valid' form elements that were input. this bean can now be used by the previous form to initialize the input elements that were valid then, return from the body of the _jspService() method to terminate further processing */
          return;
  }
%>

401.    How can I get to view any compilation/parsing errors at the client while developing JSP pages?  
Ø   With JSWDK 1.0, set the following servlet initialization property within the \WEB-INF\servlets.properties file for your application:
jsp.initparams=sendErrToClient=true
This will cause any compilation/parsing errors to be sent as part of the response to the client.

402.    Is there a way to reference the "this" variable within a JSP page?  
Ø   Yes, there is. Under JSP 1.0, the page implicit object is equivalent to "this", and returns a reference to the servlet generated by the JSP page.

403.    How do I instantiate a bean whose constructor accepts parameters using the useBean tag?  
Ø   Consider the following bean: package bar;
public class FooBean {
          public FooBean(SomeObj arg) {
                   ...
          }
          //getters and setters here
}
The only way you can instantiate this bean within your JSP page is to use a scriptlet. For example, the following snippet creates the bean with session scope:
<% SomeObj x = new SomeObj(...);
bar.FooBean foobar = new FooBean(x);
session.putValue("foobar",foobar);
%> You can now access this bean within any other page that is part of the same session as:
<% bar.FooBean foobar = session.getValue("foobar");
%>
To give the bean "application scope", you will have to place it within the ServletContext as:
<%
application.setAttribute("foobar",foobar);
%>
To give the bean "request scope", you will have to place it within the request object as:
<%
request.setAttribute("foobar",foobar);
%>
If you do not place the bean within the request, session or application scope, the bean can be accessed only within the current JSP page (page scope).
Once the bean is instantiated, it can be accessed in the usual way:
<jsp:getProperty name="foobar" property="someProperty"/ jsp:setProperty name="foobar" property="someProperty" value="someValue">

404.    Can I invoke a JSP error page from a servlet?  
Ø   Yes, you can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute. However, note that you can do this from only within controller servlets. If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following translation error:
java.lang.IllegalStateException: Cannot forward as OutputStream or Writer has already been obtained
The following code snippet demonstrates the invocation of a JSP error page from within a controller servlet:
protected void sendErrorRedirect(HttpServletRequest request, HttpServletResponse response, String errorPageURL, Throwable e) throws ServletException, IOException {
request.setAttribute ("javax.servlet.jsp.jspException", e);
getServletConfig().getServletContext(). getRequestDispatcher(errorPageURL).forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
// do something
} catch (Exception ex) {
try {
sendErrorRedirect(request,response,"/jsp/MyErrorPage.jsp",ex);
} catch (Exception e) {
e.printStackTrace();
}
}
}

405.    How can you store international / Unicode characters into a cookie?  
Ø   One way is, before storing the cookie URLEncode it.
URLEnocder.encoder(str);
And use URLDecoder.decode(str) when you get the stored cookie.
Note: You must always use a relative URL as the value for the errorPage attribute.

406.    How do you prevent the Creation of a Session in a JSP Page and why?  
Ø   By default, a JSP page will automatically create a session for the request if one does not exist. However, sessions consume resources and if it is not necessary to maintain a session, one should not be created. For example, a marketing campaign may suggest the reader visit a web page for more information. If it is anticipated that a lot of traffic will hit that page, you may want to optimize the load on the machine by not creating useless sessions.
The page directive is used to prevent a JSP page from automatically creating a session:
<%@ page session="false">

407.    What is the difference between a tag handler and a tag handler class?  
Ø   The only difference between a tag handler and a tag handler class is that a tag handler is written in JSP syntax, while a tag handler class is written in the Java language.

Sumit Agarwal
J2ee Developer

EJB
408.    What cannot be or is recommended not to be done using EJB?  
Ø   · Enterprise Bean must not use read/write static fields. Using read-only static fields is allowed. Therefore, it is recommended that all static fields in enterprise bean class be declared as final.
· Enterprise Bean must not use thread synchronization primitives to synchronize execution of multiple instances.
· Enterprise bean must not attempt to manage threads. Enterprise bean must not attempt to start, stop, suspend, or resume a thread; or to change a thread's priority or name. The enterprise bean must not attempt to manage thread groups.
· Enterprise Bean must not use the AWT functionality to attempt to output information to a display, or to input information from a keyboard.
· Enterprise bean must not use java.io package to attempt to access files and directories in file system.
· Enterprise bean must not attempt to directly read or write a file descriptor.
· Enterprise bean must not attempt to listen on a socket, accept connections on a socket, or use a socket for multicast.
· Enterprise bean must not attempt to set the socket factory used by ServerSocket, Socket, or the stream handler factory used by URL.
· Enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language.
· The enterprise bean must not attempt to use the Reflection API to access information that the security rules of the Java programming language make unavailable.
· Enterprise bean must not attempt to create a class loader; obtain the current class loader; set the context class loader; set security manager; create a new security manager; stop the JVM; or change the input, output, and error streams.
· Enterprise bean must not attempt to gain access to packages and classes that the usual rules of the Java programming language make unavailable to the enterprise bean.
· Enterprise bean must not attempt to define a class in a package.
· Enterprise bean must not attempt to use the subclass and object substitution features of the Java Serialization Protocol.
· Enterprise bean must not attempt to obtain the security policy information for a particular code source.
· Enterprise bean must not attempt to access or modify the security configuration objects (Policy, Security, Provider, Signer, and Identity).
· Enterprise bean must not attempt to pass this as an argument or method result. The enterprise bean must pass the result of SessionContext.getEJBObject() or EntityContext. getEJBObject() instead.
Enterprise bean must not attempt to load a native library.

409.    What is EJB?
Ø   EJB stands for Enterprise Java Bean and is the widely-adopted server side component architecture for J2EE. it enables rapid development of mission-critical application that are versatile, reusable and portable across middleware while protecting IT investment and preventing vendor lock-in.

410.    What is EJB role in J2EE?
Ø   EJB technology is the core of J2EE. It enables developers to write reusable and portable server-side business logic for the J2EE platform.

411.    What is the difference between EJB and Java beans?
Ø   EJB is a specification for J2EE server, not a product; Java beans may be a graphical component in IDE.
412.    What are the key features of the EJB technology?
Ø   EJB components are server-side components written entirely in the Java programming language
EJB components contain business logic only - no system-level programming & services, such as transactions, security, life-cycle, threading, persistence, etc. are automatically managed for the EJB component by the EJB server.
EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and secure.
EJB components are fully portable across any EJB server and any OS.
EJB architecture is wire-protocol neutral--any protocol can be utilized like IIOP,JRMP, HTTP, DCOM,etc.

413.    What are the key benefits of the EJB technology?
Ø   Rapid application development
Broad industry adoption
Application portability
Protection of IT investment
414.    How many enterprice beans?
Ø   There are three kinds of enterprise beans:
·         session beans,
·         entity beans, and
·         message-driven beans.

415.    What is message-driven bean?
Ø   A message-driven bean combines features of a session bean and a Java Message Service (JMS) message listener, allowing a business component to receive JMS. A message-driven bean enables asynchronous clients to access the business logic in the EJB tier.

416.    What is Entity Bean and Session Bean ?
Ø   Entity Bean is a Java class which implements an Enterprise Bean interface and provides the implementation of the business methods. There are two types: Container Managed Persistence(CMP) and Bean-Managed Persistence(BMP).
Session Bean is used to represent a workflow on behalf of a client. There are two types: Stateless and Stateful. Stateless bean is the simplest bean. It doesn't maintain any conversational state with clients between method invocations. Stateful bean maintains state between invocations.


417.    Are enterprise beans allowed to use Thread.sleep()?  
Ø   Enterprise beans make use of the services provided by the EJB container, such as life-cycle management. To avoid conflicts with these services, enterprise beans are restricted from performing certain operations: Managing or synchronizing threads. So Thread.sleep() is not advisible. It also depends on the container that it allows it or not.

418.    Is it possible to write two EJB's that share the same Remote and Home interfaces, and have different bean classes? if so, what are the advantages/disadvantages?  
Ø   It's certainly possible. In fact, there's an example that ships with the Inprise Application Server of an Account interface with separate implementations for CheckingAccount and SavingsAccount, one of which was CMP and one of which was BMP.

419.    Is it possible to specify multiple JNDI names when deploying an EJB?  
Ø   No. To achieve this you have to deploy your EJB multiple times each specifying a different JNDI name.

420.    Is there any way to force an Entity Bean to store itself to the db? I don't wanna wait for the container to update the db, I want to do it NOW! Is it possible?  
Ø   Specify the transaction attribute of the bean as RequiresNew. Then as per section 11.6.2.4 of the EJB v 1.1 spec EJB container automatically starts a new transaction before the method call. The container also performs the commit protocol before the method result is sent to the client.

421.    I am developing a BMP Entity bean. I have noticed that whenever the create method is invoked, the ejbLoad() and the ejbStore() methods are also invoked. I feel that once my database insert is done, having to do a select and update SQL queries is major overhead. is this behavior typical of all EJB containers? Is there any way to suppress these invocations?  
Ø   This is the default behaviour for EJB. The specification states that ejbLoad() will be called before every transaction and ejbStore() after every transaction. Each Vendor has optimizations, which are proprietary for this scenario.

422.    Can an EJB send asynchronous notifications to its clients?  
Ø   Asynchronous notification is a known hole in the first versions of the EJB spec. The recommended solution to this is to use JMS, which is becoming available in J2EE-compliant servers. The other option, of course, is to use client-side threads and polling. This is not an ideal solution, but it's workable for many scenarios.

423.    How can I access EJB from ASP?  
Ø   You can use the Java 2 Platform, Enterprise Edition Client Access Services (J2EETM CAS) COM Bridge 1.0, currently downloadable from http://developer.java.sun.com/developer/earlyAccess/j2eecas/

424.    Is there a guarantee of uniqueness for entity beans?  
Ø   There is no such guarantee. The server (or servers) can instantiate as many instances of the same underlying Entity Bean (with the same PK) as it wants. However, each instance is guaranteed to have up-to-date data values, and be transactionally consistent, so uniqueness is not required. This allows the server to scale the system to support multiple threads, multiple concurrent requests, and multiple hosts.

425.    How do the six transaction attributes map to isolation levels like "dirty read"? Will an attribute like "Required" lock out other readers until I'm finished updating?  
Ø   The Transaction Attributes in EJB do not map to the Transaction Isolation levels used in JDBC. This is a common misconception. Transaction Attributes specify to the container when a Transaction should be started, suspended(paused) and committed between method invocations on Enterprise JavaBeans. For more details and a summary of Transaction Attributes refer to section 11.6 of the EJB 1.1 specification.

426.    I have created a remote reference to an EJB in FirstServlet. Can I put the reference in a servlet session and use that in SecondServlet?  
Ø   Yes. The EJB client (in this case your servlet) acquires a remote reference to an EJB from the Home Interface; that reference is serializable and can be passed from servlet to servlet. If it is a session bean, then the EJB server will consider your web client's servlet session to correspond to a single EJB session, which is usually (but not always) what you want.

427.    Can the primary key in the entity bean be a Java primitive type such as int?  
Ø   The primary key can't be a primitive type--use the primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive)

428.    What's new in the EJB 2.0 specification?  
Ø   Following are the main features supported in EJB 2.0
* Integration of EJB with JMS
* Message Driven Beans
* Implement additional Business methods in Home interface which
are not specific for bean instance.
·        EJB QL.

429.    What is the need of Remote and Home interface. Why cant it be in one?  
Ø   In a few words, I would say that the main reason is because there is a clear division of roles and responsabilities between the two interfaces.
The home interface is your way to communicate with the container, that is who is responsible of creating, locating even removing one or more beans.
The remote interface is your link to the bean that will allow you to remotely access to all its methods and members.
As you can see there are two distinct elements (the container and the beans) and you need two different interfaces for accessing to both of them.

430.    What is the difference between Java Beans and EJB?  
Ø   Java Beans are client-side objects and EJBs are server side object, and they have completely different development, lifecycle, purpose.

431.     With regard to Entity Beans, what happens if both my EJB Server and Database crash, what will happen to unsaved changes? Is there any transactional log file used?  
Ø   Actually, if your EJB server crashes, you will not even be able to make a connection to the server to perform a bean lookup, as the server will no longer be listening on the port for incoming JNDI lookup requests. You will lose any data that wasn't committed prior to the crash. This is where you should start looking into clustering your EJB server.
Another Answer
Any unsaved and uncommited changes are lost the moment your EJB Server crashes. If your database also crashes, then all the saved changes are also lost unless you have some backup or some recovery mechanism to retrieve the data. So consider database replication and EJB Clustering for such scenarios, though the occurence of such a thing is very very rare. All databse have the concept of log files(for exampe oracle have redo log files concept). So if data bases crashes then on starting up they fill look up the log files to perform all pending jobs. But is EJB crashes, It depend upon the container how frequenlty it passivates or how frequesntly it refreshes the data with Database.

432.     Can you control when passivation occurs?  
Ø   The developer, according to the specification, cannot directly control when passivation occurs. Although for Stateful Session Beans, the container cannot passivate an instance that is inside a transaction. So using transactions can be a strategy to control passivation.
The ejbPassivate() method is called during passivation, so the developer has control over what to do during this exercise and can implement the require optimized logic.
Some EJB containers, such as BEA WebLogic, provide the ability to tune the container to minimize passivation calls.
Taken from the WebLogic 6.0 DTD -
"The passivation-strategy can be either "default" or "transaction". With the default setting the container will attempt to keep a working set of beans in the cache. With the "transaction" setting, the container will passivate the bean after every transaction (or method call for a non-transactional invocation)."

433.    The EJB specification says that we cannot use Bean Managed Transaction in Entity Beans. Why?  
Ø   The short, practical answer is... because it makes your entity beans useless as a reusable component. Also, transaction management is best left to the application server - that's what they're there for. It's all about atomic operations on your data. If an operation updates more than one entity then you want the whole thing to succeed or the whole thing to fail, nothing in between. If you put commits in the entity beans then it's very difficult to rollback if an error occurs at some point late in the operation.

434.    Can I invoke Runtime.gc() in an EJB?  
Ø   You shouldn't.
What will happen depends on the implementation, but the call will most likely be ignored. You should leave system level management like garbage collection for the container to deal with. After all, that's part of the benefit of using EJBs, you don't have to manage resources yourself.

435.    What is clustering? What are the different algorithms used for clustering?  
Ø   Clustering is grouping machines together to transparantly provide enterprise services.The client does not now the difference between approaching one server or approaching a cluster of servers.Clusters provide two benefits: scalability and high availability. Further information can be found in the JavaWorld article J2EE Clustering.

436.    What is the advantage of using Entity bean for database operations, over directly using JDBC API to do database operations? When would I use one over the other?  
Ø   Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. There are two types of Entity Beans Container Managed and Bean Mananged. In Container Managed Entity Bean - Whenever the instance of the bean is created the container automatically retrieves the data from the DB/Persistance storage and assigns to the object variables in bean for user to manipulate or use them. For this the developer needs to map the fields in the database to the variables in deployment descriptor files (which varies for each vendor).
In the Bean Managed Entity Bean - The developer has to specifically make connection, retrieve values, assign them to the objects in the ejbLoad() which will be called by the container when it instantiates a bean object. Similarly in the ejbStore() the container saves the object values back the the persistence storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container. Apart from this, when you use Entity beans you don’t need to worry about database transaction handling, database connection pooling etc. which are taken care by the ejb container. But in case of JDBC you have to explicitly do the above features. The great thing about the entity beans of container managed, whenever the connection is failed during the transaction processing, the database consistency is maintained automatically. the container writes the data stored at persistant storage of the entity beans to the database again to provide the database consistancy. where as in jdbc api, we, developers has to do manually.

437.    What is the role of serialization in EJB?  
Ø   A big part of EJB is that it is a framework for underlying RMI: remote method invocation. You're invoking methods remotely from JVM space 'A' on objects which are in JVM space 'B' -- possibly running on another machine on the network.
To make this happen, all arguments of each method call must have their current state plucked out of JVM 'A' memory, flattened into a byte stream which can be sent over a TCP/IP network connection, and then deserialized for reincarnation on the other end in JVM 'B' where the actual method call takes place.
If the method has a return value, it is serialized up for streaming back to JVM ‘A’. Thus the requirement that all EJB methods arguments and return values must be serializable. The easiest way to do this is to make sure all your classes implement java.io.Serializable.

438.    What is EJB QL?  
Ø   EJB QL is a Query Language provided for navigation across a network of enterprise beans and dependent objects defined by means of container managed persistence. EJB QL is introduced in the EJB 2.0 specification. The EJB QL query language defines finder methods for entity beans with container managed persistence and is portable across containers and persistence managers. EJB QL is used for queries of two types of finder methods: Finder methods that are defined in the home interface of an entity bean and which return entity objects. Select methods, which are not exposed to the client, but which are used by the Bean Provider to select persistent values that are maintained by the Persistence Manager or to select entity objects that are related to the entity bean on which the query is defined.

439.    Is it legal to have static initializer blocks in EJB?  
Ø   Although technically it is legal, static initializer blocks are used to execute some piece of code before executing any constructor or method while instantiating a class. Static initializer blocks are also typically used to initialize static fields - which may be illegal in EJB if they are read/write - In EJB this can be achieved by including the code in either the ejbCreate(), setSessionContext() or setEntityContext() methods.

440.    Is it possible to stop the execution of a method before completion in a SessionBean?  
Ø   Stopping the execution of a method inside a Session Bean is not possible without writing code inside the Session Bean. This is because you are not allowed to access Threads inside an EJB.

441.    What is the difference between session and entity beans? When should I use one or the other?  
Ø   An entity bean represents persistent global data from the database; a session bean represents transient user-specific data that will die when the user disconnects (ends his session). Generally, the session beans implement business methods (e.g. Bank.transferFunds) that call entity beans (e.g. Account.deposit, Account.withdraw)

442.    Is there any default cache management system with Entity beans ? In other words whether a cache of the data in database will be maintained in EJB ?  
Ø   Caching data from a database inside the Application Server are what Entity EJB's are used for.The ejbLoad() and ejbStore() methods are used to synchronize the Entity Bean state with the persistent storage(database). Transactions also play an important role in this scenario. If data is removed from the database, via an external application - your Entity Bean can still be "alive" the EJB container. When the transaction commits, ejbStore() is called and the row will not be found, and the transaction rolled back.

443.    Why is ejbFindByPrimaryKey mandatory?  
Ø   An Entity Bean represents persistent data that is stored outside of the EJB Container/Server. The ejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the container, similar to a SELECT statement in SQL. By making this method mandatory, the client programmer can be assured that if they have the primary key of the Entity Bean, then they can retrieve the bean without having to create a new bean each time - which would mean creating duplications of persistent data and break the integrity of EJB.

444.    Why do we have a remove method in both EJBHome and EJBObject?  
Ø   With the EJBHome version of the remove, you are able to delete an entity bean without first instantiating it (you can provide a PrimaryKey object as a parameter to the remove method). The home version only works for entity beans. On the other hand, the Remote interface version works on an entity bean that you have already instantiated. In addition, the remote version also works on session beans (stateless and statefull) to inform the container of your loss of interest in this bean.

445.    How can I call one EJB from inside of another EJB?  
Ø   EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home/LocalHome Interface of the other bean, then acquire an instance reference, and so forth.

446.    What is the difference between a Server, a Container, and a Connector?  
Ø   An EJB server is an application, usually a product such as BEA WebLogic, that provides (or should provide) for concurrent client connections and manages system resources such as threads, processes, memory, database connections, network connections, etc.
An EJB container runs inside (or within) an EJB server, and provides deployed EJB beans with transaction and security management, etc. The EJB container insulates an EJB bean from the specifics of an underlying EJB server by providing a simple, standard API between the EJB bean and its container.
A Connector provides the ability for any Enterprise Information System (EIS) to plug into any EJB server which supports the Connector architecture. See http://java.sun.com/j2ee/connector/ for more indepth information on Connectors.

447.    How is persistence implemented in enterprise beans?  
Ø   Persistence in EJB is taken care of in two ways, depending on how you implement your beans: container managed persistence (CMP) or bean managed persistence (BMP)
For CMP, the EJB container which your beans run under takes care of the persistence of the fields you have declared to be persisted with the database - this declaration is in the deployment descriptor. So, anytime you modify a field in a CMP bean, as soon as the method you have executed is finished, the new data is persisted to the database by the container.
For BMP, the EJB bean developer is responsible for defining the persistence routines in the proper places in the bean, for instance, the ejbCreate(), ejbStore(), ejbRemove() methods would be developed by the bean developer to make calls to the database. The container is responsible, in BMP, to call the appropriate method on the bean. So, if the bean is being looked up, when the create() method is called on the Home interface, then the container is responsible for calling the ejbCreate() method in the bean, which should have functionality inside for going to the database and looking up the data.

448.    What is an EJB Context?  
Ø   EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details.

449.    Is method overloading allowed in EJB?  
Ø   Yes you can overload methods

450.    Should synchronization primitives be used on bean methods?  
Ø   No. The EJB specification specifically states that the enterprise bean is not allowed to use thread primitives. The container is responsible for managing concurrent access to beans at runtime

451.    Are we allowed to change the transaction isolation property in middle of a transaction?  
Ø   No. You cannot change the transaction isolation level in the middle of transaction.

452.    What is a Message Driven Bean, What functions does a message driven bean have and how do they work in collaboration with JMS?  
Ø   Message driven beans are the latest addition to the family of component bean types defined by the EJB specification. The original bean types include session beans, which contain business logic and maintain a state associated with client sessions, and entity beans, which map objects to persistent data.
Message driven beans will provide asynchrony to EJB based applications by acting as JMS message consumers. A message bean is associated with a JMS topic or queue and receives JMS messages sent by EJB clients or other beans.
Unlike entity beans and session beans, message beans do not have home or remote interfaces. Instead, message driven beans are instantiated by the container as required. Like stateless session beans, message beans maintain no client-specific state, allowing the container to optimally manage a pool of message-bean instances.
Clients send JMS messages to message beans in exactly the same manner as they would send messages to any other JMS destination. This similarity is a fundamental design goal of the JMS capabilities of the new specification.
To receive JMS messages, message driven beans implement the javax.jms.MessageListener interface, which defines a single "onMessage()" method.
When a message arrives, the container ensures that a message bean corresponding to the message topic/queue exists (instantiating it if necessary), and calls its onMessage method passing the client's message as the single argument. The message bean's implementation of this method contains the business logic required to process the message.
Note that session beans and entity beans are not allowed to function as message beans.

453.    The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes?  
Ø   The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate instance for each client request.
Another Answer
The instance pool maintainence is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the app server. How it is implemented, it is again up to the implementer.


454.    What is the advantage of puttting an Entity Bean instance from the "Ready State" to "Pooled state"?   
Ø   The idea of the "Pooled State" is to allow a container to maintain a pool of entity beans that has been created, but has not been yet "synchronized" or assigned to an EJBObject. This mean that the instances do represent entity beans, but they can be used only for serving Home methods (create or findBy), since those methods do not relay on the specific values of the bean. All these instances are, in fact, exactly the same, so, they do not have meaningful state. Jon Thorarinsson has also added: It can be looked at it this way:
If no client is using an entity bean of a particular type there is no need for cachig it (the data is persisted in the database).
Therefore, in such cases, the container will, after some time, move the entity bean from the "Ready State" to the "Pooled state" to save memory.
Then, to save additional memory, the container may begin moving entity beans from the "Pooled State" to the "Does Not Exist State", because even though the bean's cache has been cleared, the bean still takes up some memory just being in the "Pooled State".

455.    Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB?  
Ø   You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be consider as "passed-by-value", that means that it's read-only in the EJB. If anything is altered from inside the EJB, it won't be reflected back to the HttpSession of the Servlet Container.The "pass-by-reference" can be used between EJBs Remote Interfaces, as they are remote references. While it IS possible to pass an HttpSession as a parameter to an EJB object, it is considered to be "bad practice (1)" in terms of object oriented design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejb's api. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction will be flexible enough to support it. (1) Core J2EE design patterns (2001)

456.    What is the difference between a "Coarse Grained" Entity Bean and a "Fine Grained" Entity Bean?  
Ø   A 'fine grained' entity bean is pretty much directly mapped to one relational table, in third normal form.
A 'coarse grained' entity bean is larger and more complex, either because its attributes include values or lists from other tables, or because it 'owns' one or more sets of dependent objects. Note that the coarse grained bean might be mapped to a single table or flat file, but that single table is going to be pretty ugly, with data copied from other tables, repeated field groups, columns that are dependent on non-key fields, etc.
Fine grained entities are generally considered a liability in large systems because they will tend to increase the load on several of the EJB server's subsystems (there will be more objects exported through the distribution layer, more objects participating in transactions, more skeletons in memory, more EJB Objects in memory, etc.) The other side of the coin is that the 1.1 spec doesn't mandate CMP Error! No index entries found.support for dependent objects (or even indicate how they should be supported), which makes it more difficult to do coarse grained objects with CMP. The EJB 2.0 specification improves this in a huge way.

457.    What is EJBDoclet?  
Ø   EJBDoclet is an open source JavaDoc doclet that generates a lot of the EJB related source files from custom JavaDoc comments tags embedded in the EJB source file. E.g. XDoclet

458.    What are the main benefits of J2EE?  
Ø   J2EE provides the following:
Faster solutions delivery time to market. J2EE uses "containers" to simplify development. J2EE containers provide for the separation of business logic from resource and lifecycle management, which means that developers can focus on writing business logic -- their value add -- rather than writing enterprise infrastructure. For example, the Enterprise JavaBeansTM (EJBTM) container (implemented by J2EE technology vendors) handles distributed communication, threading, scaling, transaction management, etc. Similarly, Java Servlets simplify web development by providing infrastructure for component, communication, and session management in a web container that is integrated with a web server.
Freedom of choice. J2EE technology is a set of standards that many vendors can implement. The vendors are free to compete on implementations but not on standards or APIs. Sun supplies a comprehensive J2EE Compatibility Test Suite (CTS) to J2EE licensees. The J2EE CTS helps ensure compatibility among the application vendors which helps ensure portability for the applications and components written for J2EE. J2EE brings Write Once, Run AnywhereTM (WORATM) to the server.
Simplified connectivity. J2EE technology makes it easier to connect the applications and systems you already have and bring those capabilities to the web, to cell phones, and to devices. J2EE offers Java Message Service for integrating diverse applications in a loosely coupled, asynchronous way. J2EE also offers CORBA support for tightly linking systems through remote method calls. In addition, J2EE 1.3 adds J2EE Connectors for linking to enterprise information systems such as ERP systems, packaged financial applications, and CRM applications.
By offering one platform with faster solution delivery time to market, freedom of choice, and simplified connectivity, J2EE helps IT by reducing TCO and simultaneously avoiding single-source for their enterprise software needs.

459.    Name a few Design Patterns used in J2ee applications  
Ø   MVC, Front Controller, Session Facade, Data Access Object

460.    What is the deployment order for the deployed server components in WebLogic server?  
Ø   § JDBC Connection Pools
§ JDBC Multi Pools
§ JDBC Data Sources
§ JDBC Tx Data Sources
§ JMS Connection Factories
§ JMS Servers
§ Connector Components
§ EJB Components
§ Web App Components
--- An examination of the log file .,.,

461.    Why do the create() or find() method return the remote reference or a primary key only?  
Ø   The EJB Specification prohibits this behavior, and the weblogic.ejbc compiler checks for this behavior and prohibits any polymorphic type of response from a create() or find() method.
The reason the create() and find() methods cannot return any object or primitive type is similar to the reason that regular constructors can be cast into the class itself or any of it?s super classes.
For example
A a = new A() or
A b = new B() where B is a child of A.
You cannot do, for example Vector v = new A();

462.    What technologies are included in J2EE?  
Ø   The primary technologies in J2EE are: Enterprise JavaBeansTM (EJBsTM), JavaServer PagesTM (JSPsTM), Java Servlets, the Java Naming and Directory InterfaceTM (JNDITM), the Java Transaction API (JTA), CORBA, and the JDBCTM data access API.

463.    What is the Java Authentication and Authorization Service (JAAS) 1.0?  
Ø   The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. JAAS is a Java programing language version of the standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization.

464.    What are the enhancements in EJB 2.0 specification with respect to Asynchronous communication?  
Ø   EJB 2.0 mandates integration between JMS and EJB.
We have specified the integration of Enterprise JavaBeans with the Java Message Service, and have introduced message-driven beans. A message-driven bean is a stateless component that is invoked by the container as a result of the arrival of a JMS message. The goal of the message-driven bean model is to make developing an enterprise bean that is asynchronously invoked to handle the processing of incoming JMS messages as simple as developing the same functionality in any other JMS MessageListener.

465.    What are the enhancements in EJB 2.0 with respect to CMP?  
Ø   EJB 2.0 extends CMP to include far more robust modeling capability, with support for declarative management of relationships between entity EJBs. Developers no longer need to re-establish relationships between the various beans that make up their application -- the container will restore the connections automatically as beans are loaded, allowing bean developers to navigate between beans much as they would between any standard Java objects.
EJB 2.0 also introduces for the first time a portable query language, based on the abstract schema, not on the more complex database schema. This provides a database and vendor-independent way to find entity beans at run time, based on a wide variety of search criteria.

466.    Can you briefly describe about local interfaces?  
Ø   EJB was originally designed around remote invocation using the Java Remote Method Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for these calls using RMI/IIOP. This design allowed for maximum flexibility in developing applications without consideration for the deployment scenario, and was a strong feature in support of a goal of component reuse in J2EE.
Many developers are using EJBs locally -- that is, some or all of their EJB calls are between beans in a single container.
With this feedback in mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container. This does not involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performance of applications in which co-location is planned.
Local interfaces also provide the foundation for container-managed relationships among entity beans with container-managed persistence.

467.    What are the special design care that must be taken when you work with local interfaces?  
Ø   It is important to understand that the calling semantics of local interfaces are different from those of remote interfaces. For example, remote interfaces pass parameters using call-by-value semantics, while local interfaces use call-by-reference.
This means that in order to use local interfaces safely, application developers need to carefully consider potential deployment scenarios up front, then decide which interfaces can be local and which remote, and finally, develop the application code with these choices in mind.
While EJB 2.0 local interfaces are extremely useful in some situations, the long-term costs of these choices, especially when changing requirements and component reuse are taken into account, need to be factored into the design decision.

468.    What happens if remove( ) is never invoked on a session bean?  
Ø   In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The number of beans in cache is managed by the container.
In case of stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool.

469.    What is the difference between creating a distributed application using RMI and using a EJB architecture?  
Ø   It is possible to create the same application using RMI and EJB. But in case of EJB the container provides the requisite services to the component if we use the proper syntax. It thus helps in easier development and lesser error and use of proven code and methodology. But the investment on application server is mandatory in that case. But this investment is warranted because it results in less complex and maintainable code to the client, which is what the end client wants. Almost all the leading application servers provide load balancing and performance tuning techniques. In case of RMI we have to code the services and include in the program the way to invoke these services.

470.    Can the bean class implement the EJBObject class directly? If not why?  
Ø   It is better not to do it will make the Bean class a remote object and its methods can be accessed without the containers? security, and transaction implementations if our code by mistake passed it in one of its parameters. Its just a good design practice.

471.    What does isIdentical() method return in case of different type of beans?  
Ø   Stateless ? true always
Stateful ? depends whether the references point to the same session object
Entity ? Depends whether the primary key is the same and the home is same

472.    How should you type cast a remote object? Why?
Ø   A client program that is intended to be interoperable with all compliant EJB Container implementations must use the javax.rmi.PortableRemoteObject.narrow(...) method to perform type-narrowing of the client-side representations of the remote home and remote interfaces. Programs using the cast operator for narrowing the remote and remote home interfaces are likely to fail if the Container implementation uses RMI-IIOP as the underlying communication transport.

473.    What should you do in a passivate method?  
Ø   You try to make all nontransient variables, which are not one of the following to null. For the given list the container takes care of serializing and restoring the object when activated.
Serializable objects, null, UserTransaction, SessionContext, JNDI contexts in the beans context, reference to other beans, references to connection pools.
Things that must be handled explicitly are like a open database connection etc. These must be closed and set to null and retrieved back in the activate method.

474.    What is the relationship between local interfaces and container-managed relationships?  
Ø   Entity beans that have container-managed relationships with other entity beans, must be accessed in the same local scope as those related beans, and therefore typically provide a local client view. In order to be the target of a container-managed relationship, an entity bean with container-managed persistence must provide a local interface.

475.    What does a remove method do for different cases of beans?  
Ø   Stateless Session : Does not do anything to the bean as moving the bean from free pool to cache are managed by the container depending on load.
Stateful Session: Removes the bean from the cache.
Entity Bean: Deletes the bean (data) from persistent storage.

476.    How does a container-managed relationship work?  
Ø   An entity bean accesses related entity beans by means of the accessor methods for its container-managed relationship fields, which are specified by the cmr-field elements of its abstract persistence schema defined in the deployment descriptor. Entity bean relationships are defined in terms of the local interfaces of the related beans, and the view an entity bean presents to its related beans is defined by its local home and local interfaces. Thus, an entity bean can be the target of a relationship from another entity bean only if it has a local interface.

477.    What is the new basic requirement for a CMP entity bean class in 2.0 from that of ejb 1.1?  
Ø   It must be abstract class. The container extends it and implements methods which are required for managing the relationships.

478.    What are the basic classes required in the client for invoking an EJB?  
Ø   The home and the remote interfaces, the implementation of the Naming Context Factory, the stubs and skeletons.
In some App servers the stubs and the skeletons can be dynamically downloaded from the server

479.    What is the difference between Message Driven Beans and Stateless Session beans?  
Ø   In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways:
§ Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls.
§ Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic.
Note: Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary.
§ The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls.

480.    What is the need for Clustering?  
Ø   To scale the application so that it
1. Is Highly Available
2. Has High Throughput.

481.    What are the benefits of Clustering (Workload Management)?  
Ø   They are
1. It balances client processing requests, allowing incoming work requests to be distributed according to a configured Workload Management selection policy.
2. It provides fail over capability by redirecting client requests to a running server when one or more servers are unavailable. This improves the availability of applications and administrative services.
3. It enables systems to be scaled up to serve a higher client load than provided by the basic configuration. With server groups and clones additional instances of servers can easily be added to the configuration.
4. It enables servers to be transparently maintained and upgraded while applications remain available for users.
5. It centralizes administration of application servers and other objects.

482.    What are the types of Scaling?  
Ø   There are two types of scaling
1. Vertical Scaling
2. Horizontal Scaling.

483.    What is Vertical Scaling?  
Ø   When multiple server clones of an application server are defined on the same physical m/c, it is called Vertical Scaling. The objective is to use the processing power of that m/c more efficiently.

484.    What is Horizontal Scaling?  
Ø   When Clones of an application server are defined on multiple physical m/c, it is called Horizontal Scaling. The objective is to use more than one less powerful m/c more efficiently.

485.    What is a Server Group?  
Ø   A server group is a template of an Application Server(and its contents) i.e, it is a logical representation of the application server. It has the same structure and attributes as the real Application Server, but it is not associated with any node, and does not correspond to any real server process running on any node.

486.    What is a Clone?  
Ø   The copies of a server group are called Clones. But unlike a Server Group Clones are associated with a node and are real server process running in that node.

487.    What is Ripple Effect?  
Ø   The process of propagating the changes in the properties of a server group during runtime to all the associated clones is called Ripple Effect.

488.    What level of Load Balancing is possible with EJBs?  
Ø   The workload management service provides load balancing for the following types of enterprise beans
1. Homes of entity or session beans
2. Instances of entity beans
3. Instances of stateless session beans


489.    How JDBC services can be used in clustered environment?  
Ø   Identical DataSource has to be created in each clustered server instances and configure to use different connection pools.
490.    What are the services that should not be used in a Clustered Environment?  
Ø   Non-clustered services:
1. File Services
2. Time services
3. Weblogic events
4. Weblogic Workspaces (In WebLogic 5.1)

491.    Mention some tools to cluster Web Servers?  
Ø   Web Servers can be clustered using
1. Edge Server.
2. DNS

492.    What is in-memory replication?  
Ø   The process by which the contents in the memory of one physical m/c are replicated in all the m/c in the cluster is called in-memory replication.

493.    What are the types of messaging?
Ø   There are two kinds of Messaging. Synchronous messaging involves a client that waits for the server to respond to a message. Asynchronous messaging involves a client that does not wait for a message from the server. An event is used to trigger a message from a server.

494.    What is publish/subscribe messaging?
Ø   With publish/subscribe message passing the sending application/client establishes a named topic in the JMS broker/server and publishes messages to this queue. The receiving clients register (specifically, subscribe) via the broker to messages by topic; every subscriber to a topic receives each message published to that topic. There is a one-to-many relationship between the publishing client and the subscribing clients.

495.    Why doesn’t the JMS API provide end-to-end synchronous message delivery and notification of delivery?
Ø   Some messaging systems provide synchronous delivery to destinations as a mechanism for implementing reliable applications. Some systems provide clients with various forms of delivery notification so that the clients can detect dropped or ignored messages. This is not the model defined by the JMS API. JMS API messaging provides guaranteed delivery via the once-and-only-once delivery semantics of PERSISTENT messages. In addition, message consumers can insure reliable processing of messages by using either CLIENT_ACKNOWLEDGE mode or transacted sessions. This achieves reliable delivery with minimum synchronization and is the enterprise messaging model most vendors and developers prefer. The JMS API does not define a schema of systems messages (such as delivery notifications). If an application requires acknowledgment of message receipt, it can define an application-level acknowledgment message.
496.    What are the core JMS-related objects required for each JMS-enabled application?
Ø   Each JMS-enabled client must establish the following:
o   A connection object provided by the JMS server (the message broker)
o   Within a connection, one or more sessions, which provide a context for message sending and receiving
o   Within a session, either a queue or topic object representing the destination (the message staging area) within the message broker
o   Within a session, the appropriate sender or publisher or receiver or subscriber object (depending on whether the client is a message producer or consumer and uses a point-to-point or publish/subscribe strategy, respectively). Within a session, a message object (to send or to receive)
497.    What is the Role of the JMS Provider?
Ø   The JMS provider handles security of the messages, data conversion and the client triggering. The JMS provider specifies the level of encryption and the security level of the message, the best data type for the non-JMS client.

498.    How does a typical client perform the communication? -
o   Use JNDI to locate administrative objects.
o   Locate a single ConnectionFactory object.
o   Locate one or more Destination objects.
o   Use the ConnectionFactory to create a JMS Connection.
o   Use the Connection to create one or more Session(s).
o   Use a Session and the Destinations to create the MessageProducers and MessageConsumers needed.
o   Perform your communication.
499.    Give an example of using the point-to-point model.
Ø   The point-to-point model is used when the information is specific to a single client. For example, a client can send a message for a print out, and the server can send information back to this client after completion of the print job.

500.    How does the Application server handle the JMS Connection? -
Ø    
o   App server creates the server session and stores them in a pool.
o   Connection consumer uses the server session to put messages in the session of the JMS.
o   Server session is the one that spawns the JMS session.
o   Applications written by Application programmers creates the message listener.
501.    Is it possible for an EJB client to marshal an object of class java.lang.Class to an EJB?  
Ø   Technically yes, spec. compliant NO! - The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language.

502.    What is the default transaction attribute for an EJB?  
Ø   There is no default transaction attribute for an EJB. Section 11.5 of EJB v1.1 spec says that the deployer must specify a value for the transaction attribute for those methods having container managed transaction. In weblogic, the default transaction attribute for EJB is SUPPORTS.

503.    For Entity Beans, What happens to an instance field not mapped to any persistent storage,when the bean is passivated?  
Ø   The specification infers that the container never serializes an instance of an Entity bean (unlike stateful session beans). Thus passivation simply involves moving the bean from the "ready" to the "pooled" bin. So what happens to the contents of an instance variable is controlled by the programmer. Remember that when an entity bean is passivated the instance gets logically disassociated from it's remote object.
Be careful here, as the functionality of passivation/activation for Stateless Session, Stateful Session and Entity beans is completely different. For entity beans the ejbPassivate method notifies the entity bean that it is being disassociated with a particular entity prior to reuse or for dereferenc.
504.    Can a Session Bean be defined without ejbCreate() method?  
Ø   The ejbCreate() methods is part of the bean's lifecycle, so, the compiler will not return an error because there is no ejbCreate() method.
However, the J2EE spec is explicit:
the home interface of a Stateless Session Bean must have a single create() method with no arguments, while the session bean class must contain exactly one ejbCreate() method, also without arguments.
Stateful Session Beans can have arguments (more than one create method) stateful beans can contain multiple ejbCreate() as long as they match with the home interface definition
You need a reference to your EJBObject to starts with. For that Sun insists on putting a method for creating that reference (create method in the home interface). The EJBObject does matter here. Not the actual bean.
505.    Is there any way to read values from an entity bean without locking it for the rest of the transaction (e.g. read-only transactions)? We have a key-value map bean which deadlocks during some concurrent reads. Isolation levels seem to affect the database only, and we need to work within a transaction.  
Ø   The only thing that comes to (my) mind is that you could write a 'group accessor' - a method that returns a single object containing all of your entity bean's attributes (or all interesting attributes). This method could then be placed in a 'Requires New' transaction. This way, the current transaction would be suspended for the duration of the call to the entity bean and the entity bean's fetch/operate/commit cycle will be in a separate transaction and any locks should be released immediately. Depending on the granularity of what you need to pull out of the map, the group accessor might be overkill.



No comments:

Post a Comment