Sie sind auf Seite 1von 122

Java programming language The Java programming language is a high-level language that can be characterized by all of the following

buzzwords: Architecture Simple neutral Object Portable oriented High Distributed performance Robust Multithreaded Dynamic Secure Portable: Your applications are portable across multiple platforms. Write your applications once, and you never need to port themthey will run without modification on multiple operating systems and hardware architectures. Robust: Your applications are robust because the Java run-time system manages memory for you. Because Java has inbuilt garbage collector and type safety checks in code. The compiler restricts the type compatibility when converting data from one type o another. High Performance: Your interactive graphical applications have high performance because multiple concurrent threads of activity in your application are supported by the multithreading built into the Java language and runtime platform. Secure: Your end users can trust that your applications are secure, even though theyre downloading code from all over the Internet; the Java run-time system has built-in protection against viruses and tampering. Each of the preceding buzzwords is explained in The Java Language Environment , a white paper written by James Gosling and Henry McGilton. In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes the machine language of the Java Virtual Machine1 (Java VM). The java launcher tool then runs your application with an instance of the Java Virtual Machine.

An overview of the software development process. Because the Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris TM Operating System (Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java HotSpot virtual machine, perform additional steps at runtime to give your application a performance boost. This include various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code.

Through the Java VM, the same application is capable of running on multiple platforms. The Java Platform A platform is the hardware or software environment in which a program runs. We've already mentioned some of the most popular platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the operating system and underlying hardware. 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 The Java Application Programming Interface (API)

You've already been introduced to the Java Virtual Machine; it's the base for the Java platform and is ported onto various hardware-based platforms. The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. The next section, What Can Java Technology Do? highlights some of the functionality provided by the API.

The API and Java Virtual Machine insulate the program from the underlying hardware. As a platform-independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability.

Why Strings have been made immutable? JVM internally maintains the "String Pool". To achieve the memory efficiency, JVM will refer the String object from pool. It will not create the new String objects. So, whenever you create a new string literal, JVM will check in the pool whether it already exists or not. If already present in the pool, just give the reference to the same object or create the new object in the pool. There will be many references point to the same String objects, if someone changes the value, it will affect all the references. So, sun decided to make it immutable. It checks only for string literals. If you create a string with new operator it does not check it directly creates new object. String.intern() method lets you the objects created using new operator to be placed into string pool.

Primitive Data Types The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name, as you've already seen: int gear = 1; Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial value of "1". A variable's data type determines the values it may contain, plus the operations that may be performed on it. In addition to int, the Java programming language supports seven other primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are: byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation. short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters. int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead. long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int. float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should

never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform. double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency. boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined. char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";. String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such. You'll learn more about the String class in Simple Data Objects Default Values It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style. The following chart summarizes the default values for the above data types. Default Value (for Data Type fields) byte 0 short 0 int 0 long 0L float 0.0f double 0.0d

char '\u0000' String (or any null object) boolean false Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error. Literals You may have noticed that the new keyword isn't used when initializing a variable of a primitive type. Primitive types are special data types built into the language; they are not objects created from a class. A literal is the source code representation of a fixed value; literals are represented directly in your code without requiring computation. As shown below, it's possible to assign a literal to a variable of a primitive type: boolean result = true; char capitalC = 'C'; byte b = 100; short s = 10000; int i = 100000; double d = 23.45; float f = 23.45f; * If you assign 23.45 to a literal it takes it as a double value Class and Objects: Things an object knows about itself are called instance variables. They represent an objects state (the data), and can have unique values for each object of that type. Things an object does are methods. Methods operate on data. A class is not an object but its used to construct them. A class is a blueprint for an object. It tells the virtual machine how to make an object of that particular type. Each object made from that class can have its own values for the instance variables of that class. 1. Object-oriented programming lets you extend a program without having to touch previously tested, working code. 2. All Java code is defined in a class. 3. A class describes how to make an object of that class type. A class is like a blueprint.

4. An object can take care of itself; you dont have to know or care how the object does it. 5. An object knows things and does things. Things an object knows about itself are called instance variables. They represent the state of an object. Things an object does are called methods. They represent the behavior of an object. 6. A class can inherit instance variables and methods from a more abstract superclass. 7. At runtime, a Java program is nothing more than objects talking to other objects. 8. There is actually no such thing as an object variable. Theres only an object reference variable. 9. An object reference variable holds bits that represent a way to access an object. It doesnt hold the object itself, but it holds something like a pointer. Or an address. Except, in Java we dont really know what is inside a reference variable. We do know that whatever it is, it represents one and only one object. And the JVM knows how to use the reference to get to the object. Garbage collector: Some object-oriented languages require that you keep track of all the objects you create and that you explicitly destroy them when they are no longer needed. Managing memory explicitly is tedious and errorprone. The Java platform allows you to create as many objects as you want (limited, of course, by what your system can handle), and you don't have to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection. An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null. Remember that a program can have multiple references to the same object; all references to an object must be dropped before the object is eligible for garbage collection. The Java runtime environment has a garbage collector that periodically frees the memory used by objects that are no longer referenced. The garbage collector does its job automatically when it determines that the time is right. Java takes out the Garbage: Each time an object is created in Java, it goes into an area of memory known as The Heap. All objectsno matter when, where, or how theyre created live on the heap. But its no t just any old memory heap; the Java heap is actually called the

Garbage-Collectible Heap. When you create an object, Java allocates memory space on the heap according to how much that particular object needs. An object with , say, 15 instance variables, will probably need more space than an object with only two instance variables. But what happens when you need to reclaim that space ? How do you get an object out of the heap when youre done with it? Java manages that memory for you! When the JV M can see that an object can never be used again, that object becomes eligible for garbage collection. And if youre running low on memory, the Garbage Collector will run, throw out the un reachable objects, and free up the space, so that the space can be reused. Reference variables: All references for a given JVM will be the same size regardless of the objects they reference, but each JVM might have a different way of representing references, so references on one JVM may be smaller or larger than references on another JVM. How big the reference variable is? You dont know. Unless youre cozy with someone on the JVMs development team, you dont know how a reference is represented. There are pointers in there somewhere, but you cant access them. You wont need to. (OK, if you insist, you might as well just imagine it to be a 64-bit value.) But when youre talking about memory allocation issues, your Big Concern should be about how many objects (as opposed to object references) youre creating, and how big they (the objects) really are. 1. 2. 3. 4. 5. 6. 7. 8. 9. Unreachable objects are eligible for garbage collection The final variables are not allowed to be assigned again. Variables come in two flavors: primitive and reference. Variables must always be declared with a name and a type. A primitive variable value is the bits representing the value (5, a, true, 3.1416, etc.). A reference variable value is the bits representing a way to get to an object on the heap. A reference variable is like a remote control. Using the dot operator (.) on a reference variable is like pressing a button on the remote control to access a method or instance variable. A reference variable has a value of null when it is not referencing any object. An array is always an object, even if the array is declared to hold primitives. There is no such thing as a primitive array, only an array that holds primitives.

Difference between instance variables and local variables

Instance variables are declared within the class. Instance variables always get a default value if you dont explicitly set a value. Integers ------ 0 Floating points --------- 0.0 Boolean ------ false References--- null Local variables are declared within the method. They dont get a default value if you dont assign a value. They must be initialized before they are used. The compiler complains you if you use the local variables before they are initialized. Public void change(){ Int x; Int y = x + 4; //error X = 10; Int z = x + 4;//Okay } Method parameters are virtually the same as local variablestheyre declared inside the method (well, technically theyre declared in the argument list of the method rather than within the body of the method, but theyre still local variables as opposed to instance variables). But method parameters will never be uninitialized, so youll never get a compiler error telling you that a parameter variable might not have been initialized. Comparison: The == compares between primitive values. It compares bits within the variables. And if the two reference variables are refereeing same object on the heap, == returns true. Foo a = new Foo(); Foo b = new Foo(); Foo c = a; if (a == b) { // false } if (a == c) { // true } if (b == c) { // false } Pass by Value: Java is a pass by value that means pass by copy. When the variables are passed to the methods the bits representing values are get actually copied and copies will be passed instead of originals. In the case of primitives the bits are copied and copies are sent to method and the original values are remains same after the completion of method execution even though the parameters of the method have

been changed inside the method. The method cant change the bits that were in the calling variable. In the case of reference variables, the copies of reference variables are sent to the method. And both the original and copy referring to the same object in the heap, the modification made on the state of objects during the method execution can be accessed by the original reference variable too. class PassByCopyTest { static void change(int y){ y = y + 10; } static void change(A obj){ obj.x = 15; } public static void main(String[] args) { System.out.println("Pass by copy example"); int a = 20; System.out.println("Primitive variable after change: "+a); change(a); System.out.println("Primitive variable after change: "+a); A obj = new A(); obj.x = 30; System.out.println("Object state before change : "+obj.x); change(obj); System.out.println("Object state after change : "+obj.x); } } class A { int x = 20; } ---------- run ---------Pass by copy example Primitive variable after change: 20 Primitive variable after change: 20 Object state before change : 30 Object state after change : 15

Arrays Arrays are always objects, whether theyre declared to hold primitives or object references. But you can have an array object thats declared to hold primitive values. In other words, the array object can have elements which are primitives, but the array itself is never a primitive. Regardless of what the array holds, the array itself is always an object!. Array of references hold references not objects. Every element in an array is just a variable. In other words, one of the eight primitive variable types (think: Large Furry Dog) or a reference variable. Anything you would put in a variable of that type can be assigned to an array element of that type. So in an array of type int (int[]), each element can hold an int. In a Dog array (Dog[]) each element can hold... a Dog? No, remember that a reference variable just holds a reference (a remote control), not the object itself. So in a Dog array, each element can hold a remote control to a Dog. Encapsulation: Encapsulation is nothing but hiding the details. Encapsulation puts a force-field around my instance variables, so nobody can set them to, lets say, something inappropriate. It is good practice, make the instance variables as private and provide public setter and getter methods to access them. Inheritance 1. A subclass extends a superclass. 2. A subclass inherits all public instance variables and methods of the superclass, but 3. does not inherit the private instance variables and methods of the superclass. 4. Inherited methods can be overridden; instance variables cannot be overridden (although they can be redefined in the subclass, but thats not the same thing, and theres almost never a need to do it.) 5. Use the IS-A test to verify that your inheritance hierarchy is valid. If X extends Y, 6. then X IS-A Y must make sense. 7. The IS-A relationship works in only one direction. A Hippo is an Animal, but not all 8. Animals are Hippos. 9. When a method is overridden in a subclass, and that method is invoked on an instance of 10. the subclass, the overridden version of the method is called. (The lowest one wins.) 11. If class B extends A, and C extends B, class B IS-A class A, and class C IS-A class B, and class C also IS-A class A. What does all this inheritance buy you:

1. You can get rid of duplicate code by abstracting out the behavior common to a group of classes, and sticking that code in a superclass. That way, when you need to modify it, you have only one place to update, and the change is magically reflected in all the classes that inherit that behavior. 2. Just deliver the newly-changed superclass, and all classes that extend it will utomatically use the new version. Polymorphism With polymorphism, the reference type can be a superclass of the actual object type. Using polymorphic arguments, where you can declare the method parameter as a superclass type, you can pass in any subclass object at runtime. Polymorphism lets you use a more abstract supertype (including an interface) reference to refer to one of its subtypes (including interface implementers).

Aninal getAnimal(){ } Void method(Animal animal){ } //method(new Tiger());// With polymorphic perspective, we can design Animal-using programs with Animal arguments (and array declarations) Overriding rules: 1. Arguments must be the same, and return types must be compatible. The contract of superclass defines how other code can use a method. Whatever the superclass takes as an argument, the subclass overriding the method must use that same argument and same in the order. And whatever the superclass declares as a return type, the overriding method must declare either the same type, or a subclass type. Remember, a subclass object is guaranteed to be able to do anything its superclass declares, so its safe to return a subclass where the superclass is expected. Error case: class A { OverridingTest one(){ return new OverridingTest();

} } class OverridingTest extends A { A one(){ return new OverridingTest(); } public static void main(String[] args) { System.out.println("Hello World!"); } } ---------- compile ---------OverridingTest.java:11: one() in OverridingTest cannot override one() in A; attempting to use incompatible return type found : A required: OverridingTest A one(){ ^ 1 error Output completed (0 sec consumed) Success case: class A { A one(){ return new OverridingTest(); } } class OverridingTest extends A { OverridingTest one(){ return new OverridingTest(); } public static void main(String[] args) { System.out.println("Hello World!"); } }

2. The method cant be less accessible. The access modifier of overridden method in subclass cant be less than that of the overridden method in superclass. Order of access modifiers : private, default, protected, public Error case class A { public A one(){ return new OverridingTest(); } } class OverridingTest extends A { OverridingTest one(){ //OverridingTest.java:11: one() in OverridingTest cannot override one() //in A; attempting to assign weaker access privileges; was public return new OverridingTest(); } public static void main(String[] args) { System.out.println("Hello World!"); } } Success case: class A { A one(A a ){ return new OverridingTest(); } A one(OverridingTest a){ return new OverridingTest(); } } //Arguments types are not exactly same. 3. The throws clause: Every method has RutimeException (unchecked exception) in its throws clause by default. Sub class method should not define checked exception in throws clause if the super class method didnt. Sub class method can throw its sub class exception not super class exception. 4. The overriding method (sub class) CAN throw any unchecked (runtime) exception, regardless of whether the overridden method declares the exception. (More in Chapter 5.)

5.

The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException. The overriding method can throw narrower or fewer exceptions. Just because an overridden method "takes risks" doesn't mean that the overriding subclass' exception takes the same risks. Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of what the overridden method declares.

6.

Overloading: Method overloading is nothing more than having two methods with the same name but different argument lists. Theres no polymorphism involved with overloaded methods! Overloading lets you make multiple versions of a method, with different argument lists 1. The return types can be different. Youre free to change the return types in overloaded methods, as long as the argument lists are different. 2. You cant change ONLY the return type. If only the return type is different, its not a valid overloadthe compiler will assume youre trying to override the method. And even that wont be legal unless the return type is a subtype of the return type declared in the superclass. To overload a method, you MUST change the argument list, although you can change the return type to anything. 3. You can vary the access levels in any direction. Youre free to overload a method with a method thats more restrictive. It doesnt matter, since the new method isnt obligated to fulfill the contract of the overloaded method. class A { A one(){ return new OverridingTest(); } OverridingTest one(){ //OverridingTest.java:7: one() is already defined in A return new OverridingTest(); } }

Final Final classes and methods provide security. If you need security of knowing that the methods will always work the way that you wrote them (because they cant be overridden), a final will help us. If you want to protect a specific method from being overridden, mark the method with the final modifier. Mark the whole class as final if you want to guarantee that none of the methods in that class will ever be overridden. Abstract class: Consider a scenario where Animal is the super class for Tiger, Lion and Wolf. We can create objects for Tiger, Lion and Wolf. We cant create object for Animal. Because we dont know what color, size and how many of legs the animal has. ENCAPSULATION (data hiding) The technique of hiding the internal implementation detail of an object from its external views. Internal structure remains private and services can be accessed by other objects only through messages passed via a clearly defined interface. Encapsulation ensures that the object providing service can prevent other objects from manipulating its data or procedures directly, and it enables the object requesting service to ignore the details of how that service is provided. Access specifiers: Protected: The sub class can access protected members of super class only through the inheritance. Once the subclass-outside-the-package inherits the protected member, that member (as inherited by the subclass) becomes private to any code outside the subclass, with the exception of subclasses of the subclass. The protected members become private to the subclass and its subclasses. The bottom line: when a subclass-outside-the-package inherits a protected member, the member is essentially private inside the subclass, such that only the subclass and its subclasses can access it through the inheritance. For years, object-oriented programmers knew that one of the main OOP features is encapsulation: an ability to hide and protect object internals. Private and protected properties were invented to support this. But who are we hiding from? From stupid developers who will decide to use our smart framework classes.

The Private and Protected section of the classes you design should contain Abstraction "java abstraction is data hiding concepts" this is completely incorrect. Encapsulation is used for data hiding not abstraction. Abstraction is a design concept on which we only declare functionality doesn't define it because we don't know about them at design point. For example if you are designing Server Class you know that there must be start() and stop() method but you don't know the exact way each server will start and stop because that will vary from server to server, so in this case we will declare Server as abstract. In Java abstraction is implemented using either abstract class or interface. Interface achieves 100% abstractness. what is abstraction ? something which is not concrete , something which is incomplete. java has concept of abstract classes , abstract method but a variable can not be abstract. an abstract class is something which is incomplete and you can not create instance of it for using it.if you want to use it you need to make it complete by extending it. an abstract method in java doesn't have body , its just a declaration. so when do you use abstraction ? ( most important in my view ) when I know something needs to be there but I am not sure how exactly it should look like. e.g. when I am creating a class called Vehicle, I know there should be methods like start() and Stop() but don't know start and stop mechanism of every vehicle since they could have different start and stop mechanism e..g some can be started by kick or some can be by pressing buttons .

the same concept apply to interface also , which we will discuss in some other post. so implementation of those start() and stop() methods should be left to there concrete implementation e.g. Scooter , MotorBike , Car etc. In Java Interface is an another way of providing abstraction, Interfaces are by default abstract and only contains public static final constant or abstract methods. Its very common interview question is that where should we use abstract class and where should we use Java Interfaces in my view this is important to understand to design better java application, you can go for java interface if you only know the name of methods your class should have e.g. for Server it should have start() and stop() method but we don't know how exactly these start and stop method will work. if you know some of the behavior while designing class and that would remain common across all subclasses add that into abstract class. Interfaces An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface. Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. 1. Interface is 100 % abstract. 2. Interfaces increase the abstractness by moving one step further when compare to abstract class and only allows to declare abstract methods and their implementation. 3. Interfaces are implicitly abstract. 4. Interface methods are by default public and abstract, they can not be static, native and strictfp. 5. All the member variables in interface are constants, public , static and final.

Difference between String, StringBuffer and StringBuilder Methods in String produce new objects rather than modifying the same object. So String is immutable(unchanged). String buffer and String builder is mutable(can be changed). And StringBuffer is thread safe (synchronized). StringBuilder is not. Nested classes Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes. A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private, public, protected, or package private. (Recall that outer classes can only be declared public or package private.) Inner classes: 1. Inner classes cant have main method to run, because a regular inner class can't have static declarations of any kind. The only way you can access the inner class is through a live instance of the outer class! In other words, only at runtime when there's already an instance of the outer class to tie the inner class instance to. 2. Since being a member of outer class, Inner class can access the members of outer class even they are private. 3. Inner class objects always have tied with outer class object. To create an instance of an inner class, you must have an instance of the outer class to tie to the inner class. There are no exceptions to this rule: an inner class instance can never stand alone without a direct relationship to an instance of the outer class. 4. You always need to create instance for inner class before you using the members. Declaring the inner class does not meant that outer class has a object of inner class. 5. Inner classes are basically designed to be helper classes for Outer classes. 6. Sample public class Outer { class Inner{

void display(){ System.out.println("Welcome to Inner classes"); } } void showMsg(){ Inner inner = new Inner(); //Outer.Inner inner1 = this.new Inner(); inner.display(); } public static void main(String[] args) { Outer.Inner inner = new Outer().new Inner(); inner.display(); } } 7. Member Modifiers Applied to Inner Classes A regular inner class is a member of the outer class just as instance variables and methods are, so the following modifiers can be applied to an inner class: 1. I final 2. I abstract 3. I public 4. I private 5. I protected 6. I staticbut static turns it into a static nested class not an inner class 7. I strictfp Method local Inner Class & Anonymous Inner Class Both the classes cannot access outside method local variables unless they are final. You must create an instance of this inner class before you use it. Static Inner Classes A static nested class is simply a class that's a static member of the enclosing class: The class itself isn't really "static"; there's no such thing as a static class. The static modifier in this case says that the nested class is a static member of the outer class. That means it can be accessed, as with other static members, without having an instance of the outer class. Just as a static method does not have access to the instance variables and nonstatic methods of the class, a static nested class does not have access to the instance variables and nonstatic methods of the

outer class. Look for static nested classes with code that behaves like a nonstatic (regular inner) class.

Inner Class Can have declaration of any kind static Can be instantiated from outside of class of outer class Can be created in a method No

Static Inner Class yes

Method Local Inner Class No

Anonymous Inner class No

Yes

Yes

No

No

No

No

Yes

Yes

Enume You should use enum types any time you need to represent a fixed set of constants. Java programming language enum types are much more powerful than their counterparts in other languages. The enu declaration defines a class m (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static va method l u that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself. All enums implicitly extend . j a v Since a . l a n n E . g Java does not support multiple inheritance, an enum cannot extend anything else. public enum Day {

MONDAY (1), TUESDAY (2), WEDNESDAY (3), THURSDAY (4), FRIDAY (5), SATURDAY (6), SUNDAY (7); private int day; private Day(int day){ this.setDay(day); } @Deprecated public void setDay(int day) { this.day = day; } public int getDay() { return day; } public static Day getDay(int day){ Day d = null; for(Day d1 : values()){ if(d1.getDay() == day){ d = d1; break; } } return d; } } Shutdown Hook In many circumstances, you need a chance to do some clean-up when the user shuts down your application. The problem is, the user does not always follow the recommended procedure to exit. Java provides an elegant way for programmers to execute code in the middle of the shutdown process, thus making sure your clean-up code is always executed. This article shows how to use a shutdown hook to guarantee that clean-up code is always run, regardless of how the user terminates the application. You may have code that must run just before an application completely exits. For example, if you are writing a text editor with Swing and your application creates a temporary edit file when it starts, this temporary file must be deleted when the user closes your application. If you are writing a servlet container such as Tomcat or

Jetty, you must call the destroy method of all loaded servlets before the application shuts down. In many cases, you rely on the user to close the application as prescribed. For instance, in the first example, you may provide a JButton that, when clicked, runs the clean up code before exiting. Alternatively, you may use a Window listener that listens to the windowClosing event. Tomcat uses a batch file that can be executed for a proper shutdown. However, you know that the user is the king; he or she can do whatever they want with the application. He or she might be nice enough to follow your instruction, but could just close the console or log off of the system without first closing your application. In Java, the virtual machine shuts down itself in response to two types of events: first, when the application exits normally, by calling the System.exit method or when the last non-daemon thread exits. Second, when the user abruptly forces the virtual machine to terminate; for example, by typing Ctrl+C or logging off from the system before closing a running Java program. Fortunately, the virtual machine follows this two-phase sequence when shutting down: The virtual machine starts all registered shutdown hooks, if any. Shutdown hooks are threads registered with the Runtime. All shutdown hooks are run concurrently until they finish. 2. The virtual machine calls all uninvoked finalizers, if appropriate. In this article, we are interested in the first phase, because it allows the programmer to ask the virtual machine to execute some clean-up code in the program. A shutdown hook is simply an instance of a subclass of the Thread class. Creating a shutdown hook is simple: 1. Write a class extending the Thread class. Provide the implementation of your class' run method. This method is the code that needs to be run when the application is shut down, either normally or abruptly. 3. In your application, instantiate your shutdown hook class. 4. Register the shutdown hook with the current runtime's addShutdownHook method. As you may have noticed, you don't start the shutdown hook as you would other threads. The virtual machine will start and run your shutdown hook when it runs its shutdown sequence. 1. 2. The code in Listing 1 provides a simple class called

ShutdownHookDemo and a subclass of Thread named ShutdownHook. Note that the run method of the ShutdownHook class simply prints the string "Shutting down" to the console. Of course, you can insert any code that needs to be run before the shutdown. After instantiation of the public class, its start method is called. The start method creates a shutdown hook and registers it with the current runtime. ShutdownHook shutdownHook = new ShutdownHook(); Runtime.getRuntime().addShutdownHook(shutdownHook); Then, the program waits for the user to press Enter. System.in.read(); When the user does press Enter, the program exits. However, the virtual machine will run the shutdown hook, printing the words "Shutting down." Listing 1: Using ShutdownHook package test; public class ShutdownHookDemo { public void start() { System.out.println("Demo"); ShutdownHook shutdownHook = new ShutdownHook(); Runtime.getRuntime().addShutdownHook(shutdownHook); } public static void main(String[] args) { ShutdownHookDemo demo = new ShutdownHookDemo(); demo.start(); try { System.in.read(); } catch(Exception e) { } } } class ShutdownHook extends Thread { public void run() { System.out.println("Shutting down"); } }

As another example, consider a simple Swing application whose class is called MySwingApp (see Figure 1). This application creates a temporary file when it is launched. When closed, the temporary file must be deleted. The code for this class is given in Listing 2 on the following page.

Figure 1: A simple Swing application package test;

import import import import import

java.awt.*; javax.swing.*; java.awt.event.*; java.io.File; java.io.IOException;

public class MySwingApp extends JFrame { JButton exitButton = new JButton(); JTextArea jTextArea1 = new JTextArea(); String dir = System.getProperty("user.dir"); String filename = "temp.txt"; public MySwingApp() { exitButton.setText("Exit"); exitButton.setBounds(new Rectangle(304, 248, 76, 37)); exitButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { exitButton_actionPerformed(e); } }); this.getContentPane().setLayout(null); jTextArea1.setText("Click the Exit button to quit"); jTextArea1.setBounds(new Rectangle(9, 7, 371, 235)); this.getContentPane().add(exitButton, null); this.getContentPane().add(jTextArea1, null); this.setDefaultCloseOperation(EXIT_ON_CLOSE);

this.setBounds(0,0, 400, 330); this.setVisible(true); initialize(); } private void initialize() { // create a temp file File file = new File(dir, filename); try { System.out.println("Creating temporary file"); file.createNewFile(); } catch (IOException e) { System.out.println("Failed creating temporary file."); } } private void shutdown() { // delete the temp file File file = new File(dir, filename); if (file.exists()) { System.out.println("Deleting temporary file."); file.delete(); } } void exitButton_actionPerformed(ActionEvent e) { shutdown(); System.exit(0); } public static void main(String[] args) { MySwingApp mySwingApp = new MySwingApp(); } } When run, the application calls its initialize method. The initialize method, in turn, creates a temporary file called temp.txt in the user's directory: private void initialize() { // create a temp file File file = new File(dir, filename); try {

System.out.println("Creating temporary file"); file.createNewFile(); } catch (IOException e) { System.out.println("Failed creating temporary file."); } } When the user closes the application, the application must delete the temporary file. We hope that the user will always click the Exit button-by doing so, the shutdown method (which deletes the temporary file) will always be called. However, the temporary file will not be deleted if the user closes the application, by clicking the X button of the frame or by some other means. Listing 3 offers a solution to this. It modifies the code in Listing 2 by providing a shutdown hook. The shutdown hook class is declared as an inner class so that it has access to all of the methods of the main class. In Listing 3, the shutdown hook's run method calls the shutdown method, guaranteeing that this method will be invoked when the virtual machine shuts down. Listing 3: Using a shutdown hook in the Swing application package test; import import import import import java.awt.*; javax.swing.*; java.awt.event.*; java.io.File; java.io.IOException;

public class MySwingAppWithShutdownHook extends JFrame { JButton exitButton = new JButton(); JTextArea jTextArea1 = new JTextArea(); String dir = System.getProperty("user.dir"); String filename = "temp.txt"; public MySwingAppWithShutdownHook() { exitButton.setText("Exit"); exitButton.setBounds(new Rectangle(304, 248, 76, 37)); exitButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { exitButton_actionPerformed(e);

} }); this.getContentPane().setLayout(null); jTextArea1.setText("Click the Exit button to quit"); jTextArea1.setBounds(new Rectangle(9, 7, 371, 235)); this.getContentPane().add(exitButton, null); this.getContentPane().add(jTextArea1, null); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setBounds(0,0, 400, 330); this.setVisible(true); initialize(); } private void initialize() { // add shutdown hook MyShutdownHook shutdownHook = new MyShutdownHook(); Runtime.getRuntime().addShutdownHook(shutdownHook); // create a temp file File file = new File(dir, filename); try { System.out.println("Creating temporary file"); file.createNewFile(); } catch (IOException e) { System.out.println("Failed creating temporary file."); } } private void shutdown() { // delete the temp file File file = new File(dir, filename); if (file.exists()) { System.out.println("Deleting temporary file."); file.delete(); } } void exitButton_actionPerformed(ActionEvent e) { shutdown(); System.exit(0); }

public static void main(String[] args) { MySwingAppWithShutdownHook mySwingApp = new MySwingAppWithShutdownHook(); } private class MyShutdownHook extends Thread { public void run() { shutdown(); } } } Pay special attention to the initialize method in the class shown in Listing 3. The first thing it does is to create an instance of the inner class MyShutdownHook, which extends a Thread: // add shutdown hook MyShutdownHook shutdownHook = new MyShutdownHook(); Once you get an instance of the MyShutdownHook class, pass it to the addShutDownHook method of the Runtime, as in the following line: Runtime.getRuntime().addShutdownHook(shutdownHook); The rest of the initialize method is similar to the initialize method in the class given in Listing 2. It creates a temporary file and prints a string "Creating temporary file": // create a temp file File file = new File(dir, filename); try { System.out.println("Creating temporary file"); file.createNewFile(); } catch (IOException e) { System.out.println("Failed creating temporary file."); } Now, start the small application given in Listing 3. Check that the temporary file is always deleted, even if you abruptly shut down the application. Summary Sometimes we want our application to run some clean-up code prior to shutting down. However, it is impossible to rely on the user to always quit properly. The shutdown hook described in this article offers a solution that guarantees that the clean-up code is run, regardless of

how the user closes the application. Q: What is OOPS, object and class. A: OOPS provide the way of modularizing the program by creating partitioned memory area for both data and operations. OOPS allows describing the problem in terms of problem rather than in terms of computer where the solution will run and follows bottom-up approach in design. Objects are run time entities (physical entities) represent the real world entities. That has both data and operations to manipulate data. We can make request to object asking it to perform its operations by sending messages (making a call to method of object). Each object occupies its own memory. Thats the way all object are communicate each other through sending message. Object is an entity, we can feel and touch. Objects are really existed in real world. In theory the conceptual concept of problem is represented as object in problem space. Class is user defined data type that represents the logical idea of real world entity and describes the properties and behavior of real world entity. Class is blue print or plan, we cant feel and touch. Classes are not existed in real world. Q. What is inheritance? A. Is the process by which an object can acquires the properties of another object. Inheritance allows the creation of hierarchical classification. Which defines an interface is common for a set of related items. Which provides is-a relationship between classes. For example A Triangle is a Shape. A class is inherited is called superclass and a class does inheriting is called subclass. The main goal of inheritance is to provide code reusability. a) All the messages send to object of superclass can also send to subclass. b) We can add additional features to the existing type with out disturbing it. c) We can change the behavior of new class. This is called overriding. It means we are using same interface as existing type, but we are making it something different for new type. Q What is the difference between an Interface and an Abstract class? : A:An abstract class provides common interface for all its subclasses. And this common interface expressed differently in sub classes. An abstract class is a class that is declared abstractit may or may not include abstract methods. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract

methods in its parent class. However, if it does not, the subclass must also be declared abstract. Abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. An abstract class can have instance methods, instance variables that implement a default behavior. Abstract class may also contain abstract methods which has no implementation. An abstract class may have static fields and static methods. You can use these static members with a class referencefor example, AbstractClass.staticMethod()as you would with any other class. An abstract class can not be instantiated. And may refer the sub classs objects. Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods which are not private.

abstract class GraphicObject { int x, y; ... void moveTo(int newX, int newY) { ... } abstract void draw(); abstract void resize(); } class Circle extends GraphicObject { void draw() { ... } void resize() { ... } } class Rectangle extends GraphicObject { void draw() { ... }

void resize() { ... } } An Interface can only declare constants and abstract methods which has no implementation. An interface has all public members and no implementation. Interface may contain fields those are public, static and final implicitly. An interface may can extend any number of interfaces. All methods declared in an interface are implicitly public, so the public modifier can be omitted. An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, these modifiers can be omitted. An interface cannot provide any code at all, much less default code. An abstract class can provide complete code, default code, and/or just stubs that have to be overridden. Abstract class provides is-a relationship. Interface provides has-a or can-do relationship. 1.MyThread is a Thread. 2.MyCode has a runnable independent capability(Runnable). Interfaces are often used to describe the minor abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects. An abstract class defines the central part identity of its children. If you defined a Dog abstract class then Damamation descendants are Dogs(is-a), they are not only dogable. In a Java context, users should typically implement the Runnable interface rather than extending Thread, because they're not really interested in providing some new Thread functionality, they normally just want some code to have (has-a)the capability of thread(running independently). They want to create something that can be run in a thread, not a new kind of thread. When you implement the inteface, It strictly force you to start from scratch without any default implementation. You have to obtain your tools from other classes; nothing comes with the interface other than a few constants. This gives you freedom to implement a very different internal design. You must use the abstract class as-is for the code base, with all its attendant belongings, good or bad. The abstract class author has imposed structure on you. Depending on the cleverness of the author of the abstract class, this may be good or bad. If implementors/subclasses are homogeneous, tend towards an abstract base class. If they are heterogeneous, use an interface. If

the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class(abstract class). If all they share is a set of method signatures, then tend towards an interface. When to choose Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design frequently, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks. Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework.

Q. Difference between Overloading and overriding A. Using the same name for operations on different types is called overloading. Method overloading allows several methods to share the same name but with a different set of parameters (does not depend on return type). Each overloaded method performs a similar task. Overloaded methods are normally used to perform similar operations that involve different programming logic on different data types. Overloading occurs within a class. Another common use of overloading is when defining constructors: public Time( ) //default constructor public Time( int hr, int min, int sec ) //general constructor public Time( Time time ) //copy constructor Overriding is similar to overloading, with the exception that it occurs between classes and each method has the same signature. An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.A subclass can override a superclass method by redefining that method. When the method is mentioned by name in the subclass, then the subclass version is automatically used. Overloading deals with multiple methods in the same class with the same name but different signatures. Overriding deals with two

methods, one in a parent class and one in a child class that have the same signature. Overloading lets you define a similar operation in different ways for different data. Overriding lets you define a similar operation in different ways for different object types. Instance method cannot override the static methods and vice-versa. While overriding be care of weaker privileges (The method must have higher access specifier than that of in super class). Q What is the purpose of garbage collection in Java, and when is it : used? A:The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. In java memory deallocation is done automatically. When object has no reference is exists then it is treated to be no longer needed. Then the garbage collector reclaims the memory occupied by that object. The finalize () method on object is called just prior to object is going to be garbage collected. Which is usually cleans up or releases the resources used by that object. We can do garbage collection manually by a call System.gc(); Example: class NoOfObjects { String nameOfObject; static int count=0; NoOfObjects(String name) { nameOfObject=name; System.out.println("object "+nameOfObject+" is created"); count++; } /*finalize method is called just before object is going to be garbage collected.*/ public void finalize() { count--; System.out.println(nameOfObject+" is garbage collected"); } public static void main(String[] args) { NoOfObjects a=new NoOfObjects("a");

NoOfObjects b=new NoOfObjects("b"); new NoOfObjects("c"); System.out.println("no of objects "+NoOfObjects.count); b=null; System.gc(); System.out.println("no of objects "+NoOfObjects.count); } } Initializing the base class

are

are

In super class, when we dont have any constructors or we have implemented default constructor and parameterized constructors, there is no need to call super class constructor from base class constructor. If we have parameterized constructor and not having any implemented default constructor then we have to call super classs constructor from base class constructor. Why because the default is lost when we have implemented any constructor. Initializing and loading of child class Class (.class file) is loaded at the point of used first. This is usually when the object of that is class is constructed, but loading also occurs when a static field or static method is accessed. When a class file is going to be loaded it checks extends keyword, if there is super class then first super class is loaded then the child class. If the base class again has another base class, that second class would then be loaded, and so on. Class A { } Class B extends A { } Class C extends B { } Class Demo { //C.staticMethod(); or new C(); ----} A is first loaded, then B, finally C. 1. All the static variables and static block are loaded in textual order (the order that you write down in class definition). And statics also initialized only once. 2. After all the initialization variables and initialization block are loaded in textual order (the order that you write down in class definition). And these are initialized as many as times as no of objects are created.

3. Finally constructor is executed. For example Class A { } Clsss B extends A {} Class Demo { Public static void main(String a[]) { B ob1 =new B(); B ob2=new B(); } } //end Demo Execution flow B ob1=new B(); 1. Static variables and static block of class A in textual order. These are executed only once. 2. Static variables and static block of class B in textual order. These are executed only once. 3. Instance variables and initialization block of class A in textual order and finally constructor. 4. Instance variables and initialization block of class B in textual order and finally constructor. B ob2=new B() 5. Instance variables and initialization block of class A in textual order and finally constructor. 6. Instance variables and initialization block of class B in textual order and finally constructor. What is final? Final means it is constant. A field is both static and final is single storage field that cannot be changed. Final classes can not be inherited. We can change the fields in final class objects as well as final objects (it means fields in final class are not final). All the methods in final class are implicitly final. Final primitives are can not be changed. Final referenced variables are can not point to another objects. But the objects are modifiable. This is also for arrays. Those array contents can be modified. Finals that are declared as final but not given an initialization values are called blank finals. Blank finals must be initialized in constructor. Final arguments cannot be changed (primitives cannot be changed, references can not point to other objects) within the method. But we can read them. Final methods are not overridden. We can prevent the change of code. All the private methods in a class are implicitly final. final class B {

final int b; int c; B() { b=c; } void change(int i) { //b=i; final variable b can not be changed } int a=40; } class A //extends B --A final class canot be inherited { A () { } A (B b,final int c,final B d) { b=new B();//ok //d=new B();//cant change //c=20; cannot change } final private void bb() { } int y; } Public class FinalDemo { final int x=30; final A ob=new A(); final int arr[]=new int[9]; void fun1() { ob.y=20; arr[6]=90; //x=80; primitive finals can not be changed //ob=new A();

//arr=new int[90]; int z; z=20; System.out.println(z); final A a; //System.out.println(a); //a.y=0; we cannot use local variable before //assinging it even it is non-final B oa=new B(); oa.a=70; //we can change final class objects System.out.println("ok"); } /** * @param args */ public static void main(String[] args) { FinalDemo i=new FinalDemo(); i.fun1(); i.ob.y=80; //x=90; // TODO Auto-generated method stub } } Q. What is singleton java class? A java class allows to create only one object for it is called singleton java class. Creation: class SingleTon { private static SingleTon obj=null; private SingleTon() { } static SingleTon getObj() { obj=new SingleTon(); return obj; } public clone()

{ throw new CloneNotSupportedException(); } }

Q Describe synchronization in respect to multithreading. : A: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 variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors. Synchronization allows one thread can use the resource at a time. In java every object has its own monitor implicitly so that it is entered automatically when a thread uses a objects synchronized method, no other threads can invoke any synchronized method on same object. Q Explain different way of using thread? : A:The thread could be implemented by using Runnable interface or by inheriting from the Thread class. The former is more advantageous, because when you are going for multiple inheritance., the only interface can help. Q: What are pass by reference and passby value? A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed. Q: What is HashMap and Map? A: Map is Interface and Hashmap is class that implements that. Maps store a key / value pairs. Keys are unique. Some Maps allows null key and null value others can not. HashMap uses hashing when storing the elements. When we are using HashMap, specify the object as key and value that linked to that object key. The key is then hashed. The resulting hashcode is used as the index at which the value is stored in map. These hashcodes are used to look up the values. HashMap allows nulls as both keys and values. Hashing is used to get fast lookup. Q: Difference between HashMap and HashTable?

A: Hashtable is synchronized whereas HashMap not. The HashMap class is roughly equivalent to HashTable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. In addition to methods defined by Map interface a Hastable adds some of legacy methods for better performance. Q: Difference between ArrayList and LinkedList? If you need to support random access (getting elements from anywhere), without inserting or removing elements at/from any place other than the end, then ArrayList offers the optimal collection. Randomly accessing elements in ArrayList is a constant time operation. It takes same time regardless where from you accessing element. In LinkedList it is expensive. Both are not synchronized. Both allow null values. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially then LinkedList offers the better implementation. In addition, LinkedList adds several methods for working with the elements at the ends of the list (only the new methods are shown in the following diagram):

By using these new methods, you can easily treat the LinkedList as a stack, queue, or other end-oriented data structure. Basics The underlaying data structure for the ArrayList is the array, and for the LinkedList the linked list. This means for the ArrayList; fast random access but slow insert/remove except adding elements at the end because the array index gets you right to that element. But then adding and deleting at the start and middle of the arraylist would be slow, because all the later elements have to copied forward or backward. (Using System.arrayCopy()). when run an "add(Object o)" command a new array will be created

with n+1 dimension. All "older" elements will be copied to first n elements and last n+1 one will filled with the value which you provide with add() method. To avoid that internal re-copying of arrays you should use ensureCapacity(int requestCapacity) method it will create an array only once. For example if you need to add new element to the end of an ArrayList you have to look at the size of the collection and then add that new element at n+1 place. In LinkedList you do it directly by addLast(E e) method. And for the LinkedList; slow random access but fast insert/remove anywhere. LinkedList is made up of a chain of nodes. Each node stores an element and the pointer to the next node. A singly linked list only has pointers to next. A doubly linked list has a pointer to the next and the previous element. This makes walking the list backward easier. Linked lists are fast for inserts and deletes anywhere in the list, since all you do is update a few next and previous pointers of a node. Q Difference between Vector and ArrayList? : The Vector is a historical collection which is replaced by ArrayList. The documentation for ArrayList states "This class roughly equivalent to Vector, except that it unsynchronized."

is is

An ArrayList could be a good choice if you need very flexible Array type of collection with limited functionality. Vectors are a lot slower, performance wise, than ArrayLists. So, use Arraylists unless you need synchronised lists. Vector is historical class and was retrofitted to satisfy the List interface, but still retain the "old" methods (like getElementAt()). Vector is synchronized whereas ArrayList is not. Vector has many legacy methods that shows high performance and those are not part of collections. public synchronized void removeElementAt(int); protected void removeRange(int,int); public synchronized java.lang.Object firstElement(); public synchronized java.lang.Object lastElement(); public java.util.Enumeration elements(); public synchronized java.util.List subList(int,int); we can use Collections wrapper to get synchronization list List myList=new ArrayList(); myList = Collections.synchronizedList(myList)

Q. Difference between Iterator and ListLterator? A.ListIterator are obtainable only from collections that implements List interface. Iterator provides only forward access whereas List iterator can move in both directions. List iterator has higher performance. Iterator supports only removal of its content. ListIterator can also add and modify the elements to its content. ListIterator can produce the previous and next indexes respect to the current position. Q: Difference between Swing and Awt? A: AWT are heavy-weight components. Swings are light-weight components. Hence swing works faster than AWT. Q: What is the difference between a constructor and a method? A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

Q: State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers. A: public : Public class is visible in other packages, field is visible everywhere (class must be public too) private: Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature. protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature. This access is provided even to subclasses that reside in a different package from the class that owns the protected feature. default:What you get by default i.e., without any access modifier (public or private or protected).It means that it is visible to all within a particular package. Q What is static in java? :

A:Static block is executed when a class is loaded into memory. Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class. Static methods and variables can be used in non-static methods, reverse is not possible. Static methods can be overridden. you can't override a static method with a non-static method. In other words, you can't change a static method into an instance method in a subclass. Q What is final? : A:A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant). Q What if the main method is declared as private? : A:The program compiles properly but at runtime it will give "Main method not public." message. [ Recei ved from Sandes h Sadhal e] Q: What if the static modifier is removed from the signature of the main method? A: Program compiles. But at runtime throws an error "NoSuchMethodError". [ Receive d from Sandesh Sadhale] Q What if I write static public void instead of public static void? : A:Program compiles and runs properly. [ Received from Sandesh Sadhale] Q What if I do not provide the String array as the argument to the : method? A:Program compiles but throws a runtime error "NoSuchMethodError". [ Received from Sandesh Sadhale] Q What is the first argument of the String array in main method? : A:The String array is empty. It does not have any element. This is

unlike C/C++ where the first element by default is the program name. [ Received from Sandesh Sadhale] Q If I do not provide any arguments on the command line, then the : String array of Main method will be empty or null? A:It is empty. But not null. [ Received from Sandesh Sadhale] Q How can one prove that the array is not null but empty using one line : of code? A:Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length. [ Received from Sandesh Sadhale] Q What environment variables do I need to set on my machine in order : to be able to run Java programs? A:CLASSPATH and PATH are the two variables. [ Receiv ed from Sandesh Sadhale] Q Can an application have multiple classes having main method? : A:Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method. [ Receiv ed from Sandesh Sadhale] Q Can I have multiple main methods in the same class? : A:No the program fails to compile. The compiler says that the main method is already defined in the class. [ Receiv ed from Sandesh Sadhale] Q Do I need to import java.lang package any time? Why ? : A:No. It is by default loaded internally by the JVM. [ Receiv ed from Sandesh Sadhale]

Q Can I import same package/class twice? Will the JVM load the : package twice at runtime? A:One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. And the JVM will internally load the class only once no matter how many times you import the same class. Q: A: What are Checked and UnChecked Exception? A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be. What are different types of inner classes? Nested top-level classes, Member classes, Local classes, Anonymous classes Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety. Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Q: A:

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface. Because local classes are not members, the modifiers public, protected, private, and static are not usable. Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor. Q: Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile? A: Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol symbol : class ABCD location: package io import java.io.ABCD; [ Receive d from Sandesh Sadhale] Q: Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*? A: No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage. [ Receive d from Sandesh Sadhale] Q: What is the difference between declaring a variable and defining a variable? A: In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization. e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions. [ Receive d from Sandesh Sadhale] Q: What is the default value of an object reference declared as an instance variable? A: null unless we define it explicitly. [ Receive

d from Sandesh Sadhale] Q: Can a top level class be private or protected? A: No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected. [ Receive d from Sandesh Sadhale] Q: What type of parameter passing does Java support? A: In Java the arguments are always passed by value . [ Update from Eki and Jyothish Venu] Q: Primitive data types are passed by reference or pass by value? A: Primitive data types are passed by value. [ Received from Sandesh Sadhale] Q: Objects are passed by value or by reference? A: Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object. [ Update from Eki and Jyothish Venu] Q: What is serialization? A: Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream. [ Received from Sandesh Sadhale] Q: How do I serialize an object to a file? A: The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the

ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file. [ Received from Sandesh Sadhale] Q: Which methods of Serializable interface should I implement? A: The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods. [ Received from Sandesh Sadhale] Q:How can I customize the seralization process? i.e. how can one have a control over the serialization process? A: Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process. [ Received from Sandesh Sadhale] Q:What is the common usage of serialization? A: Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed. [ Received from Sandesh Sadhale] Q:What is Externalizable interface? A: Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods. [ Received from Sandesh Sadhale] Q:When you serialize an object, what happens to the object references included in the object? A: The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect. [ Received from

Sandesh Sadhale] Q:What one should take care of while serializing the object? A: One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException. [ Received from Sandesh Sadhale] Q:What happens to the static fields of a class during serialization? A: There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are 1. Serialization ignores static fields, because they are not part of ay particular state state. 2. Base class fields are only hendled if the base class itself is serializable. 3. Transient fields. [ Received from Sandesh Sadhale Modified after P.John David comments.] Q:Does Java provide any construct to find out the size of an object? A: No there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in Java. [ Received from Sandesh Sadhale] Q:Give a simplest way to find out the time a method takes for execution without using any profiling tool? A: Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution. To put it in code... long start = System.currentTimeMillis (); method (); long end = System.currentTimeMillis (); System.out.println ("Time taken for execution is " + (end - start)); Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing. [ Received from Sandesh Sadhale] Q:What are wrapper classes? A: Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc.

[ Received from Sandesh Sadhale] Q:Why do we need wrapper classes? A: It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object. [ Received from Sandesh Sadhale] Q:What are checked exceptions? A: Checked exceptions are those which the Java compiler forces you to catch. E.g. IOException are checked Exceptions. [ Received from Sandesh Sadhale] Q:What are runtime exceptions? A: Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time. [ Received from Sandesh Sadhale] Q:What is the difference between error and an exception? A: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.). [ Received from Sandesh Sadhale] Q:How to create custom exceptions? A: Your class should extend class Exception, or some more specific type thereof. [ Received from Sandesh Sadhale] Q:If I want an object of my class to be thrown as an exception object, what should I do? A: The class should extend from Exception class. Or you can extend your class from some more precise exception type also. [ Received from Sandesh Sadhale]

Q:If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object? A: One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well. [ Received from Sandesh Sadhale] Q:How does an exception permeate through the code? A: An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates. [ Received from Sandesh Sadhale] Q:What are the different ways to handle exceptions? A: There are two ways to handle exceptions, 1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and 2. List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions. [ Received from Sandesh Sadhale] Q:What is the basic difference between the 2 approaches to exception handling? 1> try catch block and 2> specifying the candidate exceptions in the throws clause? When should you use which approach? A: In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use. [ Received from Sandesh Sadhale] Q:Is it necessary that each try block must be followed by a catch

block? A: It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method. [ Received from Sandesh Sadhale] Q:If I write return at the end of the try block, will the finally block still execute? A: Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return. [ Received from Sandesh Sadhale] Q:If I write System.exit (0); at the end of the try block, will the finally block still execute? A: No in this case the finally block will not execute because when you say System. exit (0); the control immediately goes out of the program, and thus finally never executes. [ Received from Sandesh Sadhale] Q:How are Observer and Observable used? A: 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. [Received from Venkateswara Manam] Q:What is synchronization and why is it important? A: 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. [ Received from Venkateswara Manam] Q:How does Java handle integer overflows and underflows? A: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation. [ Received from Venkateswara Manam] Q:Does garbage collection guarantee that a program will not run out of memory? A: 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 . [ Received from Venkateswara Manam] Q:What is the difference between preemptive scheduling and time slicing? A: 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. [ Received from Venkateswara Manam] Q:When a thread is created and started, what is its initial state? A: A thread is in the ready state after it has been created and started. [ Received from Venkateswara Manam] Q:What is the purpose of finalization? A: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. [ Received from Venkateswara Manam] Q:What is the Locale class? A: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. [ Received from Venkateswara Manam] Q:What is the difference between a while statement and a do statement? A: 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. [ Received from Venkateswara Manam] Q:What is the difference between static and non-static variables? A: 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. [ Received from Venkateswara Manam] Q:How are this() and super() used with constructors? A: This() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. [ Received from Venkateswara Manam] Q:What are synchronized methods and synchronized statements? A: 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. [ Received from Venkateswara Manam] Q:What is daemon thread and which method is used to create the daemon thread? A: Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread. [ Received from Shipra Kamra] : Can applets communicate with each other? A: At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable. An applet can also get references to all other applets on the same page using the getApplets() method of java.applet.AppletContext. Once you get the reference to an applet, you can communicate with it by using its public members. It is conceivable to have applets in different virtual machines that talk to a server somewhere on the Internet and store any data that needs to be serialized there. Then, when another applet needs this data, it could connect to this same server. Implementing this is nontrivial. [ Received from Krishna Kumar ] Q:What are the steps in the JDBC connection? A: While making a JDBC connection we go through the following steps : Step 1 : Register the database driver by using : Class.forName(\" driver classs for that specific database\" ); Step 2 : Now create a database connection using : Connection con = DriverManager.getConnection(url,username,password); Step 3: Now Create a query using : Statement stmt = Connection.Statement(\"select * from TABLE NAME\"); Step 4 : Exceute the query : stmt.exceuteUpdate(); [ Received from Shri Prakash Kunwar] Q:How does a try statement determine which catch clause should be used to handle an exception?

A: 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 exceptionis executed. The remaining catch clauses are ignored. Q Can an unreachable object become reachable again? : A: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. [Received from P Rajesh] Q What method must be implemented by all threads? : A:All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface. [ Received from P Rajesh] Q What are synchronized methods and synchronized statements? : A: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. [ Received from P Rajesh] Q What is Externalizable? : A: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) [ Received from Venkateswara Manam] Q What modifiers are allowed for methods in an Interface? : A:Only public and abstract modifiers are allowed for methods in interfaces. [ Received from P Rajesh] Q What are some alternatives to inheritance? : A:Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is

harder to re-use (because it is not a subclass). [ Received from P Rajesh] Q What does it mean that a method or field is "static"? : A: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. [ Received from P Rajesh] Q What is the difference between preemptive scheduling and time : slicing? A: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. [ Received from P Rajesh] Q What is the catch or declare rule for method declarations? : A: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. [ Received from P Rajesh] Q:What is the Collections API? A: The Collections API is a set of classes and interfaces that support operations on collections of objects. [ Received from Prasanna Inamanamelluri] Q:What is the List interface? A: The List interface provides support for ordered collections of objects. [ Received from SPrasanna Inamanamelluri] Q What is the Vector class? : A:The Vector class provides the capability to implement a growable array of objects. [ Received from Prasanna Inamanamelluri] Q What is an Iterator interface? :

A:The Iterator interface is used to step through the elements of a Collection. [ Received from Prasanna Inamanamelluri] Q Which java.util classes and interfaces support event handling? : A:The EventObject class and the EventListener interface support event processing. [ Received from Prasanna Inamanamelluri] Q What is the GregorianCalendar class? : A:The GregorianCalendar provides support for traditional Western calendars [ Received from Prasanna Inamanamelluri] Q What is the Locale class? : A:The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. [ Received from Prasanna Inamanamelluri] Q What is the SimpleTimeZone class? : A:The SimpleTimeZone class provides support for a Gregorian calendar. [ Received from Prasanna Inamanamelluri] Q What is the Map interface? : A:The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values. [ Received from Prasanna Inamanamelluri] Q What is the highest-level event class of the event-delegation model? : A:The java.util.EventObject class is the highest-level class in the eventdelegation class hierarchy. [ Received from Prasanna Inamanamelluri] Q What is the Collection interface? : A:The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates. [ Received from Prasanna Inamanamelluri] Q What is the Set interface? : A:The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements. [ Received from Prasanna Inamanamelluri] Q What is the typical use of Hashtable? :

A:Whenever a program wants to store a key value pair, one can use Hashtable. [ Received from Sandesh Sadhale] Q I am trying to store an object using a key in a Hashtable. And some : other object already exists in that location, then what will happen? The existing object will be overwritten? Or the new object will be stored elsewhere? A:The existing object will be overwritten and thus it will be lost. [ Received from Sandesh Sadhale] Q What is the difference between the size and capacity of a Vector? : A:The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time. [ Received from Sandesh Sadhale] Q Can a vector contain heterogeneous objects? : A Yes a Vector can contain heterogeneous objects. Because a Vector stores everything in terms of Object. [ Received from Sandesh Sadhale] Q Can a ArrayList contain heterogeneous objects? : A:Yes a ArrayList can contain heterogeneous objects. Because a ArrayList stores everything in terms of Object. [ Received from Sandesh Sadhale] Q What is an enumeration? : A:An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection. [ Received from Sandesh Sadhale] Q Considering the basic properties of Vector and ArrayList, where will : you use Vector and where will you use ArrayList? A:The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one. [ Received from Sandesh Sadhale] Q Can a vector contain heterogeneous objects? :

A:Yes a Vector can contain heterogeneous objects. Because a Vector stores everything in terms of Object. 1) What is the difference between an Abstract class and Interface? Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code. A class can implement any number of interfaces, but subclass at most one abstract class. An abstract class can have no abstract methods. All methods of an interface are abstract. An abstract class can have instance variables. An interface cannot. An abstract class can define constructor. An interface cannot. An abstract class can have any visibility: public, protected, private or none (package). An interface's visibility must be public or none (package). An abstract class inherits from Object and includes methods such as clone() and equals(). 2) What is a user defined exception? User-defined exceptions may be implemented by defining a class to respond to the exception and

Embedding a throw statement in the try block where the exception can occur or declaring that the method throws the exception (to another method where it is handled). The developer can define a new exception by deriving it from the Exception class as follows:

code: public class MyException extends Exception { /* class definition of constructors (but NOT the exception handling code) goes here */ public MyException() { super(); } public MyException( String errorMessage ) {

super( errorMessage ); } } The throw statement is used to signal the occurance of the exception within a try block. Often, exceptions are instantiated in the same statement in which they are thrown using the syntax. code: throw new MyException("I threw my own exception.") To handle the exception within the method where it is thrown, a catch statement that handles MyException, must follow the try block. If the developer does not want to handle the exception in the method itself, the method must pass the exception using the syntax: code: public myMethodName() throws MyException 3) What is the difference between C++ & java? Well as Bjarne Stroustrup says "...Despite the syntactic similarities, C+ + and Java are very different languages. In many ways, Java seems closer to Smalltalk than to C++.... Here are few I discovered: Java is multithreaded

Java has no pointers Java has automatic memory management (garbage collection) Java is platform independent (Stroustrup may differ by saying "Java is a platform" Java has built-in support for comment documentation Java has no operator overloading Java doesnt provide multiple inheritance There are no destructors in Java

4) What are statements in JAVA ? Statements are equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon

Assignment expressions

Any use of ++ or -Method calls Object creation expressions

These kinds of statements are called expression statements. In addition to these kinds of expression statements, there are two other kinds of statements. A declaration statement declares a variable. A control flow statement regulates the order in which statements get executed. The for loop and the if statement are both examples of control flow statements. 5) What is JAR file?

JavaARchive files are a big glob of Java classes, images, audio, etc., compressed to make one simple, smaller file to ease Applet downloading. Normally when a browser encounters an applet, it goes and downloads all the files, images, audio, used by the Applet separately. This can lead to slower downloads. 6) What is JNI? JNI is an acronym of Java Native Interface. Using JNI we can call functions which are written in other languages from Java. Following are its advantages and disadvantages: Advantages:

You want to use your existing library which was previously written in other language. You want to call Windows API function. For the sake of execution speed. You want to call API function of some server product which is in c or c++ from java client.

Disadvantages:

You cant say write once run anywhere. Difficult to debug runtime error in native code. Potential security risk. You cant call it from Applet.

7) What is serialization? Quite simply, object serialization provides a program the ability to read or write a whole object to and from a raw byte stream. It allows Java objects and primitives to be encoded into a byte stream suitable for

streaming to some type of network or to a file-system, or more generally, to a transmission medium or storage facility. A seralizable object must implement the Serilizable interface. We use ObjectOutputStream to write this object to a stream and ObjectInputStream to read it from the stream. 8) Why there are some null interfaces in java? What does it mean? Give me some null interfaces in JAVA? Null interfaces act as markers..they just tell the compiler that the objects of this class need to be treated differently..some marker interfaces are : Serializable, Remote, Cloneable 9) What are checked and unchecked exceptions? Checked exceptions are the ones which you expect beforehand to be raised when an exceptional condition occurs and so write your code in a try-catch block to handle that sufficiently. For example: InsuffucientBalanceException which might be raised when money is being withdrawn from a bank account and the account has insufficient balance. Checked exceptions are sub classes of Exception. Unchecked exceptions are the ones which cannot be handled in the code. These are rather unexpected exceptions like NullPointerException, OutOfMemoryError, DivideByZeroException, typically, programming errors. Unchecked exceptions are subclasses of RunTimeExceptions. 10) Is synchronised a modifier?indentifier??what is it?? It's a modifier. 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. 1) What is singleton class?where is it used? Singleton is a design pattern meant to provide one and only one instance of an object. Other objects can get a reference to this instance through a static method (class constructor is kept private). Why do we need one? Sometimes it is necessary, and often sufficient, to create a single instance of a given class. This has advantages in memory management, and for java, in garbage collection. Moreover, restricting the number of instances may be necessary or desirable for technological or business reasons--for example, we may only want a

single instance of a pool of database connections. 2) What is a compilation unit? The smallest unit of source code that can be compiled, i.e. a .java file. 3) Is string a wrapper class? String is a class, but not a wrapper class. Wrapper classes like (Integer) exist for each primitive type. They can be used to convert a primitive data value into an object, and vice-versa. 4) Why java does not have multiple inheritance? The Java design team strove to make Java:

Simple, object oriented, and familiar Robust and secure Architecture neutral and portable High performance Interpreted, threaded, and dynamic

The reasons for omitting multiple inheritances from the Java language mostly stem from the "simple, object oriented and familiar" goal. As a simple language, Java's creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to C++ as possible (familiar) without carrying over C++'s unnecessary complexity (simple). In the designers' opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritance from the language (just as they cut operator overloading). The designers' extensive C++ experience taught them that multiple inheritance just wasn't worth the headache. 5) Why java is not a 100% oops? Many people say this because Java uses primitive types such as int, char, double. But then all the rest are objects. Confusing question.. 6)What is a resource bundle? In its simplest form, a resource bundle is represented by a text file containing keys and a text value for each key. 7) What is transient variable? Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

8)What is Collection API? The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.Example of interfaces: Collection, Set, List and Map. 9) Is Iterator a Class or Interface? What is its use? Iterator is an interface which is used to step through the elements of a Collection. 10) What is similarities/difference between an Abstract class and Interface? Differences are as follows:

Interfaces provide a form of multiple inheritance. 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. A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.

Similarities: Neither Abstract classes or Interface can be instantiated. 1) Is it the "servlets" directory or the "servlet" directory? For java Web server: on the file system, it's "servlets" c:\JavaWebServer1.1\servlets\DateServlet.class in a URL path, it's "servlet" http://www.stinky.com/servlet/DateServlet

2) How do I support both GET and POST protocol from the same Servlet? The easy way is, just support POST, then have your doGet method call your doPost method:

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req, res); } 3) How do I ensure that my servlet is thread-safe? ] This is actually a very complex issue. A few guidelines: 1. The init () method is guaranteed to be called once per servlet instance,when the servlet is loaded. You don't have to worry about thread safety inside this method, since it is only called by a single thread, and the web server will wait until that thread exits before sending any more threads into your service() method. 2. Every new client request generates (or allocates) a new thread; that thread calls the service () method of your servlet (which may in turn call doPost(), doGet() and so forth). 3. Under most circumstances, there is only one instance of your servlet, no matter how many client requests are in process. That means that at any given moment, there may be many threads running inside the service() method of your solo instance, all sharing the same instance data and potentially stepping on each other's toes. This means that you should be careful to synchronize access to shared data (instance variables) using the synchronized keyword. (Note that the server will also allocate a new instance if you register the servlet with a new name and, e.g., new init parameters.) 4. Note that you need not (and should not) synchronize on local data or parameters. And especially you shouldn't synchronize the service() method! (Or doPost(), doGet() et al.) 5. A simple solution to synchronizing is to always synchronize on the servlet instance itself using "synchronized (this) { ... }". However, this can lead to performance bottlenecks; you're usually better off synchronizing on the data objects themselves.

6. If you absolutely can't deal with synchronizing, you can declare that your servlet "implements SingleThreadModel". This empty interface tells the web server to only send one client request at a time into your servlet. From the JavaDoc: "If the target servlet is flagged with this interface, the servlet programmer is guaranteed that no two threads will execute concurrently the service method of that servlet. This guarantee is ensured by maintaining a pool of servlet instances for each such servlet, and dispatching each service call to a free servlet. In essence, if the servlet implements this interface, the servlet will be thread safe." Note that this is not an ideal solution, since performance may suffer (depending on the size of the instance pool), plus it's more difficult to share data across instances than within a single instance. See also What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization? 7. To share data across successive or concurrent requests, you can use either instance variables or class-static variables, or use Session Tracking. 8. The destroy() method is not necessarily as clean as the init() method. The server calls destroy either after all service calls have been completed, or after a certain number of seconds have passed, whichever comes first. This means that other threads might be running service requests at the same time as your destroy() method is called! So be sure to synchronize, and/or wait for the other requests to quit. Sun's Servlet Tutorial has an example of how to do this with reference counting. 9. Destroy () can not throw an exception, so if something bad happens, call log() with a helpful message (like the exception). See the "closing a JDBC connection" example in Sun's Tutorial. 4) What is the difference between URL encoding, URL rewriting, HTML escaping, and entity encoding? URL Encoding is a process of transforming user input to a CGI form so it is fit for travel across the network -- basically, stripping spaces and punctuation and replacing with escape characters. URL Decoding is the reverse process. To perform these operations, call java.net.URLEncoder.encode() and java.net.URLDecoder.decode() (the latter was (finally!) added to

JDK 1.2, aka Java 2). Example: changing "We're #1!" into "We%27re+%231%21" URL Rewriting is a technique for saving state information on the user's browser between page hits. It's sort of like cookies, only the information gets stored inside the URL, as an additional parameter. The HttpSession API, which is part of the Servlet API, sometimes uses URL Rewriting when cookies are navailable. Example: changing <A HREF="nextpage.html"> into <A HREF="nextpage.html;$sessionid$=DSJFSDKFSLDFEEKOE"> (or whatever the actual syntax is; I forget offhand) (Unfortunately, the method in the Servlet API for doing URL rewriting for session management is called encodeURL(). Sigh...) There's also a feature of the apache web server called URL Rewriting; it is enabled by the mod_rewrite module. It rewrites URLs on their way in to the server, allowing you to do things like automatically add a trailing slash to a directory name, or to map old file names to new file names. This has nothing to do with servlets. For more information, see the Apache faq (http://www.apache.org/docs/misc/FAQ.html#rewrite-moreconfig). 5) How do I upload a file to my servlet or JSP? On the client side, the client's browser must support formbased upload. Most modern browsers do, but there's no guarantee. For example, <FORM ENCTYPE='multipart/form-data' method='POST' action='/myservlet'> <INPUT TYPE='file' NAME='mptest'> <INPUT TYPE='submit' VALUE='upload'> </FORM> The input type &amp;quot;file&amp;quot; brings up a button for a file select box on the browser together with a text field that takes the file name once selected. The servlet can use the GET method parameters to decide what to do with the upload while the POST body of the request contains the file data to parse. When the user clicks the "Upload" button, the client browser locates the local file and sends it using HTTP POST, encoded using

the MIME-type multipart/form-data. When it reaches your servlet, your servlet must process the POST data in order to extract the encoded file. You can learn all about this format in RFC 1867. Unfortunately, there is no method in the Servlet API to do this. Fortunately, there are a number of libraries available that do. Some of these assume that you will be writing the file to disk; others return the data as an InputStream. Jason Hunter's MultipartRequest (available from http://www.servlets.com/) Apache Jakarta Commons Upload (package org.apache.commons.upload) "makes it easy to add robust, high-performance, file upload capability to your servlets and web applications" CParseRFC1867 (available from http://www.servletcentral.com/). HttpMultiPartParser by Anil Hemrajani, at the isavvix Code Exchange There is a multipart/form parser availailable from Anders Kristensen (http://wwwuk.hpl.hp.com/people/ak/java/, ak@hplb.hpl.hp.com) at http://www-uk.hpl.hp.com/people/ak/java/#utils. JavaMail also has MIME-parsing routines (see the Purple Servlet References). Jun Inamori has written a class called org.apache.tomcat.request.ParseMime which is available in the Tomcat CVS tree. JSPSmart has a free set of JSP for doing file upload and download. UploadBean by JavaZoom claims to handle most of the hassle of uploading for you, including writing to disk or memory. There's an Upload Tag in dotJ

Once you process the form-data stream into the uploaded file, you can then either write it to disk, write it to a database, or process it as an InputStream, depending on your needs. See How can I access or create a file or folder in the current directory from inside a servlet? and other questions in the Servlets:Files Topic for information on writing files from a Servlet.

Please note that you can't access a file on the client system directly from a servlet; that would be a huge security hole. You have to ask the user for permission, and currently form-based upload is the only way to do that. 6) How does a servlet communicate with a JSP page? The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing. public void doPost (HttpServletRequest request, HttpServletResponse response) { try { govi.FormBean f = new govi.FormBean(); String id = request.getParameter("id"); f.setName(request.getParameter("name")); f.setAddr(request.getParameter("addr")); f.setAge(request.getParameter("age")); //use the id to compute //additional bean properties like info //maybe perform a db query, etc. // . . . f.setPersonalizationInfo(info); request.setAttribute("fBean",f); getServletConfig().getServletContext().getRequestDispatch er ("/jsp/Bean1.jsp").forward(request, response); } catch (Exception ex) { ... }

} The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action. <jsp:useBean id="fBean" class="govi.FormBean" scope="request"/> <jsp:getProperty name="fBean" property="name" /> <jsp:getProperty name="fBean" property="addr" /> <jsp:getProperty name="fBean" property="age" /> <jsp:getProperty name="fBean" property="personalizationInfo" />

7) 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. 8) Can a servlet maintain a JTA UserTransaction object across multiple servlet invocations? No. A JTA transaction must start and finish within a single invocation (of the service() method). Note that this question does not address servlets that maintain and manipulate JDBC connections, including a connection's transaction handling. 9) How does the performance of JSP pages compare with that of servlets? How does it compare with Perl scripts? The performance of JSP pages is very close to that of servlets. However, users may experience a perceptible delay when a JSP

page is accessed for the very first time. This is because the JSP page undergoes a "translation phase" wherein it is converted into a servlet by the JSP engine. Once this servlet is dynamically compiled and loaded into memory, it follows the servlet life cycle for request processing. Here, the jspInit() method is automatically invoked by the JSP engine upon loading the servlet, followed by the _jspService() method, which is responsible for request processing and replying to the client. Do note that the lifetime of this servlet is non-deterministic - it may be removed from memory at any time by the JSP engine for resource-related reasons. When this happens, the JSP engine automatically invokes the jspDestroy() method allowing the servlet to free any previously allocated resources. Subsequent client requests to the JSP page do not result in a repeat of the translation phase as long as the servlet is cached in memory, and are directly handled by the servlet's service() method in a concurrent fashion (i.e. the service() method handles each client request within a seperate thread concurrently.) There have been some recent studies contrasting the performance of servlets with Perl scripts running in a "real-life" environment. The results are favorable to servlets, especially when they are running in a clustered environment. 10) How do I call one servlet from another servlet? [ Short answer: there are several ways to do this, including use a RequestDispatcher use a URLConnection or HTTPClient send a redirect

call getServletContext().getServlet(name) (deprecated, doesn't work in 2.1+) - Alex ] It depends on what you mean by "call" and what it is you seek to do and whyyou seek to do it. If the end result needed is to invoke the methods then the simplest mechanism would be to treat the servlet like any java object , create an instance and call the mehods.

If the idea is to call the service method from the service method of another servlet, AKA forwarding the request, you could use the RequestDispatcher object. If, however, you want to gain access to the instance of the servlet that has been loaded into memory by the servlet engine, you have to know the alias of the servlet. (How it is defined depends on the engine.) For example, to invoke a servlet in JSDK a servlet can be named by the property myname.code=com.sameer.servlets.MyServlet The code below shows how this named servlet can be accessed in the service method of another servlet public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... MyServlet ms=(MyServlet) getServletConfig().getServletContext().getServlet("myname "); ... } That said, This whole apporach of accessing servlets in another servlets has been deprecated in the 2.1 version of the servlet API due to the security issues. The cleaner and better apporach is to just avoid accessing other servlets directly and use the RequestDispatcher instead.

Why do GenericServlet and HttpServlet implement the Serializable interface? GenericServlet and HttpServlet implement the Serializable interface so that servlet engines can "hybernate" the servlet state when the servlet is not in use and reinstance it when needed or to duplicate servlet instances for better load balancing. I don't know if or how current servlet engines do this, and it could have serious implications, like breaking references to objects gotten in the init() method without the programmer knowing it. Programmers should be aware of this pitfall and

implement servlets which are stateless as possible, delegating data store to Session objects or to the ServletContext. In general stateless servlets are better because they scale much better and are cleaner code. How can I get the absolute URL of a servlet/JSP page at runtime ? You can get all the necessary information to determine the URL from the request object. To reconstruct the absolute URL from the scheme, server name, port, URI and query string you can use the URL class from java.net. The following code fragment will determine your page's absolute URL: String file = request.getRequestURI(); if (request.getQueryString() != null) { file += '?' + request.getQueryString(); } URL reconstructedURL = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), file); out.println(URL.toString()); 37) How do I deal with multi-valued parameters in a servlet? Instead of using getParameter() with the ServletRequest, as you would with single-valued parameters, use the getParameterValues() method. This returns a String array (or null) containing all the values of the parameter requested. What is meant by the term "business logic"? "Business logic" is just a fancy way of saying "code." :-) More precisely, in a three-tier architecture, business logic is any code that is not specifically related to storing and retrieving data (that's "data storage code"), or to formatting data for display to the user (that's "presentation logic"). It makes sense, for many reasons, to store this business logic in separate objects; the middle tier comprises these objects. However, the divisions between

the three layers are often blurry, and business logic is more of an ideal than a reality in most programs. The main point of the term is, you want somewhere to store the logic and "business rules" (another buzzword) of your application, while keeping the division between tiers clear and clean. 45) How can I explicitly unload a servlet or call the destroy method? In general, you can't. The Servlet API does not specify when a servlet is unloaded or how the destroy method is called. Your servlet engine (ie the implementation of the interfaces in the JSDK) might provide a way to do this, probably through its administration interface/tool (like Webshpere or JWS). Most servlet engines will also destroy and reload your servlet if they see that the class file(s) have been modified. 46) What is a servlet bean? A servlet bean is a serializable servlet that follows the JavaBeans component architecture, basically offering getter/setter methods. As long as you subclass GenericServlet/HttpServlet, you are automatically Serializable. If your web server supports them, when you install the servlet in the web server, you can configure it through a property sheet-like interface. 47) Why do we need to call super.init(config) in the init method of a servlet? Just do as you're told and you won't get hurt! :-) Because if you don't, then the config object will get lost. Just extend HttpServlet, use init() (no parameters) and it'll all work ok. From the Javadoc: init() - A convenience method which can be overridden so that there's no need to call super.init(config).

48) What is a servlet engine? A "servlet engine" is a program that plugs in to a web server and runs servlets. The term is obsolete; the preferred term now is "servlet container" since that applies both to plug-in engines and to stand-alone web servers that support the Servlet API. 49) Which is the most efficient (i.e. processing speed) way to create a server application that accesses a database: A Servlet using JDBC; a JSP page using a JavaBean to carry out the db access; or JSP combined with a Servlet? Are these my only choices? Your question really should be broken in two. 1-What is the most efficient way of serving pages from a Java object?. There you have a clear winner in the Servlet. Althought if you are going to change the static content of the page often is going to be a pain because you'll have to change Java code. The second place in speed is for JSP pages. But, depending on your application, the difference in speed between JSP pages and raw servlets can be so small that is not worth the extra work of servlet programming. 2-What is the most efficient way of accessing a database from Java?. If JDBC is the way you want to go the I'd suggest to pick as many drivers as you can (II,III,IV or wathever) and benchmark them. Type I uses a JDBC/ODBC bridge and usually has lousy performance. Again, go for the simplest (usually type IV driver) solution if that meets you performance needs. For database applications, the performance bottleneck is usually the database, not the web server/engine. In this case, the use of a package that access JDBC with connection pooling at the application level used from JSP pages (with or withouth beans as middleware) is the usual choice. Of course, your applications requirements may vary. 50) How can I change the port of my Java Web Server from 8080 to something else?

It is very simple. JAVA WEB SERVER comes with remote Web administration tool. You can access this with a web browser. Administration tool is located on port 9090 on your web server. To change port address for web server: 1. Access tool (http://hostname:9090) 2. Enter User Id/Password (by default it is admin/admin) 3. Select service (Web service) 4. Click on "manage" button. You will get a popup screen with all settings. 5. Click on network tree node, On right hand side you will get text box for entering port no. 6. Change port number with desire one. 7. click on restart button. 56) How can I call a servlet from a JSP page? How can I pass variables from the JSP that the servlet can access?

You can use <jsp:forward page="/relativepath/YourServlet" /> or response.sendRedirect("http://path/YourServlet"). Variables can be sent as: <jsp:forward page=/relativepath/YourServlet> <jsp:param name="name1" value="value1" /> <jsp:param name="name2" value="value2" /> </jsp:forward> You may also pass parameters to your servlet by specifying response.sendRedirect("http://path/YourServlet?param1=val1"). 57) Can there be more than one instance of a servlet at one time?

It is important to note that there can be more than one instance of a given Servlet class in the servlet container. For example, this can occur where there was more than one servlet definition that utilized a specific servlet class with different initialization parameters. This can also occur when a servlet implements the SingleThreadModel interface and the container creates a pool of servlet instances to

use. 58) How can I measure the file downloading time using servlets?

ServletOutputStream out = response.getOutputStream(); String filename = getServletContext().getRealPath(request.getQueryString()); FileInputStream fin = new FileInputStream(filename); long start = System.currentTimeMillis(); byte data[] = new byte[1024]; int len = 0; while ((len = fin.read(data)) > 0) { out.write(data, 0, len); } out.flush(); long stop = System.currentTimeMills(); log("took " + (stop - start) + "ms to download " + filename); 59) What is inter-servlet communication? As the name says it, it is communication between servlets. Servlets talking to each other. [There are many ways to communicate between servlets, including Request Dispatching HTTP Redirect Servlet Chaining HTTP request (using sockets or the URLConnection class) Shared session, request, or application objects (beans) Direct method invocation (deprecated) Shared static or instance variables (deprecated)

Search the FAQ, especially topic Message Passing (including Request Dispatching) for information on each of these techniques. -Alex] Basically interServlet communication is acheived through servlet

chaining. Which is a process in which you pass the output of one servlet as the input to other? These servlets should be running in the same server. e.g. ServletContext.getRequestDispatcher(HttpRequest, HttpResponse).forward("NextServlet") ; You can pass in the current request and response object from the latest form submission to the next servlet/JSP. You can modify these objects and pass them so that the next servlet/JSP can use the results of this servlet. There are some Servlet engine specific configurations for servlet chaining. Servlets can also call public functions of other servlets running in the same server. This can be done by obtaining a handle to the desired servlet through the ServletContext Object by passing it the servlet name ( this object can return any servlets running in the server). And then calling the function on the returned Servlet object. e.g. TestServlet test= (TestServlet)getServletConfig().getServletContext().getServlet("Othe rServlet"); otherServletDetails= Test.getServletDetails(); You must be careful when you call another servlet's methods. If the servlet that you want to call implements the SingleThreadModel interface, your call could conflict with the servlet's single threaded nature. (The server cannot intervene and make sure your call happens when the servlet is not interacting with another client.) In this case, your servlet should make an HTTP request to the other servlet instead of direct calls. Servlets could also invoke other servlets programmatically by sending an HTTP request. This could be done by opening a URL connection to the desired Servlet. 60) How do I make servlet aliasing work with Apache+Tomcat? When you use Tomcat standalone as your web server, you can modify the web.xml in $TOMCAT_HOME/webapps/myApp/WEB-INF to add a url-pattern: <web-app> <servlet> <servlet-name> myServlet

</servlet-name> <servlet-class> myServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> myServlet </servlet-name> <url-pattern> /jsp-bin/* </url-pattern> </servlet-mapping> </web-app> This will let you use: http://webserver:8080/myApp/jsp-bin/stuff.html instead of: http://webserver:8080/myApp/servlet/myServlet/stuff.html But it won't work on port 80 if you've integrated Tomcat with Apache. Graeme Wallace provided this trick to remedy the situation. Add the following to your tomcat-apache.conf (or to a static version of it, since tomcat re-generates the conf file every time it starts): <LocationMatch /myApp/jsp-bin/* > SetHandler jserv-servlet </LocationMatch> This lets Apache turn over handling of the url pattern to your servlet. Is there any way to determine the number of concurrent connections my servlet engine can handle? Depends on whether or not your servlet container uses thread pooling. If you do not use a thread pool, the number of concurrent connections accepted by Tomcat 3.1, for example, is 10. This you can see for yourself by testing a servlet with the Apache JMeter tool. However, if your servlet container uses a thread pool, you can specify the number of concurrent connections to be accepted by the container. For Tomcat 3.1, the information on how to do so is supplied with the documentation in the TOMCAT_HOME/doc/uguide directory. 62) What is a request dispatcher and how does it work? A RequestDispatcher object can forward a client's request to a resource or include the resource itself in the response back to the client. A resource can be

another servlet, or an HTML file, or a JSP file, etc. You can also think of a RequestDispatcher object as a wrapper for the resource located at a given path that is supplied as an argument to the getRequestDispatcher method. For constructing a RequestDispatcher object, you can use either the ServletRequest.getRequestDispatcher() method or the ServletContext.getRequestDispatcher() method. They both do the same thing, but impose slightly different constraints on the argument path. For the former, it looks for the resource in the same webapp to which the invoking servlet belongs and the pathname specified can be relative to invoking servlet. For the latter, the pathname must begin with '/' and is interpreted relative to the root of the webapp. To illustrate, suppose you want Servlet_A to invoke Servlet_B. If they are both in the same directory, you could accomplish this by incorporating the following code fragment in either the service method or the doGet method of Servlet_A: RequestDispatcher dispatcher = getRequestDispatcher("Servlet_B"); dispatcher.forward( request, response ); where request, of type HttpServletRequest, is the first parameter of the enclosing service method (or the doGet method) and response, of type HttpServletResponse, the second. You could accomplish the same by RequestDispatcher dispatcher=getServletContext().getRequestDispatcher( "/servlet/Servlet_B" ); dispatcher.forward( request, response ); 63) What is a Servlet Context? A Servlet Context is a grouping under which related servlets (and JSPs and other web resources) run. They can share data, URL namespace, and other resources. There can be multiple contexts in a single servlet container. The ServletContext object is used by an individual servlet to "call back" and obtain services from the container (such as a request dispatcher). Read the JavaDoc for javax.servlet.ServletContext for more information. You can maintain "application global" variables by using Servlet Context Attributes.

64) Does the RequestDispatcher expect a relative URL to be relative to the originally-called servlet or to the current servlet (if different)? Since the RequestDispatcher will be passing the control (request object and response object) from the current Servlet, the relative URL must be relative to the current servlet. The originally called servlet has passed the control to the current servlet, and now current servlet is acting as controller to other resourses. 65) What is the difference between in-process and out-of-process servlet containers? The in-process Servlet containers are the containers which work inside the JVM of Web server, these provides good performance but poor in scalibility. The out-of-process containers are the containers which work in the JVM outside the web server. poor in performance but better in scalibility In the case of out-of-process containers, web server and container talks with each other by using the some standard mechanism like IPC. In addition to these types of containers, there is 3rd type which is stand-alone servlet containers. These are an integral part of the web server. 66) How is SingleThreadModel implemented in Tomcat? In other containers? [I would assume that Tomcat uses its connection thread pool, and creates a new instance of the servlet for each connection thread, instead of sharing one instance among all threads. Is that true?]

The question mixes together two rather independent aspects of a servlet container: "concurrency control" and "thread pooling". Concurrency control, such as achieved by having a servlet implement the SingleThreadModel interface, addresses the issue of thread safety. A servlet will be thread-safe or thread-unsafe regardless of whether the servlet container used a thread pool. Thread pooling merely eliminates the overhead associated with the creation and destruction of threads as a servlet container tries to respond to multiple requests received simultaneously. It is for this reason that the specification document for Servlet 2.2 API is silent on the subject of thread pooling -- as it is merely an implementation detail. However, the document does indeed address the issue of thread safety and how and when to use SingleThreadModel servlets.

Section 3.3.3.1 of the Servlet 2.2 API Specification document says that if a servlet implements the SingleThreadModel it is guaranteed "that only one request thread at time will be allowed in the service method." It says further that "a servlet container may satisfy this guarantee by serializing requests on a servlet or by maintaining a pool of servlet instances." Obviously, for superior performance you'd want the servlet container to create multiple instances of a SingleThreadModel type servlet should there be many requests received in quick succession. Whether or not a servlet container does that depends completely on the implementation. My experiments show that Tomcat 3.1 does indeed create multiple instances of a SingleThreadModel servlet, but only for the first batch of requests received concurrently. For subsequent batches of concurrent requests, it seems to use only one of those instances. 67) Which servlet containers have persistent session support? Specifically, does Tomcat 3.1? All servlet containers that implement the Servlet 2.2 API must provide for session tracking through either the use of cookies or through URL rewriting. All Tomcat servlet containers support session tracking. 68) Can I use JAAS as the authentication technology for servlets ? Yes, JAAS can be used as authentication technology for servlets. One important feature of JAAS is pure Java implementation. The JAAS infrastructure is divided into two main components: an authentication component and an authorization component. The JAAS authentication component provides the ability to reliably and securely determine who is currently executing Java code, regardless of whether the code is running as an application, an applet, a bean, or a servlet. 69) How can I set a servlet to load on startup of the container, rather than on the first request? The Servlet 2.2 spec defines a load-on-startup element for just this purpose. Put it in the <servlet> section of your web.xml deployment descriptor. It is either empty (<load-on-startup/>) or contains "a positive integer indicating the order in which the servlet should be loaded. Lower integers are loaded before higher integers. If no value is specified, or if the value specified is not a positive integer, the container is free to load it at any time in the startup sequence." For example, <servlet>

<servlet-name>foo</servlet-name> <servlet-class>com.foo.servlets.Foo</servlet-class> <load-on-startup>5</load-on-startup> </servlet> Some servlet containers also have their own techniques for configuring this; please submit feedback with information on these. 70) Is it possible to write a servlet that acts as a FTP server? Yes. It would spawn a thread that opens a ServerSocket, then listens for incoming connections and speaks the FTP protocol. 74) What are the different cases for using sendRedirect() vs. getRequestDispatcher()? When you want to preserve the current request/response objects and transfer them to another resource WITHIN the context, you must use getRequestDispatcher or getNamedDispatcher. If you want to dispatch to resources OUTSIDE the context, then you must use sendRedirect. In this case you won't be sending the original request/response objects, but you will be sending a header asking to the browser to issue a request to the new URL.

If you don't need to preserve the request/response objects, you can use either. 75) How do I access the value of a cookie using JavaScript? You can manipulate cookies in JavaScript with the document.cookie property. You can set a cookie by assigning this property, and retrieve one by reading its current value. The following statement, for example, sets a new cookie with a minimum number of attributes: document.cookie = "cookieName=cookieValue"; And the following statement displays the property's value: alert(document.cookie); The value of document.cookie is a string containing a list of all cookies that are associated with a web page. It consists, that is, of name=value pairs for each cookie that matches the current domain, path, and date. The value of the document.cookie property, for instance, might be the following string: cookieName1=cookieValue1; cookieName2=cookieValue2;

76) How do I write to a log file using JSP under Tomcat? Can I make use of the log() method for this? Yes, you can use the Servlet API's log method in Tomcat from within JSPs or servlets. These messages are stored in the server's log directory in a file called servlet.log. 77) How can I use a servlet to print a file on a printer attached to the client? The security in a browser is designed to restrict you from automating things like this. However, you can use JavaScript in the HTML your servlet returns to print a frame. The browser will still confirm the print job with the user, so you can't completely automate this. Also, you'll be printing whatever the browser is displaying (it will not reliably print plug-ins or applets), so normally you are restricted to HTML and images. [The JavaScript source code for doing this is: <input type="button" onClick="window.print(0)" value="Print This Page"> 78) How do you do servlet aliasing with Apache and Tomcat? Servlet aliasing is a two part process with Apache and Tomcat. First, you must map the request in Apache to Tomcat with the ApJServMount directive, e.g., ApJServMount /myservlet /ROOT Second, you must map that url pattern to a servlet name and then to a servlet class in your web.xml configuration file. Here is a sample exerpt: servlet> <servlet-name>myservlet</servlet-name> <servlet-class>com.mypackage.MyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>myservlet</servlet-name> <url-pattern>/myservlet</url-pattern> </servlet-mapping>

79 ) I want my servlet page to redirect to a login page if the session has timed out. How can I know if my session has timed out? If the servlet engine does the time-out, following code should help you: //assume you have a HttpServletRequest request if(request.getSession(false)==null) { //no valid session (timeouted=invalid) //code to redirect to login page } 80) Can Tomcat be configured to interpret all, or selected, .html files within a given context as JSP? Or, do JSP files have to end with a .jsp extension? yes you can do that by modifying the web.xml file. You will have to invoke the org.apache.jasper.runtime.JspServlet for all the requests having extension .html. You can do that by changing the Servlet mapping code: <servlet-mapping> <servlet-name> jsp </servlet-name> <url>*.html</url> </servlet-mapping> And comment out the following block <mime-mapping> <extension> html </extension> <mime-type> text/html </mime-type> </mime-mapping> What is the difference between request attributes, session attributes, and ServletContext attributes? A ServletContext attribute is an object bound into a context through

ServletContext.setAttribute() method and which is available to ALL servlets (thus JSP) in that context, or to other contexts via the getContext() method. By definition a context attribute exists locally in the VM where they were defined. So, they're unavailable on distributed applications. Session attributes are bound to a session, as a mean to provide state to a set of related HTTP requests. Session attributes are available ONLY to those servlets which join the session. They're also unavailable to different JVMs in distributed scenarios. Objects can be notified when they're bound/unbound to the session implementing the HttpSessionBindingListener interface. Request attributes are bound to a specific request object, and they last as far as the request is resolved or while it keep dispatched from servlet to servlet. They're used more as comunication channel between Servlets via the RequestDispatcher Interface (since you can't add Parameters...) and by the container. Request attributes are very useful in web apps when you must provide setup information between information providers and the information presentation layer (a JSP) that is bound to a specific request and need not be available any longer, which usually happens with sessions without a rigorous control strategy. Thus we can say that context attributes are meant for infra-structure such as shared connection pools, session attributes to contextual information such as user identification, and request attributes are meant to specific request info such as query results. 82) Are singleton/static objects shared between servlet contexts? [Question continues: For example if I have two contexts on a single web server, and each context uses a login servlet and the login servlet connects to a DB. The DB connection is managed by a singleton object. Do both contexts have their own instance of the DB singleton or does one instance get shared between the two?] It depends on from where the class is loaded. The classes loaded from context's WEB-INF directory are not shared by other contexts, whereas classes loaded from CLASSPATH are shared. So if you have exactly the same DBConnection class in WEB-INF/classes directory of two different contexts, each context gets its own copy of the singleton (static) object. 83) When building web applications, what are some areas where synchronization problems arrise? In general, you will run into synchronization issues when you try to access any

shared resource. By shared resource, I mean anything which might be used by more than one request. Typical examples include: Connections to external servers, especially if you have any sort of pooling.

Anything which you include in a Http Session. (Your user could open many browser windows and make many simultaneous requests within the one session.) Log destinations, if you do your own logging from your servlets.

84) What is the difference between apache web server, java web server and tomcat server? Apache is an HTTP server written in C that can be compiled and run on many platforms. Java Web Server is an HTTP server from Sun written in Java that also supports Servlets and JSP. Tomcat is an open-source HTTP server from the Apache Foundation, written in Java, that supports Servlets and JSP. It can also be used as a "plug-in" to nativecode HTTP servers, such as Apache Web Server and IIS, to provide support for Servlets (while still serving normal HTTP requests from the primary, native-code web server). 85) How can you embed a JavaScript within servlets / JSP pages? You don't have to do anything special to include JavaScript in servlets or JSP pages. Just have the servlet/JSP page generate the necessary JavaScript code, just like you would include it in a raw HTML page. The key thing to remember is it won't run in the server. It will run back on the client when the browser loads the generate HTML, with the included JavaScript. 86) How can I make a POST request through response.sendRedirect() or response.setStatus() and response.setHeader() methods? You can't. It's a fundamental limitation of the HTTP protocol. You'll have to figure out some other way to pass the data, such as Use GET instead

Make the POST from your servlet, not from the client Store data in cookies instead of passing it via GET/POST

87) How do I pass a request object of one servlet as a request object to another servlet? Use a Request Dispatcher. 88) I call a servlet as the action in a form, from a jsp. How can I redirect the response from the servlet, back to the JSP? (RequestDispatcher.forward will not help in this case, as I do not know which resource has made the request. request.getRequestURI will return the uri as contained in the action tag of the form, which is not what is needed.) You'll have to pass the JSP's URI in to the servlet, and have the servlet call sendRedirect to go back to the JSP. For example: <FORM ACTION="/foo/myservlet"> <INPUT TYPE="HIDDEN" NAME="redirect" VALUE="/foo/thisjsp.jsp"> Shoe size: <INPUT NAME="shoesize"> <INPUT TYPE="SUBMIT"> </FORM> Then in the servlet... response.sendRedirect(request.getParameter("redirect")); 89) What is the ServletConfig object, and why is it useful? The ServletConfig object is an interface. It contains the methods getInitParameter getInitParameterNames getServletContext getServletName You can use the methods to determine the Servlet's initialization parameters,

the name of the servlets instance, and a reference to the Servlet Context the servlet is running in. getServletContext is the most valuable method, as it allows you to share information accross an application (context). 90) I have a global variable in a servlet class. What will happen to this global variable if two requests hit on the same time? What will happen is an unforeseeable event. The best way to establish a default occurrence (the servlet handles a request at a time) is to synchronize the access to the global variable or alternatively to create a servlet that implements the SingleThreadModel interface. 91) Suppose I have 2 servers, server1 and server2. How can I take data in a cookie from server1, and send it to server2? You'll have to create a (new) similar cookie on server 2. Have a ReadCookieServlet running on server1 that Reads the cookie, using request.getCookies()

Redirects to WriteCookieServlet running on server2, passing the cookie name, value and expiration date as request parameters, using response.sendRedirect(). Have a WriteCookieServlet running on server2 that Reads the cookie name, value and expiration date request parameters, using request.getParameter(). Creates a similar cookie, using response.addCookie().

92) How can I pass data from a servlet running in one context (webapp) to a servlet running in another context? There are three ways I can think of off the top of my head: 1. Store the information you want to share in a persistant format, such as in a file system or database. That way, any servlet that is running in a JVM that can "see" these resources can get to this information. 2. If persisting this information is not an option, you can bind this information to a context that is accessible to all servlet contexts, such as the application

server's context. This way, you can keep the data you want to share in memory. 3. Use the old fashion way of passing information to a servlet - HTTP. One servlet could foward a request to another servlet and include the data that needs to be shared as parameters in the request. 93) How can I write an "error page" -- that is, a servlet or JSP to report errors of other servlets? The Servlet 2.2 specification allows you to specify an error page (a servlet or a JSP) for different kinds of HTTP errors or ServletExceptions. You can specify this in deployment descriptor of the web application as: <error-page> <exception-type>FooException</exception-type> <location>/error.jsp</location> </error-page> where FooException is a subclass of ServletException. The web container invokes this servlet in case of errors, and you can access the following information from the request object of error servlet/JSP: error code, exception type, and a message. 94) What is the difference between ServletContext and ServletConfig? A ServletContext represents the context in a servlet container of a servlet instance operates. A servlet container can have several contexts (or web applications) at one time. Each servlet instance is running in one of these contexts. All servlets instances running in the same context are part of the same web application and, therefore, share common resources. A servlet accesses these shared resource (such as a RequestDispatcher and application properties) through the ServletContext object. This notion of a web application became very significant upon the Servlet 2.1 API, where you could deploy an entire web application in a WAR file. Notice that I always said "servlet instance", not servlet. That is because the same servlet can be used in several web applications at one time. In fact, this may be common if there is a generic controller servlet that can be configured at run time for a specific application. Then, you would have several instances of the same servlet running, each possibly having different configurations. This is where the ServletConfig comes in. This object defines how a servlet is to be configured is passed to a servlet in its init method. Most servlet containers

provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters. The container, in turn, passes these parameters to the servlet via the ServetConfig. 95) Under what circumstances will a servlet be reloaded? That depends on the Servlet container. Most of the Servlet containers reload the servlet only it detects the code change in the Servlet, not in the referenced classes. In Tomcat's server.xml deployment descriptor, if you have mentioned <Context path="/myApp" docBase="D:/myApp/webDev" crossContext="true" debug="0" reloadable="true" trusted="false" > </Context> The reloadable = true makes the magic. Every time the Servlet container detects that the Servlet code is changed, it will call the destroy on the currently loaded Servlet and reload the new code. But if the class that is referenced by the Servlet changes, then the Servlet will not get loaded. You will have to change the timestamp of the servlet or stopstart the server to have the new class in the container memory. 96) What is a Servlet Filter? A filter is basically a component that is invoked whenever a resource is invoked for which the filter is mapped. The resource can be something like a servlet, or a URL pattern. A filter normally works on the request, response, or header attributes, and does not itself send a response to the client. 97) I am using the RequestDispatcher's forward() method to redirect to a JSP. The problem is that the jsp's url is now relative to the servlet's url and all my

url's in the jsp such as <img src="pic.gif"> will be corrupt. How do I solve this problem? You can use absolute urls like: <BODY> <% String base = request.getContextPath(); %> <IMG src="<%=base%>/img/pic.gif"> </BODY> or write out a BASE tag like: <% String base = request.getContextPath(); %> <HEAD> <BASE HREF="<%=base%>"> </HEAD> <BODY> <IMG src="img/pic.gif"> </BODY> That should take care of the problem. 98) How can I return a readily available (static) HTML page to the user instead of generating it in the servlet? To solve your problem, you can either send a "Redirect" back to the client or use a RequestDispatcher and forward your request to another page: 1. Redirect: A redirection is made using the HttpServletResponse object: 2. 3. if(condition) { response.sendRedirect("page1.html");

4. 5. 6.

} else { response.sendRedirect("page2.html"); }

7. RequestDispatcher: A request dispatcher can be obtained through the ServletContext. It can be used to include another page or to forward to it. 8. 9. 10. 11. 12. 13. 14. } if(condition) { this.getServletContext() .getRequestDispatcher("page1.html").forward(); } else { this.getServletContext() .getRequestDispatcher("page2.html").forward();

Both solutions require, that the pages are available in you document root. If they are located somewhere else on your filesystem, you have to open the file manually and copy their content to the output writer. If your application server is set up in combination with a normal web server like Apache, you should use solution (1), because the the web server usually serves static files much faster than the application server.99) What is the difference between static variables and instance variables in a servlet? According to the Java Language definition, a static variable is shared among all instances of a class, where a non-static variable -- also called an instance variable -- is specific to a single instance of that class. According to the Servlet specification, a servlet that does not declare SingleThreadModel usually has one and only one instance, shared among all concurrent requests hitting that servlet. That means that, in servlets (and other multithreaded applications), an instance variable behaves very much like a static variable, since it is shared among all threads. You have to be very careful about synchronizing access to shared data. The big difference between instance variables and static variables comes when you have configured your servlet engine to instantiate two instances of the same servlet class, but with different init parameters. In this case, there will be two instances of the same servlet class, which means two sets of instance variables,

but only one set of static variables. Remember that you can store data in lots of different places in a servlet. To wit: Local variables - for loop iterators, result sets, and so forth

Request attributes - for data that must be passed to other servlets invoked with the RequestDispatcher only Session attributes - persists for all future requests from the current user

Instance variables - for data that persists for the life of the servlet, shared with all concurrent users Static variables - for data that persists for the life of the application, shared with all concurrent users -- including any other servlet instances that were instantiated with different init parameters Context attributes - for data that must persist for the life of the application, and be shared with all other servlets 100) How can I share data between two different web applications? Different servlets may share data within one application via ServletContext. If you have a compelling to put the servlets in different applications, you may wanna consider using EJBs. Java Servlet Interview Questions 1. What is an Exception? 2. An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error.

2. What is a Java Exception? A Java exception is an object that describes an exceptional condition i.e., an error condition that has occurred in a piece of code. When this type of condition arises, an object representing that exception is created and thrown in the method that caused the error by the Java Runtime. That method may choose to handle the exception itself, or

pass it on. Either way, at some point, the exception is caught and processed. 3. What are the different ways to generate and Exception? 4. There are two different ways to generate an Exception. 1. Exceptions can be generated by the Java run-time system. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. Exceptions can be manually generated by your code. Manually generated exceptions are typically used to report some error condition to the caller of a method. 5. Where does Exception stand in the Java tree hierarchy? 6. java.lang.Object 7. java.lang.Throwable 8. java.lang.Exception 9. java.lang.Error 5. Is it compulsory to use the finally block? It is always a good practice to use the finally block. The reason for using the finally block is, any unreleased resources can be released and the memory can be freed. For example while closing a connection object an exception has occurred. In finally block we can close that object. Coming to the question, you can omit the finally block when there is a catch block associated with that try block. A try block should have at least a catch or a finally block. 7. How are try, catch and finally block organized? 8. A try block should associate with at least a catch or a finally block. The sequence of try, catch and finally matters a lot. If you modify the order of these then the code wont compile. Adding to this there can be multiple catch blocks associated with a try block. The final concept is there should be a single try, multiple catch blocks and a single finally block in a try-catch-finally block. 7. What is a throw in an Exception block? throw is used to manually throw an exception (object) of type Throwable class or a subclass of Throwable. Simple types, such as int

or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or a subclass of Throwable.

throw new NullPointerException("thrownException"); 8. What is the use of throws keyword? If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the methods declaration. A throws clause lists the types of exceptions that a method might throw. type method-name(parameter-list) throws exception-list { // body of method }

Here, exception-list is a comma-separated list of the exceptions that a method can throw.

static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); 9. What are Checked Exceptions and Unchecked Exceptions?

The types of exceptions that need not be included in a methods throws list are called Unchecked Exceptions.

ArithmeticException ArrayIndexOutOfBoundsException ClassCastException IndexOutOfBoundsException IllegalStateException NullPointerException SecurityException

The types of exceptions that must be included in a methods throws list if that method can generate one of these exceptions and does not handle it itself are called Checked Exceptions.

ClassNotFoundException CloneNotSupportedException IllegalAccessException InstantiationException InterruptedException NoSuchFieldException NoSuchMethodException

10. What are Chained Exceptions?

The chained exception feature allows you to associate another exception with an exception. This second exception describes the cause of the first exception. Lets take a simple example. You are trying to read a number from the disk and using it to divide a number. Think the method throws an ArithmeticException because of an attempt to divide by zero (number we got). However, the problem was that an I/O error occurred, which caused the divisor to be set improperly (set to zero). Although the method must certainly throw an ArithmeticException, since that is the error that occurred, you might also want to let the calling code know that the underlying cause was an I/O error. This is the place where chained exceptions come in to picture.

Throwable getCause( ) Throwable initCause(Throwable causeExc)

When running on a Java Virtual Machine that is implemented in software on top of a host operating system, a Java program interacts with the host by invoking native methods. In Java, there are two kinds of methods: Java and native. A Java method is written in the Java language, compiled to bytecodes, and stored in class files. A native method is written in some other language, such as C, C++, or assembly, and compiled to the native machine code of a particular processor. Native methods are stored in a dynamically linked library whose exact form is platform specific. While Java methods are platform independent, native methods are not. When a running Java program calls a native method, the virtual machine loads the dynamic library that contains the native method and invokes it. As you can see in Figure 1-4, native methods are the connection between a Java program and an underlying host operating system. Method overloading 1. The two method having same name and different parameter types is called method overloading. 2. Method overloading does not consider return type. int f1(int x,float y){ return 0;

float f1(int x,float y){ return 0; } //Compiler error: StaticTest.java:35: f1(int,float) is already defined in StaticTest 3. Get inserted row id JDBC public void create(User user) throws SQLException { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet generatedKeys = null; try { connection = daoFactory.getConnection(); preparedStatement = connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS); preparedStatement.setValue(1, user.getName()); // Set more values here. int affectedRows = preparedStatement.executeUpdate(); if (affectedRows == 0) { throw new SQLException("Creating user failed, no rows affected."); } generatedKeys = preparedStatement.getGeneratedKeys(); if (generatedKeys.next()) { user.setId(generatedKeys.getLong(1)); } else { throw new SQLException("Creating user failed, no generated key obtained."); } } finally { close(connection, preparedStatement, generatedKeys); } }

1. What is the difference between Servlet & Jsp?. A JSP is typically oriented more towards displaying information, and a servlet is more oriented towards processing information. For example, a JSP might display a report, while a servlet would process a user submitted form. These uses are not exclusive, but they are optimized more for performing tasks in this manner. It is much easier to incorporate HTML coding into a JSP than a Servlet. It is also easier to write more complex Java code in a servlet.

JSP has Implicit objects and Servlets do not.

JSP specification provides more convenient web page authoring framework than Servlet and simplifies the creation and management of dynamic web content. JSP provides templatebased approach to content generation. JSP pages are textual documents containing HTML, XHTML, or XML markup with embedded Java code and custom JSP tags.

From the developers perspective Servlets are pure java programs with class and method definitions whereas a JSP page is much like a text document or web page. With servlets developer must write java code to output the entire markup, on the other hand a JSP page can be designed like a static web page. JSP separates static content from dynamic content and Java beans and/or custom JSP tags are used to generate dynamic portion of the web page. Servlets are well suited for handling client request and executing application logic whereas JSP pages are well suited as views. In jsp's the overall code is modulated so the developer who deesn't know about java can write jsp pages by simply knowing the additional tages and class names. One more important to be considered is servlet take less time to compile. Jsp is a tool to simplify the process and make the process automate.

2. What is the difference between Servlet & Jsp?. A JSP is typically oriented more towards displaying information, and a servlet is more oriented towards processing information. For example, a JSP might display a report, while a servlet would process a user submitted form. These uses are not exclusive, but they are optimized more for performing tasks in this manner. It is much easier to incorporate HTML coding into a JSP than a Servlet. It is also easier to write more complex Java code in a servlet.

JSP has Implicit objects and Servlets do not.

JSP specification provides more convenient web page authoring framework than Servlet and simplifies the creation and management of dynamic web content. JSP provides templatebased approach to content generation. JSP pages are textual documents containing HTML, XHTML, or XML markup with embedded Java code and custom JSP tags.

From the developers perspective Servlets are pure java programs with class and method definitions whereas a JSP page is much like a text document or web page. With servlets developer must write java code to output the entire markup, on the other hand a JSP page can be designed like a static web page. JSP separates static content from dynamic content and Java beans and/or custom JSP tags are used to generate dynamic portion of the web page. Servlets are well suited for handling client request and executing application logic whereas JSP pages are well suited as views. In jsp's the overall code is modulated so the developer who deesn't know about java can write jsp pages by simply knowing the additional tages and class names. One more important to be considered is servlet take less time to compile. Jsp is a tool to simplify the process and make the process automate.

Design Patterns: Creational Patterns: All of the Creational patterns deal with ways to create instances of objects. In many cases, the exact nature of the object that is created could vary with the needs of the program. Abstracting the creation process into a special "creator" class can make your program more flexible and general. The six Creational patterns follow: Simple Factory Pattern: Simple Factory pattern returns an instance of one of several possible classes depending on the data provided to it. Usually all classes that it returns have a common parent class and common methods, but each performs a task differently and is optimized for different kinds of data. Base class public class Namer { //base class extended by two child classes String last; String first; } Two sub classes public class FirstFirst extends Namer { } public class LastLast extends Namer { } Factory class public class NamerFactory { //Factory decides which class to return based on //presence of a comma public Namer getNamer(String entry) { //comma determines name order int i = entry.indexOf(","); if (i > 0) return new LastFirst(entry); else return new FirstFirst(entry); }

} Based on the data passed to the method it creates the instance and returns the instance. Factory Method This pattern does not actually have a decision point where one subclass is directly selected over another subclass. Instead, a program written using this pattern defines an abstract class that creates objects but lets each subclass decide which object to create. Simple factory method package simple.pizza; import pizza.Pizza; public class PizzaStore { Pizza orderPizza(String name){ Pizza pizza = createPizaa(name); pizza.bake(); pizza.cut(); pizza.box(); return pizza; } /** * Factory methods creates products depending on the data passed to it. * * @param name * @return */ Pizza createPizaa(String name){ if(name.equals("NY")){ return new Pizza("NY"); }else{ return new Pizza("Chicago"); } } } Factory Method

package pizza; public abstract class PizzaStore { Pizza orderPizza(){ Pizza pizza = createPizaa(); pizza.bake(); pizza.cut(); pizza.box(); return pizza; } /** * There is no decision making logic here. * This pattern does not actually have a decision point where one subclass is * directly selected over another subclass. Instead, a program written using * this pattern defines an abstract class that creates objects but lets each * subclass decide which object to create. * * @return */ abstract Pizza createPizaa(); } Two sub classes: package pizza; public class ChicagoPizzaStore extends PizzaStore { @Override Pizza createPizaa() { return new Pizza("Chicago"); } } package pizza; public class NYPizzaStore extends PizzaStore { @Override

Pizza createPizaa() { return new Pizza("NY"); } } Product class package pizza; public class Pizza { public Pizza(String name) { this.name = name; } String name; public void bake() { System.out.println("Bake for 25 minutes at 350"); } public void cut() { System.out.println("Cutting the pizza into diagonal slices"); } public void box() { System.out.println("Place pizza in official PizzaStore box"); } public String getName() { return name; } } Abstract Factory In the context of a factory method, there exists a class hierarchy composed of a set of subclasses with a common parent class. A factory method is used when a client object knows when to create an instance of the parent class type, but does not know (or should not know) exactly which class from among the set of subclasses (and possibly the parent class) should be instantiated. Besides the class selection criteria, a factory method also hides any special mechanism required to instantiate the selected class. The Abstract Factory pattern takes the same concept to the next level. In simple terms, an abstract factory is a class that provides an interface to produce a family of objects. In the Java programming language, it can be implemented either as an interface or as an abstract class. In the context of an abstract factory there exist: Suites or families of related, dependent classes. A group of concrete factory classes that implements the interface provided

by the abstract factory class. Each of these factories controls or provides access to a particular suite of related, dependent objects and implements the abstract factory interface in a manner that is specific to the family of classes it controls. ABSTRACT FACTORY VERSUS FACTORY METHOD Abstract Factory is used to create groups of related objects while hiding the actual concrete classes. This is useful for plugging in a different group of objects to alter the behavior of the system. For each group or family, a concrete factory is implemented that manages the creation of the objects and the interdependencies and consistency requirements between them. Each concrete factory implements the interface of the abstract factory. This situation often arises when designing a framework or a library, which needs to be kept extensible. One example is the JDBC (Java Database Connectivity) driver system, where each driver contains classes that implement the Connection, the Statement and the ResultSet interfaces. The set of classes that the Oracle JDBC driver contains are different from the set of classes that the DB2 JDBC driver contains and they must not be mixed up. This is where the role of the factory comes in: It knows which classes belong together and how to create objects in a consistent way. Factory Method is specifying a method for the creation of an object, thus allowing subclasses or implementing classes to define the concrete object. Abstract Factories are usually implemented using the Factory Method pattern. Another approach would be to use the Prototype pattern. Example public interface Car { public String getCarName(); public String getCarFeatures(); } Singleton Pattern It ensures that there is one and only one instance of a class and provides a global point of access to that instance. Any number of cases in programming in which you need to ensure that there can be one and only one instance of a class are possible. public class PrintSpooler { private static PrintSpooler spooler; private PrintSpooler() { }

//return only one spooler instance public static synchronized PrintSpooler getSpooler() { if (spooler == null) //if none created spooler = new PrintSpooler(); //create one return spooler; } public void print(String s) { System.out.println(s); } } Prototype Pattern Prototype pattern copies or clones an existing class rather than creating a new instance, when creating new instances is more expensive. Prototype pattern suggests to: Create one object upfront and designate it as a prototype object. Create other objects by simply making a copy of the prototype object and making required modifications. SHALLOW COPY VERSUS DEEP COPY When an object is cloned as a shallow copy: The original top-level object and all of its primitive members are duplicated. Any lower-level objects that the top-level object contains are not duplicated. Only references to these objects are copied. This results in both the original and the cloned object referring to the same copy of the lower-level object. In contrast, when an object is cloned as a deep copy: The original top-level object and all of its primitive members are duplicated. Any lower-level objects that the top-level object contains are also duplicated. In this case, both the original and the cloned object refer to two different lower-level objects. In general, a class must implement the Cloneable interface to indicate that a field-for-field copy of instances of that class is allowed by the Object.clone() method. When a class implements the Cloneable interface, it should override the Object.clone method with a public method. Note that when the clone method is invoked on an object that does not implement the Cloneable interface, the exception CloneNotSupportedException is thrown. public class AccountPrototypeFactory {

private UserAccount accountRep; private UserAccount supervisor; public AccountPrototypeFactory(UserAccount supervisorAccount, UserAccount arep) { accountRep = arep; supervisor = supervisorAccount; } public UserAccount getAccountRep() { return (UserAccount) accountRep.clone(); } public UserAccount getSupervisor() { return (UserAccount) supervisor.clone(); } } Builder Pattern This design may not be effective when the object being created is complex and the series of steps constituting the object creation process can be implemented in different ways producing different representations of the object. Because different implementations of the construction process are all kept within the object, the object can become bulky (construction bloat) and less modular. Subsequently, adding a new implementation or making changes to an existing implementation requires changes to the existing code. Using the Builder pattern, the process of constructing such an object can be designed more effectively. The Builder pattern suggests moving the construction logic out of the object class to a separate class referred to as a builder class. There can be more than one such builder class each with different implementation for the series of steps to construct the object. Each such builder implementation results in a different representation of the object. A client object can create an instance of a concrete builder and invoke the set of methods required to construct different parts of the final object. This approach requires every client object to be aware of the construction logic. Whenever the construction logic undergoes a change, all client objects need to be modified accordingly. The Builder pattern introduces another level of separation that addresses this problem. Instead of having client objects invoke different builder methods directly, the Builder pattern suggests using a dedicated object referred to as a Director, which is responsible for invoking

different builder methods required for the construction of the final object. Different client objects can make use of the Director object to create the required object. Once the object is constructed, the client object can directly request from the builder the fully constructed object. To facilitate this process, a new method getObject can be declared in the common Builder interface to be implemented by different concrete builders. The new design eliminates the need for a client object to deal with the methods constituting the object construction process and encapsulates the details of how the object is constructed from the client. Builder abstract class package searcher; import javax.swing.JPanel; public abstract class UIBuilder { protected JPanel searchUI; //add necessary UI controls and initialize them public abstract void addUIControls(); public abstract void initialize(); //common to all concrete builders. //returns the fully constructed search UI public JPanel getSearchUI() { return searchUI; } } Two builders package searcher; class EmployeeSearchUIBuilder extends UIBuilder { public void addUIControls() { } public void initialize() { }

} package searcher; public class CandidateSearchUIBuilder extends UIBuilder { public void addUIControls() { } public void initialize() { } } Client needs to know about director. Clients need not know about the steps followed by builders. Director talks with builder and knows the steps needed to construct the object. package searcher; public class UIDirector { private UIBuilder builder; public UIDirector(UIBuilder bldr) { builder = bldr; } public void build() { builder.addUIControls(); builder.initialize(); } } Client package searcher; import javax.swing.JPanel; public class Client { public static void main(String[] args) { //Create builder

EmployeeSearchUIBuilder builder = new EmployeeSearchUIBuilder(); //Clients knows about director. Not about how the builder constructs the object UIDirector director = new UIDirector(builder); //Director directs the builder to construct the object director.build(); //Get the required object it has been constructed vi.a Director JPanel saerchUI = builder.getSearchUI(); //Use search UI } } Structural Patterns A structural pattern describes how classes and objects can be combined to form larger structures. Class and object patterns differ in that a class pattern describes how inheritance can be used to provide more useful program interfaces. An object pattern describes how objects can be composed into larger structures using object composition or by including objects within other objects. Composite Pattern: Allows both individual objects and composite objects to be treated uniformly. Every component or object can be classified into one of the two categories Individual Components or Composite Components which are composed of individual components or other composite components. The Composite pattern is useful in designing a common interface for both individual and composite components so that client programs can view both the individual components and groups of components uniformly. In other words, the Composite design pattern allows a client object to treat both single components and collections of components in an identical manner. Programmers often develop systems in which a component may be an individual object or may represent a collection of objects. The Composite pattern is designed to accommodate both cases. You can use it to build part-whole hierarchies or to construct data representations of trees. In summary, a composite is a collection of objects, any one of which may be either a composite or a primitive

object. In tree nomenclature, some objects may be nodes with additional branches, and some may be leaves. Web Services Web services are based on the concept of service-oriented architecture (SOA). SOA is the latest evolution of distributed computing, which enables software components, including application functions, objects, and processes from different systems, to be exposed as services. 1. The service provider deploys its Web services by exposing the business applications obtained from different travel businesses like airlines, car-rental, hotel accommodation, credit card payment, and so forth. 2. The service provider registers its business services with descriptions using a public or private registry. The registry stores the information about the services exposed by the service provider. 3. The customer discovers the Web services using a search engine or by locating it directly from the registry and then invokes the Web services over the Internet using any platform or device. Web services are typically implemented based on open standards and technologies specifically leveraging XML. The XML-based standards and technologies, such as Simple Object Access Protocol (SOAP); Universal Description, Discovery, and Integration (UDDI); Web Services Definition Language (WSDL); and Electronic Business XML (ebXML), are commonly used as building blocks for Web services. Web services enable businesses to communicate, collaborate, and conduct business transactions using a lightweight infrastructure by adopting an XML-based data exchange format and industry standard delivery protocols. The basic characteristics of a Web services application model are as follows: Web services are based on XML messaging, which means that the data exchanged between the Web service provider and the user are defined in XML. Web services provide a cross-platform integration of business appli- cations over the Internet. To build Web services, developers can use any common programming language, such as Java, C, C++, Perl, Python, C#, and/or Visual Basic, and its existing application components.

Web services are not meant for handling presentations like HTML contextit is developed to generate XML for uniform accessibility through any software application, any platform, or device. Because Web services are based on loosely coupled application components, each component is exposed as a service with its unique functionality. Web services use industry-standard protocols like HTTP, and they can be easily accessible through corporate firewalls. Web services can be used by many types of clients. Web services vary in functionality from a simple request to a complex business transaction involving multiple resources. All platforms including J2EE, CORBA, and Microsoft .NET provide extensive support for creating and deploying Web services. Web services are dynamically located and invoked from public and private registries based on industry standards such as UDDI and ebXML. Why we use webservices Traditionally, Web applications enable interaction between an end user and a Web site, while Web services are service-oriented and enable application- to-application communication over the Internet and easy accessibility to heterogeneous applications and devices. The following are the major tech- nical reasons for choosing Web services over Web applications: Web services can be invoked through XML-based RPC mechanisms across firewalls. Web services provide a cross-platform, cross-language solution based on XML messaging. Web services facilitate ease of application integration using a light- weight infrastructure without affecting scalability. Web services enable interoperability among heterogeneous applications. These roles and relationships are defined as follows: Service provider. The service provider is responsible for developing and deploying the Web services. The provider also defines the services and publishes them with the service broker. Service broker. The service broker (also commonly referred to as a service registry) is responsible for service registration and discovery of the Web services. The broker lists the various service types, descriptions, and locations of the services that help the service requesters find and subscribe to the required services. Service requestor. The service requestor is responsible for the service invocation. The requestor locates the Web service using the

service broker, invokes the required services, and executes it from the service provider. Simple Object Access Protocol (SOAP) Simple Object Access Protocol, or SOAP, is a standard for a lightweight XML-based messaging protocol. It enables an exchange of information between two or more peers and enables them to communicate with each other in a decentralized, distributed application environment. Like XML, SOAP also is independent of the application object model, language, and running platforms or devices. In the core of the Web services model, SOAP is used as the messaging protocol for transport with binding on top of various Internet protocols such as HTTP, SMTP, FTP, and so on. SOAP uses XML as the message for- mat, and it uses a set of encoding rules for representing data as messages. Although SOAP is used as a messaging protocol in Web services, it also can operate on a request/response model by exposing the functionality using SOAP/RPC based on remote procedural calls. The Simple Object Access Protocol, or SOAP, plays the role of the messaging protocol for exchanging information between the service provider and the service requestor. It consists of the following: SOAP Envelope. It describes the message, identifying the contents and the envelopes processing information. SOAP Transport. It defines the bindings for the underlying transport protocols such as HTTP and SMTP. SOAP Encoding. It defines a set of encoding rules for mapping the instances of the application-specific data types to XML elements. SOAP RPC conventions. It defines the representation of the RPC requests and responses. These SOAP requests and responses are marshaled in a data type and passed in to a SOAP body.

POST /StockQuote HTTP/1.1 Host: www.acmeretailer.com ContentType: text/xml; charset=utf-8 Content-Length: 1000 SOAPAction: getBookPrice <SOAP-ENV:Envelope xmlns:SOAP-ENV=http://schemas.xmlsoap.org/soap/envelope/ xmlns:xsi=http://www.w3c.org/2001/XMLSchema-instance xmlns:xsd=http://www.w3c.org/2001/XMLSchema SOAPENV:encodingStyle =http://schemas.xmlsoap.org/soap/encoding/> <SOAP-ENV:Body> <m:getBookPrice xmlns:m=http://www.wiley.com/jws.book.priceList> <bookname xsi:type=xsd:string> Developing Java Web services</bookname>

</m:getBookPrice> /SOAP-ENV:Body> </SOAP-ENV:Envelope> Web Services Definition Language (WSDL) The Web Services Definition Language (WSDL) standard is an XML format for describing the network services and its access information. It defines a binding mechanism used to attach a protocol, data format, an abstract message, or set of endpoints defining the location of services. In the core of the Web services model, WSDL is used as the metadata language for defining Web services and describes how service providers and requesters communicate with one another. WSDL describes the Web services functionalities offered by the service provider, where the service is located, and how to access the service. Usually the service provider creates Web services by generating WSDL from its exposed business applications. A public/private registry is utilized for storing and publishing the WSDL- based information. The Web Services Description Language, or WDDL, is an XML schemabased specification for describing Web services as a collection of operations and data input/output parameters as messages. WSDL also defines the communication model with a binding mechanism to attach any transport protocol, data format, or structure to an abstract message, operation, or endpoint. A WSDL example that describes a Web service meant for obtaining a price of a book using a GetBookPrice operation. <?xml version=1.0?> <definitions name=BookPrice targetNamespace=http://www.wiley.com/bookprice.wsdl xmlns:tns=http://www.wiley.com/bookprice.wsdl xmlns:xsd=http://www.w3.org/2000/10/XMLSchema xmlns:xsd1=http://www.wiley.com/bookprice.xsd xmlns:soap=http://schemas.xmlsoap.org/wsdl/soap/ xmlns=http://schemas.xmlsoap.org/wsdl/> <message name=GetBookPriceInput> <part name=bookname element=xsd:string/> </message> <message name=GetBookPriceOutput> <part name=price type=xsd:float/> </message> <portType name=BookPricePortType> <operation name=GetBookPrice> <input message=tns:GetBookPriceInput/> <output message=tns:GetBookPriceOutput/> </operation> </portType> <binding name=BookPriceSoapBinding type=tns:BookPricePortType> <soap:binding style=rpc

transport=http://schemas.xmlsoap.org/soap/http/> <operation name=GetBookPrice> <soap:operation <input> soapAction=http://www.wiley.com/GetBookPrice/> <soap:body use=encoded namespace=http://www.wiley.com/bookprice encodingStyle=http://schemas.xmlsoap.org/soap/encoding//> </input> <output> <soap:body use=encoded namespace=http://www.wiley.com/bookprice encodingStyle=http://schemas.xmlsoap.org/soap/encoding//> </output> </operation>> </binding> <service name=WileyBookPriceService> <documentation>Wiley Book Price Service</documentation> <port name=BookPricePort binding=tns:BookPriceSoapBinding> <soap:address location=http://www.wiley.com/bookprice/> </port> </service> </definitions> Universal Description, Discovery, and Integration (UDDI) Universal Description, Discovery, and Integration, or UDDI, defines the standard interfaces and mechanisms for registries intended for publishing and storing descriptions of network services in terms of XML messages. It is similar to the yellow pages or a telephone directory where businesses list their products and services. Web services brokers use UDDI as a stan- dard for registering the Web service providers. By communicating with the UDDI registries, the service requestors locate services and then invoke them. In the core Web services model, UDDI provides the registry for Web services to function as a service broker enabling the service providers to populate the registry with service descriptions and service types and the service requestors to query the registry to find and locate the services. It enables Web applications to interact with a UDDI-based registry using SOAP messages. These registries can be either private services within an enterprise or a specific community, or they can be public registries to ser- vice the whole global business community of the Internet. Implementing Web Services The process of implementing Web services is quite similar to implementing any distributed application using CORBA or RMI. However, in Web services, all the components are bound dynamically

only at its runtime using standard protocols. The basic steps of implementing Web services are as follows: 1. The service provider creates the Web service typically as SOAPbased service interfaces for exposed business applications. The provider then deploys them in a service container or using a SOAP runtime environment, and then makes them available for invocation over a network. The service provider also describes the Web service as a WSDL-based service description, which defines the clients and the service container with a consistent way of identifying the service location, operations, and its communication model. 2. The service provider then registers the WSDL-based service description with a service broker, which is typically a UDDI registry. 3. The UDDI registry then stores the service description as binding templates and URLs to WSDLs located in the service provider environment. 4. The service requestor then locates the required services by querying the UDDI registry. The service requestor obtains the binding information and the URLs to identify the service provider. 5. Using the binding information, the service requestor then invokes the service provider and then retrieves the WSDL Service description for those registered services. Then, the service requestor creates a client proxy application and establishes communication with the service provider using SOAP. 6. Finally, the service requestor communicates with the service provider and exchanges data or messages by invoking the available services in the service container. SOAP message (as per SOAP version 1.1 with attachments) contains the following elements: Envelope Header (optional) Body Attachments (optional) Figure 4.1 represents the structure of a SOAP message with attachments. Typically, a SOAP message is represented by a SOAP envelope with zero or more attachments. The SOAP message envelope contains the header and body of the message, and the SOAP message attachments enable the mes- sage to contain data, which include XML and non-XML data (like text/binary files). In fact, a SOAP message package is constructed using the MIME Multipart/Related structure approaches to separate and identify the different parts of the message.

1. SOAP Message 1.1 SOAP Envelope 1.1.1 SOAP Header 1.1.2 SOAP Body 1.2 Attachments

Q) How to terminate servlet? I needed to terminate a Java Servlet recently if a startup condition failed - my initial approach was: System.exit(-1) However, this terminates the entire servlet-container (Jetty, Tomcat, Glassfish, etc) together with any other servlets that may be running within. What I wanted was to just terminate the servlet in question... As usual, the answer is relatively straightforward - you need to throw a servlet exception - at first glace this can be achieved using javax.servlet.ServletException. The servlet-container will catch this exception and gracefully terminate the servlet without affecting any other running servlets. However, there is also an UnavailableException (a subclass of ServletException) that is more appropriate for indicating misconfiguration, etc. Interestingly, this class can be used to indicate both 'permanent' and 'temporary' unavailability, with permanent unavailability meaning that the servlet cannot recover. If an permanent UnavailableException is thrown during the init() method, the servlet will never enter into service. Alternatively, if the exception is thrown during normal processing, the servlet-container

will remove that servlet instance and create a new one in its place. If a temporary UnavailableException is thrown the servlet-container will generate a HTTP 503 message, with the Retry-After header set to indicate to the client how long the service is likely to be unavailable for. Note that thowing a 'temporary' UnavailableException during the init() method prevents the servlet from entering into service - as with a 'premanent' exception above. In my case I wanted to indicate 'permanent' unavailability, which is based on the following snippet: import javax.servlet.* if (true) { throw new UnavailableException("Startup condition failed") } JNDI

What is LDAP? LDAP is an Internet standard protocol used by applications to access information in a directory. It runs directly over TCP, and can be used to access a standalone LDAP directory service or to access a directory service that is back-ended by X.500. It was created as a way to minimize the implementation requirements on directory clients, and to simplify and encourage the use of directories among applications. The LDAP directory service model is based on e .n t An r entry is a collection of attributes that describing it. Each attribute has a name, type and one or more values. For example, attributes describing a person might include person's name (common name, or cn), telephone number, and email address. The entry for P C might e t e r have the following h attributes:

8. LDAP is a protocol defining a directory service and access to that service. LDAP is based on a client-server model. LDAP servers provide the directory service, and LDAP clients use the directory service to access entries and attributes.

How LDAP organize directories In LDAP, directory entries are arranged in a hierarchical tree-like structure, starting at a root and then branching down into individual entries. At the top level of the hierarchy, entries represent larger organizations. Under these larger organization in the hierarchy might be entries for smaller organizations. The hierarchy might end with entries for individual people or resources. The following diagram shows a example of a hierarchy of entries in an LDAP directory service.

Each entry is uniquely identified by a distinguished name. A distinguished name consists of a name that uniquely identifies the entry at that hierarchical level (for example, pe t e r and john are different user IDs that identify different entries at the same level) and a path of names that trace the entry back to the root of the tree. For example, this might be the distinguished name for the pe t e entry: Here, u i represents d the user ID of the entry, ou represents the organizational unit in which the entry belongs, and o

represents the larger organization in which the entry belongs. The following diagram shows how distinguished names are used to identify entries uniquely in the directory hierarchy and also the attributes contained in one entry: How it work? LDAP is based on a client-server model. LDAP servers make information about people, organizations, and resources accessible to LDAP clients. The LDAP protocol defines operations that clients use to search and update the directory. An LDAP client can perform these operations, among others: 5. searching and retrieving entries from the directory 6. adding new entries in the directory 7. updating entries in the directory 8. deleting entries in the directory 9. renaming entries in the directory For example, to update an entry in the directory, an LDAP client submits the distinguished name of the entry with updated attribute information to the LDAP server. The LDAP server uses the distinguished name to find the entry and performs a modify operation to update the entry in the directory. To perform any of these LDAP operations, an LDAP client needs to establish a connection with an LDAP server. The LDAP protocol specifies the use of TCP/IP port number 389, although servers may run on other ports. The LDAP protocol also defines a simple method for authentication. LDAP servers can be set up to restrict permissions to the directory. Before an LDAP client can perform an operation on an LDAP server, the client must

authenticate itself to the server by supplying a distinguished name and password. If the user identified by the distinguished name does not have permission to perform the operation, the server does not execute the operation.

Hibernate
1. How to eliminate generated comments in hibernate tools

#go to eclipse\plugins\org.hibernate.eclipse_3.2.3.GA\lib\tools #open hibernate-tools.jar #find and edit /pojo/Pojo.ftl and /hbm/hibernatemapping.hbm.ftl #remove // Generated ${date} by Hibernate Tools ${version}

Das könnte Ihnen auch gefallen