Java Interview Questions

 Q.How can you achieve Multiple Inheritance in Java? Ans: Java's interface mechanism can be used to implement multiple inheritance, with one important difference from c++ way of doing MI: the inherited interfaces must be abstract. This obviates the need to choose between different implementations, as with interfaces there are no implementations. Q.How To Replace the Characters in a String? Ans:

  • Replace all occurrences of 'a' with 'o' String newString = string.replace('a', 'o'); Replacing Substrings in a String

static String replace(String str, String pattern, String replace) { int s = 0; int e = 0; StringBuffer result = new StringBuffer(); while ((e = str.indexOf(pattern, s)) >= 0) { result.append(str.substring(s, e)); result.append(replace); s = e+pattern.length(); } result.append(str.substring(s)); return result.toString(); } Converting a String to Upper or Lower Case

  • Convert to upper case

String upper = string.toUpperCase(); // Convert to lower case String lower = string.toLowerCase(); Converting a String to a Number int i = Integer.parseInt("123"); long l = Long.parseLong("123"); float f = Float.parseFloat("123.4"); double d = Double.parseDouble("123.4e10"); Breaking a String into Words String aString = "word1 word2 word3"; StringTokenizer parser = new StringTokenizer(aString); while (parser.hasMoreTokens()) { processWord(parser.nextToken()); Q.What is a transient variable? Ans: A transient variable is a variable that may not be serialized. If you don't want some field not to be serialized, you can mark that field transient or static. Q.What is the difference between Serializalble and Externalizable interface? Ans: When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject()two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process. Q.How many methods in the Externalizable interface? Ans: There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal(). Q.How many methods in the Serializable interface? Ans: 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. Q.How to make a class or a bean serializable? Ans: By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that class is serializable. Q.What is the serialization? Ans: 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. Q.What are synchronized methods and synchronized statements? Ans: 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. Q.What is synchronization and why is it important? Ans: 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. Q.What is the purpose of finalization? Ans: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. Q.What classes of exceptions may be caught by a catch clause? Ans: A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Q.What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy? Ans: The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented. Q.What happens when a thread cannot acquire a lock on an object? Ans: 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. Q.What restrictions are placed on method overriding? Ans: 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. Q.What restrictions are placed on method overloading? Ans: Two methods may not have the same name and argument list but different return types. Q.How does multithreading take place on a computer with a single CPU? Ans: 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. Q.How is it possible for two String objects with identical values not to be equal under the == operator? Ans: 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. Q.How are this() and super() used with constructors? Ans: this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. Q.What class allows you to read objects directly from a stream? Ans: The ObjectInputStream class supports the reading of objects from input streams. Q.What is the ResourceBundle class? Ans: 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. Q.What interface must an object implement before it can be written to a stream as an object? Ans: An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. Q.What is Serialization and deserialization? Ans: Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects. Q.What are the Object and Class classes used for? Ans: 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. Q.Can you write Java code for declaration of multiple inheritance in Java ? Ans: Class C extends A implements B { } Q.What do you mean by multiple inheritance in C++ ? Ans: Multiple inheritance is a feature in C++ by which one class can be of different types. Say class teachingAssistant is inherited from two classes say teacher and Student. Q.Write the Java code to declare any constant (say gravitational constant) and to get its value. Ans: Class ABC { static final float GRAVITATIONAL_CONSTANT = 9.8; public void getConstant() { system.out.println("Gravitational_Constant: " + GRAVITATIONAL_CONSTANT); } } Q.Given two tables Student(SID, Name, Course) and Level(SID, level) write the SQL statement to get the name and SID of the student who are taking course = 3  and at freshman level. Ans: SELECT Student.name, Student.SID FROM Student, Level WHERE Student.SID = Level.SID AND Level.Level = "freshman" AND Student.Course = 3; Q.What do you mean by virtual methods? Ans: virtual methods are used to use the polymorhism feature in C++. Say class A is inherited from class B. If we declare say fuction f() as virtual in class B and override the same function in class A then at runtime appropriate method of the class will be called depending upon the type of the object. Q.What do you mean by static methods? Ans: By using the static method there is no need creating an object of that class to use that method. We can directly call that method on that class. For example, say class A has static function f(), then we can call f() function as A.f(). There is no need of creating an object of class A. Q.What do mean by polymorphism, inheritance, encapsulation? Ans: Polymorhism: is a feature of OOPl that at run time depending upon the type of object the appropriate method is called. Inheritance: is a feature of OOPL that represents the "is a" relationship between different objects(classes). Say in real life a manager is a employee. So in OOPL manger class is inherited from the employee class. Encapsulation: is a feature of OOPL that is used to hide the information. Q.What are the advantages of OOPL? Ans: Object oriented programming languages directly represent the real life objects. The features of OOPL as inhreitance, polymorphism, encapsulation makes it powerful. Q.How many methods do u implement if implement the Serializable Interface? Ans: The Serializable interface is just a "marker" interface, with no methods of its own to implement. Q.Are there any other 'marker' interfaces? Ans: java.rmi.Remote java.util.EventListener Q.What is the difference between instanceof and isInstance? Ans: 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 nonnull and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise. Q.why do you create interfaces, and when MUST you use one? Ans: You would create interfaces when you have two or more functionalities talking to each other. Doing it this way help you in creating a protocol between the parties involved. Q.What's the difference between the == operator and the equals() method? What test does Object.equals() use, and why? Ans: The == operator would be used, in an object sense, to see if the two objects were actually the same object. This operator looks at the actually memory address to see if it actually the same object. The equals() method is used to compare the values of the object respectively. This is used in a higher level to see if the object values are equal. Of course the the equals() method would be overloaded in a meaningful way for whatever object that you were working with. Q.Discuss the differences between creating a new class, extending a class and implementing an interface; and when each would be appropriate. Ans:

  • Creating a new class is simply creating a class with no extensions and no implementations. The signature is as follows

public class MyClass() {

  • Extending a class is when you want to use the functionality of another class or classes. The extended class inherits all of the functionality of the previous class. An example

of this when you create your own applet class and extend from java.applet.Applet. This gives you all of the functionality of the java.applet.Applet class. The signature would look like this public class MyClass extends MyBaseClass { }

  • Implementing an interface simply forces you to use the methods of the interface implemented. This gives you two advantages. This forces you to follow a standard(forces you to use certain methods) and in doing so gives you a channel for polymorphism. This isn’t the only way you can do polymorphism but this is one of the ways.

public class Fish implements Animal { } Q.Name four methods every Java class will have. Ans: public String toString(); public Object clone(); public boolean equals(); public int hashCode(); Q.What does the "abstract" keyword mean in front of a method? A class? Ans: Abstract keyword declares either a method or a class. If a method has a 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. Q.Does Java have destructors? Ans: No garbage collector does the job working in the background Q.Are constructors inherited? Can a subclass call the parent's class constructor? When? Ans: You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor of one of it's superclasses. One of the main reasons is because you probably don't want to overide the superclasses constructor, which would be possible if they were inherited. By giving the developer the ability to override a superclasses constructor you would erode the encapsulation abilities of the language. QDoes Java have "goto"? Ans: No Q.What does the "final" keyword mean in front of a variable? A method? A class? Ans: FINAL for a variable : value is constant FINAL for a method : cannot be overridden FINAL for a class : cannot be derived Core Java Interview Questions and Answers Q.what is a transient variable? Ans: A transient variable is a variable that may not be serialized. Q.which containers use a border Layout as their default layout? Ans: The window, Frame and Dialog classes use a border layout as their default layout. Q.Why do threads block on I/O? Ans: Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed Q. How are Observer and Observable used? Ans: 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. Q.What is synchronization and why is it important? Ans: 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. Q.Can a lock be acquired on a class? Ans: Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object. Q.What's new with the stop(), suspend() and resume() methods in JDK 1.2?  Ans: The stop(), suspend() and resume() methods have been deprecated in JDK 1.2. Q.Is null a keyword? Ans: The null value is not a keyword. Q.What is the preferred size of a component? Ans: The preferred size of a component is the minimum component size that will allow the component to display normally. Q.What method is used to specify a container's layout? Ans: The setLayout() method is used to specify a container's layout. Q.Which containers use a FlowLayout as their default layout? Ans: The Panel and Applet classes use the FlowLayout as their default layout. Q.What state does a thread enter when it terminates its processing? Ans: When a thread terminates its processing, it enters the dead state. Q.What is the Collections API? Ans: The Collections API is a set of classes and interfaces that support operations on collections of objects. Q.Which characters may be used as the second character of an identifier, but not as the first character of an identifier? Ans: 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. Q.What is the List interface? Ans: The List interface provides support for ordered collections of objects. Q.How does Java handle integer overflows and underflows? Ans: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation. Q.What is the Vector class? Ans: The Vector class provides the capability to implement a growable array of objects Q.What modifiers may be used with an inner class that is a member of an outer class? Ans: A (non-local) inner class may be declared as public, protected, private, static, final, or abstract. Q.What is an Iterator interface? Ans: The Iterator interface is used to step through the elements of a Collection. Q.What is the difference between the >> and >>> operators? Ans: The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out. Q.Which method of the Component class is used to set the position and size of a component? Ans: setBounds() Q.How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?  Ans: 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. Q.What is the difference between yielding and sleeping? Ans: 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. Q.Which java.util classes and interfaces support event handling? Ans: The EventObject class and the EventListener interface support event processing. Q.Is sizeof a keyword? Ans:The sizeof operator is not a keyword Q.What are wrapped classes? Ans: Wrapped classes are classes that allow primitive types to be accessed as objects. Q.Does garbage collection guarantee that a program will not run out of memory? Ans: 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 Q.What restrictions are placed on the location of a package statement within a source code file? Ans: A package statement must appear as the first line in a source code file (excluding blank lines and comments). Q.Can an object's finalize() method be invoked while it is reachable? Ans: 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. Q.What is the immediate superclass of the Applet class? Ans: Panel Q.What is the difference between preemptive scheduling and time slicing? Ans: 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. Q.Name three Component subclasses that support painting. Ans: The Canvas, Frame, Panel, and Applet classes support painting. Q.What value does readLine() return when it has reached the end of a file? Ans: The readLine() method returns null when it has reached the end of a file. Q.What is the immediate superclass of the Dialog class? Ans: Window Q.What is clipping? Ans: Clipping is the process of confining paint operations to a limited area or shape. Q.What is a native method? Ans: A native method is a method that is implemented in a language other than Java. Q.Can a for statement loop indefinitely? Ans: Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ; Q.What are order of precedence and associativity, and how are they used? Ans: Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left Q.When a thread blocks on I/O, what state does it enter? Ans: A thread enters the waiting state when it blocks on I/O. Q.To what value is a variable of the String type automatically initialized? Ans: The default value of an String type is null. Q.What is the catch or declare rule for method declarations? Ans: 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. Q.What is the difference between a MenuItem and a CheckboxMenuItem? Ans: The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked. Q.What is a task's priority and how is it used in scheduling? Ans: 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. Q.What class is the top of the AWT event hierarchy? Ans: The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy. Q.When a thread is created and started, what is its initial state Ans: A thread is in the ready state after it has been created and started. Q.Can an anonymous class be declared as implementing an interface and extending a class? Ans: An anonymous class may implement an interface or extend a superclass, but may not be declared to do both. Q.What is the range of the short type? Ans: The range of the short type is -(2^15) to 2^15 - 1. Q.What is the range of the char type? Ans: The range of the char type is 0 to 2^16 - 1. Q.In which package are most of the AWT events that support the event-delegation model defined? Ans: Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package. Q.What is the immediate superclass of Menu? Ans: MenuItem Q.What is the purpose of finalization Ans: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. Q.Which class is the immediate superclass of the MenuComponent class. Ans: Object Q.What invokes a thread's run() method? Ans: After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed. Q.What is the difference between the Boolean & operator and the && operator? Ans: 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. Q.Name three subclasses of the Component class. Ans: Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent Q.What is the GregorianCalendar class? Ans: The GregorianCalendar provides support for traditional Western calendars. Q.Which Container method is used to cause a container to be laid out and redisplayed? Ans: validate() Q.What is the purpose of the Runtime class? Ans: The purpose of the Runtime class is to provide access to the Java runtime system. Q.How many times may an object's finalize() method be invoked by the garbage collector? Ans: An object's finalize() method may only be invoked once by the garbage collector. Q.What is the purpose of the finally clause of a try-catch-finally statement? Ans: The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. Q.What is the argument type of a program's main() method? Ans: A program's main() method takes an argument of the String type. Q.Which Java operator is right associative? Ans: The = operator is right associative. Q.What is the Locale class? Ans: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. Q.Can a double value be cast to a byte? Ans: Yes, a double value can be cast to a byte. Q.What is the difference between a break statement and a continue statement? Ans: 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. Q.What must a class do to implement an interface? Ans: It must provide all of the methods in the interface and identify the interface in its implements clause. Q.What method is invoked to cause an object to begin executing as a separate thread? Ans: The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread. Q.Name two subclasses of the TextComponent class. Ans: TextField and TextArea Q.What is the advantage of the event-delegation model over the earlier event-inheritance model? Ans: 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. Q.Which containers may have a MenuBar? Ans: Frame Q.How are commas used in the initialization and iteration parts of a for statement? Ans: Commas are used to separate multiple statements within the initialization and iteration parts of a for statement. Q.What is the purpose of the wait(), notify(), and notifyAll() methods? Ans: The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods. Q.What is an abstract method? Ans: An abstract method is a method whose implementation is deferred to a subclass. Q.How are Java source code files named Ans: A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension. Q.What is the relationship between the Canvas class and the Graphics class? Ans: A Canvas object provides access to a Graphics object via its paint() method. Q.What are the high-level thread states? Ans: The high-level thread states are ready, running, waiting, and dead. Q.What value does read() return when it has reached the end of a file? Ans: The read() method returns -1 when it has reached the end of a file. Q.Can a Byte object be cast to a double value? Ans: No, an object cannot be cast to a primitive value. Q.What is the difference between a static and a non-static inner class? Ans: 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. Q.What is the difference between the String and StringBuffer classes? Ans: String objects are constants. StringBuffer objects are not. Q.If a variable is declared as private, where may the variable be accessed? Ans: A private variable may only be accessed within the class in which it is declared. Q.What is an object's lock and which object's have locks? Ans: 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. Q.What is the Dictionary class? Ans: The Dictionary class provides the capability to store key-value pairs. Q.How are the elements of a BorderLayout organized? Ans: The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container. Q.What is the % operator? Ans: It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand. Q.When can an object reference be cast to an interface reference? Ans: An object reference be cast to an interface reference when the object implements the referenced interface. Q.What is the difference between a Window and a Frame? Ans: The Frame class extends Window to define a main application window that can have a menu bar. Q.Which class is extended by all other classes? Ans: The Object class is extended by all other classes. Q.Can an object be garbage collected while it is still reachable? Ans: A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.. Q.Is the ternary operator written x : y ? z or x ? y : z ? Ans: It is written x ? y : z. Q.What is the difference between the Font and FontMetrics classes? Ans: The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object. Q.How is rounding performed under integer division? Ans: The fractional part of the result is truncated. This is known as rounding toward zero. Q.What happens when a thread cannot acquire a lock on an object? Ans: 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. Q.What is the difference between the Reader/Writer class hierarchy and the InputStream/ OutputStream class hierarchy? Ans: The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented. Q.What classes of exceptions may be caught by a catch clause? Ans: A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Q.If a class is declared without any access modifiers, where may the class be accessed? Ans: 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. Q.What is the SimpleTimeZone class? Ans: The SimpleTimeZone class provides support for a Gregorian calendar. Q.What is the Map interface? Ans: The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values. Q.Does a class inherit the constructors of its superclass? Ans: A class does not inherit constructors from any of its superclasses. Q.For which statements does it make sense to use a label? Ans: The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement. Q.What is the purpose of the System class? Ans: The purpose of the System class is to provide access to system resources. Q.Which TextComponent method is used to set a TextComponent to the read-only state? Ans: setEditable() Q.How are the elements of a CardLayout organized? Ans: The elements of a CardLayout are stacked, one on top of the other, like a deck of cards. Q.Is &&= a valid Java operator? Ans: No, it is not. Q.Name the eight primitive Java types. Ans: The eight primitive types are byte, char, short, int, long, float, double, and boolean. Q.Which class should you use to obtain design information about an object? Ans: The Class class is used to obtain information about an object's design. Q.What is the relationship between clipping and repainting? Ans: When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting. Q.Is "abc" a primitive value? Ans: The String literal "abc" is not a primitive value. It is a String object. Q.What is the relationship between an event-listener interface and an event-adapter class? Ans:  An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface. Q.What restrictions are placed on the values of each case of a switch statement? Ans: During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value. Q.What modifiers may be used with an interface declaration? Ans: An interface may be declared as public or abstract. Q.Is a class a subclass of itself? Ans: A class is a subclass of itself. Q.What is the highest-level event class of the event-delegation model? Ans: The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy. Q.What event results from the clicking of a button? Ans: The ActionEvent event is generated as the result of the clicking of a button. Q.How can a GUI component handle its own events? Ans: A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener. Q.What is the difference between a while statement and a do statement? Ans: 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. Q.How are the elements of a GridBagLayout organized? Ans: 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. Q.What advantage do Java's layout managers provide over traditional windowing systems? Ans: 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 accomodate platform-specific differences among windowing systems. Q.What is the Collection interface? Ans: The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates. Q.What modifiers can be used with a local inner class? Ans: A local inner class may be final or abstract. Q.What is the difference between static and non-static variables? Ans: 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. Q.What is the difference between the paint() and repaint() methods? Ans: 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. Q.What is the purpose of the File class? Ans: The File class is used to create objects that provide access to the files and directories of a local file system. Q.Can an exception be rethrown? Ans: Yes, an exception can be rethrown. Q.Which Math method is used to calculate the absolute value of a number? Ans: The abs() method is used to calculate absolute values. Q.How does multithreading take place on a computer with a single CPU? Ans: 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. Q.When does the compiler supply a default constructor for a class? Ans: The compiler supplies a default constructor for a class if no other constructors are provided. Q.When is the finally clause of a try-catch-finally statement executed? Ans: The finally clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the finally clause. Q.Which class is the immediate superclass of the Container class? Ans: Component Q.If a method is declared as protected, where may the method be accessed? Ans: 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. Q.How can the Checkbox class be used to create a radio button? Ans: By associating Checkbox objects with a CheckboxGroup. Q.Which non-Unicode letter characters may be used as the first character of an identifier? Ans: The non-Unicode letter characters $ and _ may appear as the first character of an identifier Q.What restrictions are placed on method overloading? Ans:Two methods may not have the same name and argument list but different return types. Q.What happens when you invoke a thread's interrupt method while it is sleeping or waiting? Ans: When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown. Q.What is casting? Ans: 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. Q.What is the return type of a program's main() method? Ans: A program's main() method has a void return type. Q.Name four Container classes. Ans: Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane Q.What is the difference between a Choice and a List? Ans: A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items. Q.What class of exceptions are generated by the Java run-time system? Ans: The Java runtime system generates RuntimeException and Error exceptions. Q.What class allows you to read objects directly from a stream? Ans: The ObjectInputStream class supports the reading of objects from input streams. Q.What is the difference between a field variable and a local variable? Ans: 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. Q.Under what conditions is an object's finalize() method invoked by the garbage collector? Ans: The garbage collector invokes an object's finalize() method when it detects that the object has become unreachable. Q.How are this() and super() used with constructors? Ans: this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. Q.What is the relationship between a method's throws clause and the exceptions that can be thrown during the method's execution? Ans: A method's throws clause must declare any checked exceptions that are not caught within the body of the method. Q.What is the difference between the JDK 1.02 event model and the event-delegation model introduced with JDK 1.1? Ans: The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component's container. The container then either handles the event or it is bubbled up to its container and so on, until the highest-level container has been tried. In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events. Q.How is it possible for two String objects with identical values not to be equal under the == operator? Ans: 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. Q.Why are the methods of the Math class static? Ans: So they can be invoked as if they are a mathematical code library. Q.What Checkbox method allows you to tell if a Checkbox is checked? Ans: getState() Q.What state is a thread in when it is executing? Ans: An executing thread is in the running state. Q.What are the legal operands of the instanceof operator? Ans: The left operand is an object reference or null value and the right operand is a class, interface, or array type. Q.How are the elements of a GridLayout organized? Ans: The elements of a GridBad layout are of equal size and are laid out using the squares of a grid. Q.What an I/O filter? Ans: 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.  Q.If an object is garbage collected, can it become reachable again? Ans: Once an object is garbage collected, it ceases to exist.  It can no longer become reachable again. Q.What is the Set interface? Ans: The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements. Q.What classes of exceptions may be thrown by a throw statement? Ans: A throw statement may throw any expression that may be assigned to the Throwable type. Q.What are E and PI? Ans: E is the base of the natural logarithm and PI is mathematical value pi. Q.Are true and false keywords? Ans: The values true and false are not keywords. Q.What is a void return type? Ans: A void return type indicates that a method does not return a value. Q.What is the purpose of the enableEvents() method? Ans: 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. Q.What is the difference between the File and RandomAccessFile classes? Ans: 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. Q.What happens when you add a double value to a String? Ans: The result is a String object. Q.What is your platform's default character encoding? Ans: 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..

 Java Interview Questions                     Java Interview Questions and Answers Q.Which package is always imported by default? Ans: The java.lang package is always imported by default. Q.What interface must an object implement before it can be written to a stream as an object? Ans: An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. Q.How are this and super used? Ans: this is used to refer to the current object instance. super is used to refer to the variables and methods of the superclass of the current object instance. Q.What is the purpose of garbage collection? Ans: 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. Q.What is a compilation unit? Ans: A compilation unit is a Java source code file. Q.What interface is extended by AWT event listeners? Ans: All AWT event listeners extend the java.util.EventListener interface. Q.What restrictions are placed on method overriding? Ans: 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. Q.How can a dead thread be restarted? Ans: A dead thread cannot be restarted. Q.What happens if an exception is not caught? Ans: An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown. Q.What is a layout manager? Ans: A layout manager is an object that is used to organize components in a container. Q.Which arithmetic operations can result in the throwing of an ArithmeticException? Ans: Integer / and % can result in the throwing of an ArithmeticException. Q.What are three ways in which a thread can enter the waiting state? Ans: 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. Q.Can an abstract class be final? Ans: An abstract class may not be declared as final. Q.What is the ResourceBundle class? Ans: 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. Q.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? Ans: The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination. Q.What is numeric promotion? Ans: 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. Q.What is the difference between a Scrollbar and a ScrollPane? Ans: 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. Q.What is the difference between a public and a non-public class? Ans: A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package. Q.To what value is a variable of the boolean type automatically initialized? Ans: The default value of the boolean type is false. Q.Can try statements be nested? Ans: Try statements may be tested. Q.What is the difference between the prefix and postfix forms of the ++ operator? Ans: 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. Q.What is the purpose of a statement block? Ans: A statement block is used to organize a sequence of statements as a single statement group. Q.What is a Java package and how is it used? Ans: 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. Q.What modifiers may be used with a top-level class? Ans: A top-level class may be public, abstract, or final. Q.What are the Object and Class classes used for? Ans: 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. Q.How does a try statement determine which catch clause should be used to handle an exception? Ans: 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. Q.Can an unreachable object become reachable again? Ans: An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects. Q.When is an object subject to garbage collection? Ans: An object is subject to garbage collection when it becomes unreachable to the program in which it is used. Q.What method must be implemented by all threads? Ans: All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface. Q.What methods are used to get and set the text label displayed by a Button object? Ans:  getLabel() and setLabel() Q.Which Component subclass is used for drawing and painting? Ans: Canvas Q.What are synchronized methods and synchronized statements? Ans: 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. Q.What are the two basic ways in which classes that can be run as threads may be defined? Ans: A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface. Q.What are the problems faced by Java programmers who don't use layout managers? Ans: 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. Q.What is the difference between an if statement and a switch statement? Ans: 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. Q.What is the List interface? Ans: The List interface provides support for ordered collections of objects.

Servlets and JSP

Q.What are Servlets? Ans: Servlets are small program which execute on the web server. They run under web server environment exploiting the functionalities of the web server. Q.What are advantages of servlets over CGI? Ans: In CGI for every request there is a new process started which is quiet an overhead. In servlets JVM stays running and handles each request using a light weight thread. In CGI if there are 1000 request then 1000 CGI program is loaded in memory while in servlets there are 1000 thread and only one copy of the servlet class. Q.Can you explain Servlet life cycle? There are three methods which are very important in servlet life cycle i.e. "init”, "service" and "destroy". Server invokes "init ()" method when servlet is first loaded in to the web server memory. Servlet reads HTTP data provided in HTTP request in the "service ()" method. Once initialized servlet remains in memory to process subsequent request. So for every HTTP request "service ()" method of the servlet is called. Finally when server unloads the "servlet ()" from the memory it calls the "destroy" method which can be used to clean up any resource the servlet is consuming. Q.What are the two important API’s in for Servlets? Ans: Two important packages are required to build servlet "javax.servlet" and "javax.servlet.http". They form the core of Servlet API. Servlets are not part of core Java but are standard extensions provided by Tomcat. Q.Can you explain in detail “javax.servlet” package? Ans: javax.servlet package has interfaces and classes which define a framework in which servlets can operate. Let’s first make a walk through of all the interfaces and methods and its description. Interfaces in javax.servlet Servlet Interface This interface has the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet. Following are the method in Servlet interface :- void destroy( ):- Executed when servlet is unloaded from the web server memory. ServletConfig getServletConfig() :- Returns back a ServletConfig object that contains initialization data. String getServletInfo( ):- Returns a string describing the servlet. init method :- Called for first time when the servlet is initialized by the web server. void service() method :- Called to process a request from a client. ServletConfig Interface This interface is implemented by the servlet container. Servlet can access any configuration data when its loaded. The methods declared by this interface are summarized here: Following are the methods in ServletConfig interface:- ServletContext getServletContext():- Gives the servlet context. String getInitParameter(String param):- Returns the value of the initialization parameter named param. Enumeration getInitParameterNames() :- Returns an enumeration of all initialization parameter names. String getServletName( ) :- Returns the name of the invoking servlet. Q.What’s the use of ServletContext? Ans: ServletContext Interface It gives information about the environment. It represents a Servlet's view of the Web Application.Using this interface servlet can access raw input streams to Web Application resources, virtual directory translation, a common mechanism for logging information, and an application scope for binding objects. Following are the methods defined in ServletContext Interface Object getAttribute(String attr) :- Returns the value of the server attribute named attr. String getMimeType(String file) :- Gives MIME type for a file. String getRealPath(String vpath) :- Gives the actual physical path for a virtual path. String getServerInfo( ) :- You can get the server information using this function. void log(String s) :- Used to write to server log. void log(String s, Throwable e) :- Writes s and the stack trace for e to the servlet log. void setAttribute(String attr, Object val) :- Sets the attribute specified by attr to the value passed in val. ServletRequest Interface The ServletRequest interface is implemented by the servlet container. It gives data regarding client request. Following are the methods defined in ServletRequest Interface Object getAttribute(String attr) :- Returns the value of the attribute named attr. String getCharacterEncoding( ) :- Returns the character encoding of the request. int getContentLength( ) :- Gives the size of the request. If no size is there then it returns -1. String getContentType( ) :- Returns the type of the request. A null value is returned if the type cannot be determined. ServletInputStream getInputStream( ) :- Returns a ServletInputStream that can be used to read binary data from the request. String getParameter(String pname) :- Returns the value of the parameter named pname. Enumeration getParameterNames( ) :- Returns an enumeration of the parameter names for this request. String getParameterValues(String name) :- Returns an array containing values associated with the parameter specified by name. String getProtocol( ) :- Gives back protocol description. BufferedReader getReader( ) :- Returns a buffered reader that can be used to read text from the request. String getRemoteAddr() :-Returns client IP address. String getRemoteHost() :- Returns client host name. String getScheme( ) :- Return what’s the transmission protocol HTTP , FTP etc. String getServerName() :- Returns the name of the server. int getServerPort() :- Returns the port number. ServletResponse Interface The ServletResponse interface is implemented by the servlet containerUsed to give response back to the client. Following are the methods defined in ServletResponse Interface String getCharacterEncoding() :- Returns back character encoding. ServletOutputStream getOutputStream() :- Returns a ServletOutputStream that can be used to write binary data to the response. PrintWriter getWriter() :- Returns a PrintWriter that can be used to write character data to the response. void setContentLength(int size) :- Sets the content length for the response to size. void setContentType(String type) :- Sets the content type for the response to type. GenericServlet Class The GenericServlet class provides implementations of the basic life cycle methods for a servlet. GenericServlet implements the Servlet and ServletConfig interfaces. void log(String s) void log(String s, Throwable e) Here, s is the string to be appended to the log, and e is an exception that occurred. Now let’s revise through different classes. ServletInputStream Class This class extends InputStream. It is implemented by the servlet container and provides an input stream that a servlet developer can use to read the data from a client request. It defines the default constructor. In addition, a method is provided to read bytes from the stream. int readLine(byte buffer, int offset, int size) :- Here, buffer is the array into which size bytes are placed starting at offset. The method returns the actual number of bytes read or –1 if an end-of-stream condition is encountered. ServletOutputStream Class The ServletOutputStream class extends OutputStream. It is implemented by the servlet container and provides an output stream that a servlet developer can use to write data to a client response. A default constructor is defined. It also defines the “print()” and “println()” methods, which output data to the stream. Servlet Exception Classes javax.servlet defines two exceptions. The first is ServletException, which indicates that a servlet problem has occurred. The second is unavailableException, which extends ServletException. It indicates that a servlet is unavailable. Q.What's the difference between GenericServlet and HttpServlet? Ans: HttpServlet class extends GenericServlet class which is an abstract class to provide HTTP protocol-specific functionalities. Most of the java application developers extend HttpServlet class as it provides more HTTP protocol-specific functionalities. You can see in HttpServlet class doGet (), doPOst () methods which are more targeted towards HTTP protocol specific functionalities. For instance we can inherit from GenericServlet class to make something like MobileServlet. So GenericServlet class should be used when we want to write protocol specific implementation which is not available. But when we know we are making an internet application where HTTP is the major protocol its better to use HttpServlet. Q.Can you explain in detail javax.servlet.http package? Ans: The javax.servlet.http package inherits from “javax.servlet” package and supplies HTTP protocol specific functionalities for JAVA developers. If you are aiming at developing HTTP application you will find “javax.servlet.HTTP” more comfortable than “javax.servlet”. So let’s revisit through the interfaces and methods HttpServletRequest Interface Below are the lists of methods in HttpServletRequest Interface:- String getAuthType( ):- Returns the type of authentication. Cookie getCookies( ) :- Returns the collection of cookies for the request. long getDateHeader(String field) :- Returns the value of the date header field named field. String getHeader(String field) :- Returns the value of the header field named field. Enumeration getHeaderNames( ) :- Returns an enumeration of the header names. int getIntHeader(String field) :- Returns the int equivalent of the header field named field. String getMethod( ) :- What type of method does this request have POST , GET etc. String getPathInfo( ) :- Returns any path information that is located after the servlet path and before a query string of the URL. String getPathTranslated( ) :- Returns any path information that is located after the servlet path and before a query string of the URL after translating it to a real path. String getQueryString( ) :- Returns any query string in the URL. String getRemoteUser( ) :- Returns the name of the user who issued this request. String getRequestedSessionId( ) :- Returns the ID of the session. String getRequestURI( ) :- Returns the URI. StringBuffer getRequestURL( ) :- Returns the URL. String getServletPath( ) :- Returns that part of the URL that identifies the servlet. HttpSession getSession( ) :- Returns the session for this request. If a session does not exist, one is created and then returned. HttpSession getSession(boolean new) :- If new is true and no session exists, creates and returns a session for this request. Otherwise, returns the existing session for this request. This section is explained in more detail in further questions. boolean isRequestedSessionIdFromCookie( ) :- Returns true if the cookie has the session id. boolean isRequestedSessionIdFromURL( ) :- Gives true if the URL has session id. boolean isRequestedSessionIdValid( ) :- Return true if the session is valid in the current context. HttpServletResponse Interface The HttpServletResponse interface is implemented by the servlet container. It enables a servlet to formulate an HTTP response to a client. Several constants are defined. These correspond to the different status codes that can be assigned to an HTTP response. Below are the methods and functions for the interface void addCookie(Cookie cookie) :-Adds cookie to the HTTP response. String encodeURL(String url) :- Determines if the session ID must be encoded in the URL identified as url. If so, returns the modified version of URL. Otherwise, returns URL. All URLs generated by a servlet should be processed by this method. String encodeRedirectURL(String url) :- Determines if the session ID must be encoded in the URL identified as url. If so, returns the modified version of URL. Otherwise, returns URL. All URLs passed to sendRedirect( ) should be processed by this method. void sendError(int c) :- Sends the error code c to the client. void sendError(int c, String s) :- Sends the error code c and message s to the client. void sendRedirect(String url) :- Redirects the client to url. void setDateHeader(String field, long msec) :- Adds field to the header with date value equal to msec (milliseconds since midnight, January 1, 1970, GMT). void setHeader(String field, String value) :- Adds field to the header with value equal to value. void setIntHeader(String field, int value) :- Adds field to the header with value equal to value. void setStatus(int code) :- Sets the status code for this response to code. HttpSession Interface HTTP protocol is a stateless protocol and this interface enables to maintain sessions between requests. Object getAttribute(String attr) :- Returns the value associated with the name passed in attr. Returns null if attr is not found. Enumeration getAttributeNames( ) :- Returns an enumeration of the attribute names associated with the session. long getCreationTime( ) :- Returns the time (in milliseconds since midnight, January 1, 1970, GMT) when this session was created. String getId( ) :- Returns the session ID. long getLastAccessedTime( ) :- Returns the time (in milliseconds since midnight, January 1, 1970, GMT) when the client last made a request for this session. void invalidate() :- Invalidates this session and removes it from the context. boolean isNew( ) :- Returns true if the server created the session and it has not yet been accessed by the client. void removeAttribute(String attr) :- Removes the attribute specified by attr from the session. void setAttribute(String attr, Object val) :- Associates the value passed in val with the attribute name passed in attr. HttpSessionBindingListener The HttpSessionBindingListener interface is implemented by objects that need to be notified when they are bound to or unbound from an HTTP session. The methods that are invoked when an object is bound or unbound are void valueBound(HttpSessionBindingEvent e) voidvalueUnbound(HttpSessionBindingEvent e) Here, e is the event object that describes the binding. Cookie Class The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state information. Cookies are valuable for tracking user activities. For example, assume that a user visits an online store. A cookie can save the user's name, address, and other information. The user does not need to enter this data each time he or she visits the store. A servlet can write a cookie to a user's machine via the addCookie( ) method of the HttpServletResponse interface. The data for that cookie is then included in the header of the HTTP response that is sent to the browser. The names and values of cookies are stored on the user's machine. Some of the information that is saved for each cookie includes name of the cookie, value of the cookie, expiration date of the cookie and domain/path of the cookie. The expiration date determines when this cookie is deleted from the user's machine. If an expiration date is not explicitly assigned to a cookie, it is deleted when the current browser session ends. Otherwise, the cookie is saved in a file on the user's machine. The domain and path of the cookie determine when it is included in the header of an HTTP request. If the user enters a URL whose domain and path match these values, the cookie is then supplied to the Web server. Otherwise, it is not. There is one constructor for Cookie. It has the signature shown here: Cookie(String name, String value) :- Here, the name and value of the cookie are supplied as arguments to the constructor. The methods of the Cookie class are Object clone( ) :- Returns a copy of this object. String getComment( ) :- Returns the comment. String getDomain( ) :- Returns the domain. int getMaxAge( ) :- Returns the maximum age (in seconds). String getName( ) :- Returns the name. String getPath( ) :- Returns the path. boolean getSecure( ) :- Returns true if the cookie is secure. Otherwise, returns false. String getValue( ) :- Returns the value. int getVersion( ) :- Returns the version. void setComment(String c) :- Sets the comment to c. void setDomain(String d) :- Sets the domain to d. void setMaxAge(int secs) :- Sets the maximum age of the cookie to secs. This is the number of seconds after which the cookie is deleted. void setPath(String p) :- Sets the path to p. void setSecure(boolean secure) :- Sets the security flag to secure. void setValue(String v) :- Sets the value to v. void setVersion(int v) :- Sets the version to v. HttpServlet Class The HttpServlet class extends GenericServlet. It is commonly used when developing servlets that receive and process HTTP requests. void doDelete(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP DELETE. void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP GET. void doOptions(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP OPTIONS. void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP POST. void doPut(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP PUT. void doTrace(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP TRACE. long getLastModified(HttpServletRequest req) :- Returns the time (in milliseconds since midnight, January 1, 1970, GMT) when the requested resource was last modified. void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Called by the server when an HTTP request arrives for this servlet. The arguments provide access to the HTTP request and response, respectively. HttpSessionEvent Class HttpSessionEvent encapsulates session events. It extends EventObject and is generated when a change occurs to the session. HttpSession getSession( ) It returns the session in which the event occurred. The HttpSessionBindingEvent Class The HttpSessionBindingEvent class extends HttpSessionEvent. It is generated when a listener is bound to or unbound from a value in an HttpSession object. It is also generated when an attribute is bound or unbound. Here are its constructors: HttpSessionBindingEvent(HttpSession session, String name) HttpSessionBindingEvent(HttpSession session, String name, Object val) Here, session is the source of the event, and name is the name associated with the object that is being bound or unbound. If an attribute is being bound or unbound, its value is passed in Val. String getName( ) :- The getName( ) method obtains the name that is being bound or unbound. Its constructor is shown here: HttpSession getSession( ) :- The getSession( ) method, shown next, obtains the session to which the listener is being bound or unbound: Object getValue( ) :- The getValue( ) method obtains the value of the attribute that is being bound or unbound. It is shown here: Q.What’s the architecture of a Servlet package? Ans: In the previous questions we saw all the servlet packages. But the basic architecture of the servlet packages is as shown below. At the top of all is the main servlet interface which is implemented by the generic servlet. But generic servlet does not provide implementation specific to any protocol. HTTP servlet further inherits from the generic servlet and provides HTTP implementation like “Get” and “Post”. Finally comes our custom servlet which inherits from HTTP Servlet. Q.Why is HTTP protocol called as a stateless protocol? Ans: A protocol is stateless if it can remember difference between one client request and the other. HTTP is a stateless protocol because each request is executed independently without any knowledge of the requests that came before it. Above is a pictorial presentation of how a stateless protocol operates. User first sends “request1” and server responds with “response1”. When the same user comes back with “request2” server treats this as new user and has no idea that it’s the same user who has come with the request. In short every request is a new request for the HTTP protocol so it’s called as a stateless protocol. Q.What are the different ways we can maintain state between requests? Ans: Following are the different ways of maintaining state’s between stateless requests:- √ URL rewriting √ Cookies √ Hidden fields √ Sessions Q.What is URL rewriting? Ans: It’s based on the concept of attaching a unique ID (which is generated by the server) in the URL of response from the server. So the server attaches this unique ID in each URL. When the client sends a requests it sends back this ID with the request also which helps the server to identify the client uniquely. Below is a snippet which is extracted from the code which is provided in the CD. In this sample we have generated a unique ID using the random class of java. This unique ID is then sent in the query string (see step 3 of the above snippet) back to the client. When the client comes back to the server the server first gets the token value from the query string and thus identifying the client uniquely. Q.What’s the difference between getSession(true) and getSession(false) ? Ans: Session's can be considered as a series of related interactions between client and the server that take place over a period of time. Because HTTP is a stateless protocol these series of interactions are difficult to track. That’s where we can use HttpSession object to save in between of these interactions so that server can co-relate between interactions between clients. Above is the code snippet which displays session data. Step1 returns an HttpSession object from the request object. “true” parameter in the “getsession” function ensures that we get a session object if there is no current session object in request which ensures that we never get a null session object. In Step 2 we are using the “getattribute” function to return the session value. In step 3 we are setting the session value with “Name” key. Q.Which are the different ways you can communicate between servlets? Ans: Below are the different ways of communicating between servlets:-

√Using RequestDispatcher object. √Sharing resource using “ServletContext ()” object. √Servlet chaining. Q.What are filters in JAVA? Ans: Filters are nothing but simple java classes which can manipulate request before it reaches the resource on the web server. Resource can be a HTML file, servlet class, JSP etc. It can also intercept responses sent back to client and thus can manipulate the response before they reach the client browser. Q.what’s the difference between Authentication and authorization? Ans: Authentication is the process the application identifies that you are who. For example when a user logs into an application with a username and password, application checks that the entered credentials against its user data store and responds with success or failure. Authorization, on the other hand, is when the application checks to see if you're allowed to do something. For instance are you allowed to do delete or modify a resource. Q.Explain in brief the directory structure of a web application? Ans: Below is the directory structure of a web application:- webapp/ WEB-INF/web.xml WEB-INF/classes WEB-INF/lib √The webapp directory contains the JSP files, images, and HTML files. The webapp directory can also contain subdirectories such as images or html or can be organized by function, such as public or private. √The WEB-INF/web.xml file is called the deployment descriptor for the Web application. This file contains configuration information for the Web application, including the mappings of URLs to servlets and filters. The web.xml file also contains configuration information for security, MIME type mapping, error pages, and locale settings √The WEB-INF/classes directory contains the class files for the servlets, JSP files, tag libraries, and any other utility classes that are used in the Web application. √The WEB-INF/lib directory contains JAR files for libraries that are used by the Web application. These are generally third-party libraries or classes for any tag libraries used by the Web application. Q.Can you explain JSP page life cycle? Ans: When first time a JSP page is request necessary servlet code is generated and loaded in the servlet container. Now until the JSP page is not changed the compiled servlet code serves any request which comes from the browser. When you again change the JSP page the JSP engine again compiles a servlet code for the same. √JSP page is first initialized by jspInit() method. This initializes the JSP in much the same way as servlets are initialized, when the first request is intercepted and just after translation. √Every time a request comes to the JSP, the container generated _jspService() method is invoked, the request is processed, and response generated. √When the JSP is destroyed by the server, the jspDestroy() method is called and this can be used for clean up purposes. Q.What is EL? Ans: EL stands for expression language. An expression language makes it possible to easily access application data.In the below expression amountofwine variable value will be rendered. There are ${amountofwine} litres of wine in the bottle. Q.how does EL search for an attribute? Ans: EL parser searches the attribute in following order: √Page √Request √Session (if it exists) √Application If no match is found for then it displays empty string. Q.What are the implicit EL objects in JSP? Ans: Following are the implicit EL objects:- PageContext: The context for the JSP page. Provides access to various objects for instance:- servletContext: The context for the JSP page's servlet and any web components contained in the same application. session: The session object for the client. request: The request triggering the execution of the JSP page. response: The response returned by the JSP page. See Constructing Responses. In addition, several implicit objects are available that allow easy access to the following objects: param: Maps a request parameter name to a single value paramValues: Maps a request parameter name to an array of values header: Maps a request header name to a single value headerValues: Maps a request header name to an array of values cookie: Maps a cookie name to a single cookie initParam: Maps a context initialization parameter name to a single value Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects. pageScope: Maps page-scoped variable names to their values requestScope: Maps request-scoped variable names to their values sessionScope: Maps session-scoped variable names to their values applicationScope: Maps application-scoped variable names to their values For instance the below snippet will indentify the browser used by the client. Browser: ${header} Q.How can we disable EL? Ans: You can disable using isELIgnored attribute of the page directive: <%@ page isELIgnored ="true|false" %> Q.Can you explain in short what the different types of JSTL tags are? Ans: Tags are classified in to four groups:- √Core tags √ Formatting tags √ XML tags √SQL tags Core tags for conditional flow and for iteration ....... for selective flow between mutually exclusive code and for working with scoped variables for rendering the value of variables and expressions for working with Java exceptions for creating and working with URLs Formatting tags Used to format and display text, the date, the time, and numbers. Below are some frequently used tags:- : To render numerical value with specific precision or format : To render date and time values in a specific format (and according to international locale-specific conventions) : To display an internationalized message (for example, a message in a different language using a different character set) XML tags XML tags are meant to process XML data. It supports data-parsing, transforming XML, plus data and flow control based on XPath expressions. These tags are used only when you need to work directly, within the JSP, with XML data. SQL tags They are designed to work directly with SQL tags. But most of the time you will see they are used for prototyping and not for final product. Just before we move ahead with some other questions. Let’s how do we install JSTL so that everything works. Below are three installation steps:- √Unzip "jakarta-taglibs-standard-1.1.2.zip" and you will see two files jstl.jar and standard.jar in lib directory. √Copy both jstl.jar and standard.jar to "\webapps\ROOT\WEB-INF\lib" directory in tomcat. √Copy all tld files from the unzipped location to \webapps\ROOT\WEB-INF" directory. √Modify the web.xml file to include all TLD files. Below is snippet of some tld's included in web.xml file. http://java.sun.com/jstl/fmt /WEB-INF/fmt.tld http://java.sun.com/jstl/fmt-rt /WEB-INF/fmt-rt.tld http://java.sun.com/jstl/core /WEB-INF/c.tld http://java.sun.com/jstl/core-rt /WEB-INF/c-rt.tld http://java.sun.com/jstl/sql /WEB-INF/sql.tld http://java.sun.com/jstl/sql-rt /WEB-INF/sql-rt.tld http://java.sun.com/jstl/x /WEB-INF/x.tld http://java.sun.com/jstl/x-rt /WEB-INF/x-rt.tld Q.What are JSP directives? Ans: JSP directives do not produce any output. They are used to set global values like class declaration, content type etc. Directives have scope for entire JSP file. They start with <%@ and ends with %>. There are three main directives that can be used in JSP:- √page directive √ include directive √ taglib directive Q.what are Page directives? Ans: Page directive is used to define page attributes the JSP file. Below is a sample of the same:- <%@ page language="Java" import="java.rmi.*,java.util.*" session="true" buffer="12kb" autoFlush="true" errorPage="error.jsp" %> To summarize some of the important page attributes:- import :- Comma separated list of packages or classes, just like import statements in usual Java code. session :- Specifies whether this page can use HTTP session. If set "true" session (which refers to the javax.servlet.http.HttpSession) is available and can be used to access the current/new session for the page. If "false", the page does not participate in a session and the implicit session object is unavailable. buffer :- If a buffer size is specified (such as "50kb") then output is buffered with a buffer size not less than that value. isThreadSafe :- Defines the level of thread safety implemented in the page. If set "true" the JSP engine may send multiple client requests to the page at the same time. If "false" then the JSP engine queues up client requests sent to the page for processing, and processes them one request at a time, in the order they were received. This is the same as implementing the javax.servlet.SingleThreadModel interface in a servlet. errorPage: - Defines a URL to another JSP page, which is invoked if an unchecked runtime exception is thrown. The page implementation catches the instance of the Throwable object and passes it to the error page processing.  Q.what’s the difference between JavaBeans and taglib directives? Ans: JavaBeans and taglib fundamentals were introduced for reusability. But following are the major differences between them:- √Taglib are for generating presentation elements while JavaBeans are good for storing information and state. √Use custom tags to implement actions and JavaBeans to present information. Q.what are the different scopes an object can have in a JSP page? Ans: There are four scope which an object can have in a JSP page:- Page Scope Objects with page scope are accessible only within the page. Data only is valid for the current response. Once the response is sent back to the browser then data is no more valid. Even if request is passed from one page to other the data is lost. Request Scope Objects with request scope are accessible from pages processing the same request in which they were created. Once the container has processed the request data is invalid. Even if the request is forwarded to another page, the data is still available though not if a redirect is required. Session Scope Objects with session scope are accessible in same session. Session is the time users spend using the application, which ends when they close their browser or when they go to another Web site. So, for example, when users log in, their username could be stored in the session and displayed on every page they access. This data lasts until they leave the Web site or log out. Application Scope Application scope objects are basically global object and accessible to all JSP pages which lie in the same application. This creates a global object that's a vailable to all pages. Application scope variables are typically created and populated when an application starts and then used as read-only for the rest of the application. Q.what are different Authentication Options available in servlets? Ans: There are four ways of authentication:- √ HTTP basic authentication √ HTTP digest authentication √ HTTPS client authentication √ Form-based authentication Let’s try to understand how the above four ways work. HTTP basic authentication In HTTP basic authentication the server uses the username and password send by the client. The password is sent using simple base64 encoding but it’s not encrypted. HTTP digest authentication HTTP digest authentication is same as HTTP basic authentication but the biggest difference is password is encrypted and transmitted using SHA or MD5. HTTPS client authentication HTTPS client authentication is based on HTTP over SSL. It requires that the end client should possess a PKC (Public Key Certificate). This verifies the browsers identity. Form-based authentication In FORM-based the web container invokes a login page. The invoked login page is used to collect username and password. Q.What is the difference between Servletcontext and ServletConfig ? Ans: ServletConfig contains configuration data for the servlet in the form of name and value pairs.Using the ServletConfigwe get reference to the ServletContext object. ServletContext gives the servlet access to information about its runtime environment such as web server logging facilities, version info, URL details, web server attributes etc. Q.How do we prevent browser from caching output of my JSP pages? Ans: You can prevent pages from caching JSP pages output using the below code snippet. <%response.setHeader("Cache-Control","no-cache"); //HTTP 1.1 response.setHeader("Pragma","no-cache"); //HTTP 1.0 response.setDateHeader ("Expires", 0); //prevents caching at the proxy server %> Q.Can we explicitly destroy a servlet object? Ans: No we can not destroy a servlet explicitly its all done by the container. Even if you try calling the destroy method container does not respond to it. contact for more on Java Online Training