+ All Categories
Home > Documents > Java Questions and Answers

Java Questions and Answers

Date post: 26-Nov-2014
Category:
Upload: rakeshshaw247
View: 140 times
Download: 5 times
Share this document with a friend
Popular Tags:
76
Home Question&Answers Revision Notes Resource s Interview Tips Interview Samples Java OOPS Java Fundamentals Exception Handling Multithreading Collections AWT/Swing Garbage Collection Applets Lang Package JDBC RMI J2EE Servlets JSP EJB CORE JAVA INTERVIEW QUESTIONS AND ANSWERS What is the most important feature of Java? Java is a platform independent language. What do you mean by platform independence? Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc). Are JVM's platform independent? JVM's are not platform independent. JVM's are platform specific run time implementation provided by the vendor. What is a JVM? JVM is Java Virtual Machine which is a run time environment for the compiled java class files. What is the difference between a JDK and a JVM? JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM. What is a pointer and does Java support pointers? Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn't support the usage of pointers. What is the base class of all classes? java.lang.Object Does Java support multiple inheritance? Java doesn't support multiple inheritance.
Transcript
Page 1: Java Questions and Answers

Home Question&Answers Revision Notes Resources Interview Tips Interview Samples

Java

OOPS

Java Fundamentals

Exception Handling

Multithreading

Collections

AWT/Swing

Garbage Collection

Applets

Lang Package

JDBC

RMI

J2EE

Servlets

JSP

EJB

JMS

CORE JAVA INTERVIEW QUESTIONS AND ANSWERS

What is the most important feature of Java? Java is a platform independent language.

What do you mean by platform independence? Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc).

Are JVM's platform independent?JVM's are not platform independent. JVM's are platform specific run time implementation provided by the vendor.

What is a JVM?JVM is Java Virtual Machine which is a run time environment for the compiled java class files.

What is the difference between a JDK and a JVM?JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM.

What is a pointer and does Java support pointers? Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn't support the usage of pointers.

What is the base class of all classes?java.lang.Object

Does Java support multiple inheritance?Java doesn't support multiple inheritance.

Is Java a pure object oriented language? Java uses primitive data types and hence is not a pure object oriented language.

Are arrays primitive data types? In Java, Arrays are objects.

What is difference between Path and Classpath? Path and Classpath are operating system level environment variales. Path is used define where the system can find the executables(.exe) files and classpath is used to specify the

Page 2: Java Questions and Answers

location .class files.

What are local variables? Local varaiables are those which are declared within a block of code like methods. Local variables should be initialised before accessing them.

What are instance variables? Instance variables are those which are defined at the class level. Instance variables need not be initialized before using them as they are automatically initialized to their default values.

How to define a constant variable in Java? The variable should be declared as static and final. So only one copy of the variable exists for all instances of the class and the value can't be changed also.static final int PI = 2.14; is an example for constant.

Should a main method be compulsorily declared in all java classes?No not required. main method should be defined only if the source class is a java application.

What is the return type of the main method?Main method doesn't return anything hence declared void.

Why is the main method declared static?main method is called by the JVM even before the instantiation of the class hence it is declared as static.

What is the arguement of main method?main method accepts an array of String object as arguement.

Can a main method be overloaded? Yes. You can have any number of main methods with different method signature and implementation in the class.

Can a main method be declared final? Yes. Any inheriting class will not be able to have it's own default main method.

Does the order of public and static declaration matter in main method?No it doesn't matter but void should always come before main().

Can a source file contain more than one Class declaration?Yes a single source file can contain any number of Class declarations but only one of the class can be declared as public.

What is a package?Package is a collection of related classes and interfaces. package declaration should be first statement in a java class.

Page 3: Java Questions and Answers

Which package is imported by default?java.lang package is imported by default even without a package declaration.

Can a class declared as private be accessed outside it's package?Not possible.

Can a class be declared as protected?A class can't be declared as protected. only methods can be declared as protected.

What is the access scope of a protected method?A protected method can be accessed by the classes within the same package or by the subclasses of the class in any package.

What is the purpose of declaring a variable as final? A final variable's value can't be changed. final variables should be initialized before using them.

What is the impact of declaring a method as final? A method declared as final can't be overridden. A sub-class can't have the same method signature with a different implementation.

I don't want my class to be inherited by any other class. What should i do? You should declared your class as final. But you can't define your class as final, if it is an abstract class. A class declared as final can't be extended by any other class.

Can you give few examples of final classes defined in Java API? java.lang.String,java.lang.Math are final classes.

How is final different from finally and finalize? final is a modifier which can be applied to a class or a method or a variable. final class can't be inherited, final method can't be overridden and final variable can't be changed.

finally is an exception handling code section which gets executed whether an exception is raised or not by the try block code segment.

finalize() is a method of Object class which will be executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.

Can a class be declared as static?No a class cannot be defined as static. Only a method,a variable or a block of code can be declared as static.

When will you define a method as static?When a method needs to be accessed even before the creation of the object of the class then we should declare the method as static.

Page 4: Java Questions and Answers

What are the restriction imposed on a static method or a static block of code?A static method should not refer to instance variables without creating an instance and cannot use "this" operator to refer the instance.

I want to print "Hello" even before main is executed. How will you acheive that?Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main method. And it will be executed only once.

What is the importance of static variable?static variables are class level variables where all objects of the class refer to the same variable. If one object changes the value then the change gets reflected in all the objects.

Can we declare a static variable inside a method? Static varaibles are class level variables and they can't be declared inside a method. If declared, the class will not compile.

What is an Abstract Class and what is it's purpose? A Class which doesn't provide complete implementation is defined as an abstract class. Abstract classes enforce abstraction.

Can a abstract class be declared final? Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.

What is use of a abstract variable? Variables can't be declared as abstract. only classes and methods can be declared as abstract.

Can you create an object of an abstract class? Not possible. Abstract classes can't be instantiated.

Can a abstract class be defined without any abstract methods? Yes it's possible. This is basically to avoid instance creation of the class.

Class C implements Interface I containing method m1 and m2 declarations. Class C has provided implementation for method m2. Can i create an object of Class C? No not possible. Class C should provide implementation for all the methods in the Interface I. Since Class C didn't provide implementation for m1 method, it has to be declared as abstract. Abstract classes can't be instantiated.

Can a method inside a Interface be declared as final? No not possible. Doing so will result in compilation error. public and abstract are the only applicable modifiers for method declaration in an interface.

Can an Interface implement another Interface? Intefaces doesn't provide implementation hence a interface cannot implement another

Page 5: Java Questions and Answers

interface.

Can an Interface extend another Interface? Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.

Can a Class extend more than one Class? Not possible. A Class can extend only one class but can implement any number of Interfaces.

Why is an Interface be able to extend more than one Interface but a Class can't extend more than one Class? Basically Java doesn't allow multiple inheritance, so a Class is restricted to extend only one Class. But an Interface is a pure abstraction model and doesn't have inheritance hierarchy like classes(do remember that the base class of all classes is Object). So an Interface is allowed to extend more than one Interface.

Can an Interface be final? Not possible. Doing so so will result in compilation error.

Can a class be defined inside an Interface? Yes it's possible.

Can an Interface be defined inside a class? Yes it's possible.

What is a Marker Interface? An Interface which doesn't have any declaration inside but still enforces a mechanism.

Which OO Concept is achieved by using overloading and overriding? Polymorphism.

If i only change the return type, does the method become overloaded? No it doesn't. There should be a change in method arguements for a method to be overloaded.

Why does Java not support operator overloading?Operator overloading makes the code very difficult to read and maintain. To maintain code simplicity, Java doesn't support operator overloading.

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

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

Page 6: Java Questions and Answers

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

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

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

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

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

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

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

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

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

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

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

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

What is casting? There are two types of casting, casting between primitive numeric types and casting between

Page 7: Java Questions and Answers

object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

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

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

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

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

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

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

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

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

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

Can an anonymous class be declared as implementing an interface and extending a class?

An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

Page 8: Java Questions and Answers

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

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

Why isn't there operator overloading? Because C++ has proven by example that operator overloading makes code almost impossible to maintain.

What does it mean that a method or field is "static"? Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work. out is a static field in the java.lang.System class.

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

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

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

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

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

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

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

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

Page 9: Java Questions and Answers

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

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

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

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

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

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

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

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

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

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

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

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

Page 10: Java Questions and Answers

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

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

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

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

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

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

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

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

How many static init can you have ?

Page 11: Java Questions and Answers

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

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

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

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

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

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

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

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

To what value is a variable of the String type automatically initialized? The default value of an String type is null. What is the difference between a field variable and a local variable? A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.

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

What does it mean that a class or member is final? A final class cannot be inherited. A final method cannot be overridden in a subclass. A final

Page 12: Java Questions and Answers

field cannot be changed after it's initialized, and it must include an initializer statement where it's declared.

What does it mean that a method or class is abstract? An abstract class cannot be instantiated. Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or it also should be declared abstract.

What is a transient variable? transient variable is a variable that may not be serialized.

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

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

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

Pls send in your feedback and contributions to [email protected]

© Copyright JGuide 2006, All Rights Reserved.

Home Question&Answers Revision Notes Resources Interview Tips Interview Samples

Java

OOPS

Java Fundamentals

Exception Handling

Multithreading

OOPS INTERVIEW QUESTIONS AND ANSWERS

1) What is meant by Object Oriented Programming?      OOP is a method of programming in which programs are organised as cooperative collections of objects. Each object is an instance of a class and each class belong to a hierarchy.

2) What is a Class?      Class is a template for a set of objects that share a common structure and a common behaviour.

Page 13: Java Questions and Answers

Collections

AWT/Swing

Garbage Collection

Applets

Lang Package

JDBC

RMI

J2EE

Servlets

JSP

EJB

JMS

3) What is an Object?      Object is an instance of a class. It has state,behaviour and identity. It is also called as an instance of a class.

4) What is an Instance?      An instance has state, behaviour and identity. The structure and behaviour of similar classes are defined in their common class. An instance is also called as an object.

5) What are the core OOP's concepts?      Abstraction, Encapsulation,Inheritance and Polymorphism are the core OOP's concepts.

6) What is meant by abstraction?      Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. Its the process of focussing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model.

7) What is meant by Encapsulation?      Encapsulation is the process of compartmentalising the elements of an abtraction that defines the structure and behaviour. Encapsulation helps to separate the contractual interface of an abstraction and implementation.

8) What is meant by Inheritance?      Inheritance is a relationship among classes, wherein one class shares the structure or behaviour defined in another class. This is called Single Inheritance. If a class shares the structure or behaviour from multiple classes, then it is called Multiple Inheritance. Inheritance defines "is-a" hierarchy among classes in which one subclass inherits from one or more generalised superclasses.

9) What is meant by Polymorphism?      Polymorphism literally means taking more than one form. Polymorphism is a characteristic of being able to assign a different behavior or value in a subclass, to something that was declared in a parent class.

10) What is an Abstract Class?      Abstract class is a class that has no instances. An abstract class is written with the expectation that its concrete subclasses will add to its structure and behaviour, typically by implementing its abstract operations. 11) What is an Interface?      Interface is an outside view of a class or object which emphaizes its abstraction while hiding its structure and secrets of its behaviour.

12) What is a base class?      Base class is the most generalised class in a class structure. Most applications have such root classes. In Java, Object is the base class for all classes.

Page 14: Java Questions and Answers

13) What is a subclass?      Subclass is a class that inherits from one or more classes

14) What is a superclass?      superclass is a class from which another class inherits.

15) What is a constructor?      Constructor is an operation that creates an object and/or initialises its state.

16) What is a destructor?      Destructor is an operation that frees the state of an object and/or destroys the object itself. In Java, there is no concept of destructors. Its taken care by the JVM.

17) What is meant by Binding?      Binding denotes association of a name with a class.

18) What is meant by static binding?      Static binding is a binding in which the class association is made during compile time. This is also called as Early binding.

19) What is meant by Dynamic binding?      Dynamic binding is a binding in which the class association is not made until the object is created at execution time. It is also called as Late binding.

20) Define Modularity?      Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules. 21) What is meant by Persistence?     Persistence is the property of an object by which its existence transcends space and time.

22) What is colloboration?      Colloboration is a process whereby several objects cooperate to provide some higher level behaviour.

23) In Java, How to make an object completely encapsulated?      All the instance variables should be declared as private and public getter and setter methods should be provided for accessing the instance variables.

24) How is polymorphism acheived in java?      Inheritance, Overloading and Overriding are used to acheive Polymorphism in java.

Pls send in your feedback and contributions to [email protected]

Page 15: Java Questions and Answers

© Copyright JGuide 2006, All Rights Reserved.

Home Question&Answers Revision Notes Resources Interview Tips Interview Samples

Java

OOPS

Java Fundamentals

Exception Handling

Multithreading

Collections

AWT/Swing

Garbage Collection

Applets

Lang Package

JDBC

RMI

J2EE

Servlets

JSP

EJB

JMS

JAVA EXCEPTION HANDLING INTERVIEW QUESTIONS AND ANSWERS

1) Which package contains exception handling related classes?     java.lang

2) What are the two types of Exceptions?      Checked Exceptions and Unchecked Exceptions.

3) What is the base class of all exceptions?      java.lang.Throwable

4) What is the difference between Exception and Error in java?      Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. Error defines exceptions that are not excepted to be caught by the user program. Example is Stack Overflow.

5) What is the difference between throw and throws?      throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions. throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. the statement would be as follows: public void doSomething() throws IOException,MyException{}

6) Differentiate between Checked Exceptions and Unchecked Exceptions?      Checked Exceptions are those exceptions which should be explicitly handled by the calling method. Unhandled checked exceptions results in compilation error.

Unchecked Exceptions are those which occur at runtime and need not be explicitly handled. RuntimeException and it's subclasses, Error and it's subclasses fall under unchecked exceptions.

7) What are User defined Exceptions?      Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class.

8) What is the importance of finally block in exception handling?      Finally block will be executed whether or not an exception is thrown. If an exception is

Page 16: Java Questions and Answers

thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally block will be executed. Finally is used to free up resources like database connections, IO handles, etc.

9) Can a catch block exist without a try block?      No. A catch block should always go with a try block.

10) Can a finally block exist with a try block but without a catch?      Yes. The following are the combinations try/catch or try/catch/finally or try/finally.

11) What will happen to the Exception object after exception handling?      Exception object will be garbage collected.

12) The subclass exception should precede the base class exception when used within the catch clause. True/False?      True.

13) Exceptions can be caught or rethrown to a calling method. True/False?      True.

14) The statements following the throw keyword in a program are not executed. True/False?      True.

15) How does finally block differ from finalize() method?      Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected.

16) What are the constraints imposed by overriding on exception handling?      An overriding method in a subclass may only throw exceptions declared in the parent class or children of the exceptions declared in the parent class.

Pls send in your feedback and contributions to [email protected]

© Copyright JGuide 2006, All Rights Reserved.

Home Question&Answers Revision Notes Resources Interview Tips Interview Samples

Page 17: Java Questions and Answers

Java

OOPS

Java Fundamentals

Exception Handling

Multithreading

Collections

AWT/Swing

Garbage Collection

Applets

Lang Package

JDBC

RMI

J2EE

Servlets

JSP

EJB

JMS

JAVA THREADS INTERVIEW QUESTIONS AND ANSWERS

1) What are the two types of multitasking ?      a. Process-based. b. Thread-based.

2) What is a Thread ?      A thread is a single sequential flow of control within a program.

3) What are the two ways to create a new thread?      a.Extend the Thread class and override the run() method. b.Implement the Runnable interface and implement the run() method.

4) If you have ABC class that must subclass XYZ class, which option will you use to create a thread?      I will make ABC implement the Runnable interface to create a new thread, because ABC class will not be able to extend both XYZ class and Thread class.

5) Which package contains Thread class and Runnable Interface?      java.lang package

6) What is the signature of the run() mehod in the Thread class?      public void run()

7) Which methods calls the run() method?      start() method.

8) Which interface does the Thread class implement?      Runnable interface

9) What are the states of a Thread ?      Ready,Running,Waiting and Dead.

10) Where does the support for threading lie?      The thread support lies in java.lang.Thread, java.lang.Object and JVM.

11) In which class would you find the methods sleep() and yield()?      Thread class

12) In which class would you find the methods notify(),notifyAll() and wait()?      Object class

13) What will notify() method do?      notify() method moves a thread out of the waiting pool to ready state, but there is no guaranty which thread will be moved out of the pool.

Page 18: Java Questions and Answers

14) Can you notify a particular thread?      No.

15) What is the difference between sleep() and yield()?      When a Thread calls the sleep() method, it will return to its waiting state. When a Thread calls the yield() method, it returns to the ready state.

16) What is a Daemon Thread?      Daemon is a low priority thread which runs in the backgrouund.

17) How to make a normal thread as daemon thread?      We should call setDaemon(true) method on the thread object to make a thread as daemon thread.

18) What is the difference between normal thread and daemon thread?      Normal threads do mainstream activity, whereas daemon threads are used low priority work. Hence daemon threads are also stopped when there are no normal threads.

19) Give one good example of a daemon thread?      Garbage Collector is a low priority daemon thread.

20) What does the start() method of Thread do?      The thread's start() method puts the thread in ready state and makes the thread eligible to run. start() method automatically calls the run () method.

21) What are the two ways that a code can be synchronised?      a. Method can be declared as synchronised. b. A block of code be sychronised.

22) Can you declare a static method as synchronized?      Yes, we can declare static method as synchronized. But the calling thread should acquire lock on the class that owns the method.

23) Can a thread execute another objects run() method?      A thread can execute it's own run() method or another objects run() method.

24) What is the default priority of a Thread?      NORM_PRIORITY

25) What is a deadlock?      A condition that occurs when two processes are waiting for each other to complete before proceeding. The result is that both processes wait endlessly.

26) What are all the methods used for Inter Thread communication and what is the class in which these methods are defined?      a. wait(),notify() & notifyall()

Page 19: Java Questions and Answers

b. Object class

27) What is the mechanisam defind in java for a code segment be used by only one Thread at a time?      Synchronisation

28) What is the procedure to own the moniter by many threads?      Its not possible. A monitor can be held by only one thread at a time.

29) What is the unit for 500 in the statement, obj.sleep(500);?      500 is the no of milliseconds and the data type is long.

30) What are the values of the following thread priority constants? MAX_PRIORITY,MIN_PRIORITY and NORMAL_PRIORITY      10,1,5

31) What is the default thread at the time of starting a java application?      main thread

32) The word synchronized can be used with only a method. True/ False?      False. A block of code can also be synchronised.

33) What is a Monitor?     A monitor is an object which contains some synchronized code in it.

34) What are all the methods defined in the Runnable Interface?      only run() method is defined the Runnable interface.

35) How can i start a dead thread?     A dead Thread cannot be started again.

36) When does a Thread die?     A Thread dies after completion of run() method.

37) What does the yield() method do?      The yield() method puts currently running thread in to ready state.

38) What exception does the wait() method throw?      The java.lang.Object class wait() method throws "InterruptedException".

39) What does notifyAll() method do?      notifyAll() method moves all waiting threads from the waiting pool to ready state.

40) What does wait() method do?      wait() method releases CPU, releases objects lock, the thread enters into pool of waiting threads.

Page 20: Java Questions and Answers

Pls send in your feedback and contributions to [email protected]

© Copyright JGuide 2006, All Rights Reserved.

Home Question&Answers Revision Notes Resources Interview Tips Interview Samples

Java

OOPS

Java Fundamentals

Exception Handling

Multithreading

Collections

AWT/Swing

Garbage Collection

Applets

Lang Package

JDBC

RMI

J2EE

Servlets

JSP

EJB

AWT & SWING INTERVIEW QUESTIONS AND ANSWERS

1) What is the difference between a Choice and a List? A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.

2) What interface is extended by AWT event listeners? All AWT event listeners extend the java.util.EventListener interface.

3) What is a layout manager? A layout manager is an object that is used to organize components in a container.

4) Which Component subclass is used for drawing and painting? Canvas

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

6) Which Swing methods are thread-safe? The only thread-safe methods are repaint(), revalidate(), and invalidate()

7) Which containers use a border Layout as their default layout? The Window, Frame and Dialog classes use a border layout as their default layout

8) What is the preferred size of a component? The preferred size of a component is the minimum component size that will allow the component to display normally

9) Which containers use a FlowLayout as their default layout?

Page 21: Java Questions and Answers

JMS The Panel and Applet classes use the FlowLayout as their default layout

10) What is the immediate superclass of the Applet class? Panel

11) Name three Component subclasses that support painting The Canvas, Frame, Panel, and Applet classes support painting

12) What is the immediate superclass of the Dialog class? Window

13) What is clipping? Clipping is the process of confining paint operations to a limited area or shape.

14) What is the difference between a MenuItem and a CheckboxMenuItem? The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.

15) What class is the top of the AWT event hierarchy? The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy

16) In which package are most of the AWT events that support the event-delegation model defined? Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package.

17) Which class is the immediate superclass of the MenuComponent class Object

18) Which containers may have a MenuBar? Frame

19) What is the relationship between the Canvas class and the Graphics class? A Canvas object provides access to a Graphics object via its paint() method.

20) How are the elements of a BorderLayout organized? The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container. 21) What is the difference between a Window and a Frame? The Frame class extends Window to define a main application window that can have a menu bar.

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

Page 22: Java Questions and Answers

23) How are the elements of a CardLayout organized? The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.

24) What is the relationship between clipping and repainting? When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.

25) What is the relationship between an event-listener interface and an event-adapter class? An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface.

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

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

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

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

30) How can the Checkbox class be used to create a radio button? By associating Checkbox objects with a CheckboxGroup

31) Difference between paint() and paintComponent()?The key point is that the paint() method invokes three methods in the following order: a) paintComponent() b) paintBorder() c) paintChildren()As a general rule, in Swing, you should be overriding the paintComponent method unless you know what you are doing. paintComponent() paints only component (panel) but paint() paints component and all its children.

32) What is the difference between paint(), repaint() and update() methods within an applet which contains images?

Page 23: Java Questions and Answers

paint : is only called when the applet is displayed for the first time, or when part of the applet window has to be redisplayed after it was hidden. repaint : is used to display the next image in a continuous loop by calling the update method. update : you should be aware that, if you do not implement it yourself, there is a standard update method that does the following : it will reset the applet window to the current background color (i.e. it will erase the current image) it will call paint to construct the new image

33) What is the name of the design pattern that Java uses for all Swing components?MVC(Model View Controller) pattern

34)Name few LayoutManagers in Java.Flow Layout ManagerGrid Layout ManagerBorder Layout ManagerBox Layout ManagerCard Layout ManagerGridBag Layout Manager

Pls send in your feedback and contributions to [email protected]

© Copyright JGuide 2006, All Rights Reserved.

Home Question&Answers Revision Notes Resources Interview Tips Interview Samples

Java

OOPS

Java Fundamentals

Exception Handling

Multithreading

Collections

AWT/Swing

JAVA GARBAGE COLLECTION INTERVIEW QUESTIONS AND ANSWERS

1) Explain Garbage collection in Java? In Java, Garbage Collection is automatic. Garbage Collector Thread runs as a low priority daemon thread freeing memory.

2) When does the Garbage Collection happen? When there is not enough memory. Or when the daemon GC thread gets a chance to run.

3) When is an Object eligible for Garbage collection? An Object is eligble for GC, when there are no references to the object.

4) What are two steps in Garbage Collection? 1. Detection of garbage collectible objects and marking them for garbage collection. 2. Freeing the memory of objects marked for GC.

Page 24: Java Questions and Answers

Garbage Collection

Applets

Lang Package

JDBC

RMI

J2EE

Servlets

JSP

EJB

JMS

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

6) Can GC be forced in Java? No. GC can't be forced.

7) What does System.gc() and Runtime.gc() methods do? These methods inform the JVM to run GC but this is only a request to the JVM but it is up to the JVM to run GC immediately or run it when it gets time.

8) When is the finalize() called? finalize() method is called by the GC just before releasing the object's memory. It is normally advised to release resources held by the object in finalize() method.

9) Can an object be resurrected after it is marked for garbage collection? Yes. It can be done in finalize() method of the object but it is not advisable to do so.

10) Will the finalize() method run on the resurrected object? No. finalize() method will run only once for an object. The resurrected object's will not be cleared till the JVM cease to exist.

11) GC is single threaded or multi threaded? Garbage Collection is multi threaded from JDK1.3 onwards.

12) What are the good programming practices for better memory management? a. We shouldn't declare unwanted variables and objects. b. We should avoid declaring variables or instantiating objects inside loops. c. When an object is not required, its reference should be nullified.d. We should minimize the usage of String object and SOP's.

13) When is the Exception object in the Exception block eligible for GC? Immediately after Exception block is executed.

14) When are the local variables eligible for GC? Immediately after method's execution is completed.

15) If an object reference is set to null, Will GC immediately free the memory held by that object? No. It will be garbage collected only in the next GC cycle.

Pls send in your feedback and contributions to [email protected]

Page 25: Java Questions and Answers

© Copyright JGuide 2006, All Rights Reserved.

Home Question&Answers Revision Notes Resources Interview Tips Interview Samples

Java

OOPS

Java Fundamentals

Exception Handling

Multithreading

Collections

AWT/Swing

Garbage Collection

Applets

Lang Package

JDBC

RMI

J2EE

Servlets

JSP

EJB

JMS

APPLETS INTERVIEW QUESTIONS AND ANSWERS

1) What is an Applet?      Applet is a java program which is included in a html page and executes in java enabled client browser. Applets are used for creating dynamic and interactive web applications.

2) Explain the life cycle of an Applet?      The following methods implement the life cycle of an Applet: init : To initialize the applet each time it's loaded (or reloaded). start : To start the applet's execution, such as when the applet's loaded or when the user revisits a page that contains the applet.stop : To stop the applet's execution, such as when the user leaves the applet's page or quits the browser. destroy : To perform a final cleanup in preparation for unloading.

3) What happens when an applet is loaded?      The following sequence happens when an applet is loaded: a) An instance of the applet's controlling class (an Applet subclass) is created. b) The applet initializes itself. c) The applet starts running.

4) How to make my class as an applet?      Your class must directly or indirectly extend either Applet or JApplet.

5) What is AppletContext?      AppletContext is an interface which provides information about applet's environment.

6) What is the difference between an Applet and a Java Application?      The following are the major differences between an Applet and an Application:a. Applets execute within a java enabled browser but an application is a standalone Java program outside of a browser. Both require a JVM (Java Virtual Machine). b. Application requires main() method to trigger execution but applets doesn't need a main() method. Applets use the init(),start(),stop() and destroy() methods for their life cycle. c. Applets typically use a fairly restrictive security policy. In a standalone application, however, the security policy is usually more relaxed.

7) What happens when a user leaves and returns to an applet's page?

Page 26: Java Questions and Answers

     When the user leaves the page, the browser stops the applet and when the user returns to the page, the browser starts the applet and normally most browser's dont initialise the applet again..

8) What are the restrictions imposed on an applet?      Due to Security reasons, the following restriction are imposed on applets: a. An applet cannot load libraries or define native methods. b. It cannot ordinarily read or write files on the host that's executing it. c. It cannot make network connections except to the host that it came from. d. It cannot start any program on the host that's executing it. e. It cannot read certain system properties.

9) Can a applet invoke public methods of another applet on the same page?      Yes. It's possible.

10) What are untrusted applets?      By default, all downloaded applets are untrusted. Untrusted Applets are those applets which cannot access or exceute local system files.

11) How to let a downloaded applet to read a file in the local system?      To allow any files in the directory /home/user1 to be read by applets loaded into the appletviewer, add the following line to your <user home directory>/.hotjava/properties file.    acl.read=/home/user1You can specify one file to be read:    acl.read=/home/user1/somedir/somefile

12) How to let a downloaded applet to write to a file in the local system?      You can allow applets to write to your /tmp directory by setting the acl.write property in your <user home directory>/.hotjava/properties file:    acl.write=/tmpYou can allow applets to write to a particular file by naming it explicitly:    acl.write=/home/user1/somedir/somefile

13) How do I hide system properties that applets are allowed to read?      To hide the name of the operating system that you are using, add the following line to your <user home directory>/.hotjava/properties file:    os.name=null

14) How can I allow applets to read system properties that they aren't allowed to read?      To allow applets to record your user name, add the following line to your <user home directory>/.hotjava/properties file:    user.name.applet=true

15) How can an applet open a network connection to a computer on the internet?      Applets are not allowed to open network connections to any computer,except for the host that provided the .class files. This is either the host where the html page came from, or the host

Page 27: Java Questions and Answers

specified in the codebase parameter in the applet tag, with codebase taking precendence.

16) Can an applet start another program on the client?      No, applets loaded over the net are not allowed to start programs on the client. That is, an applet that you visit can't start some rogue process on your PC. In UNIX terminology, applets are not allowed to exec or fork processes. In particular, this means that applets can't invoke some program to list the contents of your file system, and it means that applets can't invoke System.exit() in an attempt to kill your web browser. Applets are also not allowed to manipulate threads outside the applet's own thread group.

17) What is the difference between applets loaded over the net and applets loaded via the file system?      There are two different ways that applets are loaded by a Java system. The way an applet enters the system affects what it is allowed to do. If an applet is loaded over the net, then it is loaded by the applet classloader, and is subject to the restrictions enforced by the applet security manager. If an applet resides on the client's local disk, and in a directory that is on the client's CLASSPATH, then it is loaded by the file system loader. The most important differences are :a. applets loaded via the file system are allowed to read and write files b. applets loaded via the file system are allowed to load libraries on the clientc. applets loaded via the file system are allowed to exec processes d. applets loaded via the file system are allowed to exit the virtual machinee. applets loaded via the file system are not passed through the byte code verifier

18) What's the applet class loader, and what does it provide?      Applets loaded over the net are loaded by the applet class loader. For example, the appletviewer's applet class loader is implemented by the class sun.applet.AppletClassLoader.    The class loader enforces the Java name space hierarchy. The class loader guarantees that a unique namespace exists for classes that come from the local file system, and that a unique namespace exists for each network source. When a browser loads an applet over the net, that applet's classes are placed in a private namespace associated with the applet's origin. Thus, applets loaded from different network sources are partitioned from each other. Also, classes loaded by the class loader are passed through the verifier.The verifier checks that the class file conforms to the Java language specification - it doesn't assume that the class file was produced by a "friendly" or "trusted" compiler. On the contrary, it checks the class file for purposeful violations of the language type rules and name space restrictions. The verifier ensures that : a. There are no stack overflows or underflows. b. All register accesses and stores are valid. c. The parameters to all bytecode instructions are correct. d. There is no illegal data conversion. e. The verifier accomplishes that by doing a data-flow analysis of the bytecode instruction stream, along with checking the class file format, object signatures, and special analysis of finally clauses that are used for Java exception handling.

19) What's the applet security manager, and what does it provide?

Page 28: Java Questions and Answers

     The applet security manager is the Java mechanism for enforcing the applet restrictions described above. The appletviewer's applet security manager is implemented by sun.applet.AppletSecurity.    A browser may only have one security manager. The security manager is established at startup, and it cannot thereafter be replaced, overloaded, overridden, or extended. Applets cannot create or reference their own security manager.

20) If other languages are compiled to Java bytecodes, how does that affect the applet security model?      The verifier is independent of Sun's reference implementation of the Java compiler and the high-level specification of the Java language. It verifies bytecodes generated by other Java compilers. It also verifies bytecodes generated by compiling other languages into the bytecode format. Bytecodes imported over the net that pass the verifier can be trusted to run on the Java virtual machine. In order to pass the verifier, bytecodes have to conform to the strict typing, the object signatures, the class file format, and the predictability of the runtime stack that are all defined by the Java language implementation.

Home Question&Answers Revision Notes Resources Interview Tips Interview Samples

Java

OOPS

Java Fundamentals

Exception Handling

Multithreading

Collections

AWT/Swing

Garbage Collection

Applets

Lang Package

JAVA LANG PACKAGE INTERVIEW QUESTIONS AND ANSWERS

1) What is the base class of all classes? java.lang.Object

2) What do you think is the logic behind having a single base class for all classes?1. casting 2. Hierarchial and object oriented structure.

3) Why most of the Thread functionality is specified in Object Class? Basically for interthread communication.

4) What is the importance of == and equals() method with respect to String object? == is used to check whether the references are of the same object..equals() is used to check whether the contents of the objects are the same.But with respect to strings, object refernce with same content will refer to the same object.

String str1="Hello";String str2="Hello";

Page 29: Java Questions and Answers

JDBC

RMI

J2EE

Servlets

JSP

EJB

JMS

(str1==str2) and str1.equals(str2) both will be true.

If you take the same example with Stringbuffer, the results would be different.Stringbuffer str1="Hello";Stringbuffer str2="Hello";

str1.equals(str2) will be true. str1==str2 will be false.

5) Is String a Wrapper Class or not? No. String is not a Wrapper class.

6) How will you find length of a String object? Using length() method of String class.

7) How many objects are in the memory after the exection of following code segment? String str1 = "ABC";String str2 = "XYZ";String str1 = str1 + str2; There are 3 Objects.

8) What is the difference between an object and object reference? An object is an instance of a class. Object reference is a pointer to the object. There can be many refernces to the same object.

9) What will trim() method of String class do? trim() eliminate spaces from both the ends of a string.***

10) What is the use of java.lang.Class class? The java.lang.Class class is used to represent the classes and interfaces that are loaded by a java program. 11) What is the possible runtime exception thrown by substring() method?ArrayIndexOutOfBoundsException.

12) What is the difference between String and Stringbuffer? Object's of String class is immutable and object's of Stringbuffer class is mutable moreover stringbuffer is faster in concatenation.

13) What is the use of Math class? Math class provide methods for mathametical functions.

14) Can you instantiate Math class? No. It cannot be instantited. The class is final and its constructor is private. But all the methods are static, so we can use them without instantiating the Math class.

Page 30: Java Questions and Answers

15) What will Math.abs() do? It simply returns the absolute value of the value supplied to the method, i.e. gives you the same value. If you supply negative value it simply removes the sign.

16) What will Math.ceil() do? This method returns always double, which is not less than the supplied value. It returns next available whole number

17) What will Math.floor() do? This method returns always double, which is not greater than the supplied value.

18) What will Math.max() do? The max() method returns greater value out of the supplied values.

19) What will Math.min() do? The min() method returns smaller value out of the supplied values.

20) What will Math.random() do? The random() method returns random number between 0.0 and 1.0. It always returns double.

Pls send in your feedback and contributions to [email protected]

© Copyright JGuide 2006, All Rights Reserved.

Home Question&Answers Revision Notes Resources Interview Tips Interview Samples

Java

OOPS

Java Fundamentals

Exception Handling

JDBC INTERVIEW QUESTIONS AND ANSWERS

1) What is JDBC? JDBC is a layer of abstraction that allows users to choose between databases. JDBC allows you to write database applications in Java without having to concern yourself with the underlying details of a particular database.

2) How many types of JDBC Drivers are present and what are they?

Page 31: Java Questions and Answers

Multithreading

Collections

AWT/Swing

Garbage Collection

Applets

Lang Package

JDBC

RMI

J2EE

Servlets

JSP

EJB

JMS

There are 4 types of JDBC Drivers Type 1: JDBC-ODBC Bridge Driver Type 2: Native API Partly Java Driver Type 3: Network protocol Driver Type 4: JDBC Net pure Java Driver

3) Explain the role of Driver in JDBC? The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendors driver must provide implementations of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver.

4) Is java.sql.Driver a class or an Interface ? It's an interface.

5) Is java.sql.DriverManager a class or an Interface ? It's a class. This class provides the static getConnection method, through which the database connection is obtained.

6) Is java.sql.Connection a class or an Interface ? java.sql.Connection is an interface. The implmentation is provided by the vendor specific Driver.

7) Is java.sql.Statement a class or an Interface ? java.sql.Statement,java.sql.PreparedStatement and java.sql.CallableStatement are interfaces.

8) Which interface do PreparedStatement extend? java.sql.Statement

9) Which interface do CallableStatement extend? CallableStatement extends PreparedStatement.

10) What is the purpose Class.forName("") method? The Class.forName("") method is used to load the driver. 11) Do you mean that Class.forName("") method can only be used to load a driver? The Class.forName("") method can be used to load any class, not just the database vendor driver class.

12) Which statement throws ClassNotFoundException in SQL code block? and why? Class.forName("") method throws ClassNotFoundException. This exception is thrown when the JVM is not able to find the class in the classpath.

13) What exception does Class.forName() throw? ClassNotFoundException.

14) What is the return type of Class.forName() method ? java.lang.Class

15) Can an Interface be instantiated? If not, justify and explain the following line of code:

Page 32: Java Questions and Answers

Connection con = DriverManager.getConnection("dsd","sds","adsd"); An interface cannot be instantiated. But reference can be made to a interface. When a reference is made to interface, the refered object should have implemented all the abstract methods of the interface. In the above mentioned line, DriverManager.getConnection method returns Connection Object with implementation for all abstract methods.

16) What type of a method is getConnection()? static method.

17) What is the return type for getConnection() method?Connection object.

18) What is the return type for executeQuery() method? ResultSet

19) What is the return type for executeUpdate() method and what does the return type indicate? int. It indicates the no of records affected by the query.

20) What is the return type for execute() method and what does the return type indicate?

boolean. It indicates whether the query executed sucessfully or not. 21) is Resultset a Classor an interface? Resultset is an interface.

22) What is the advantage of PrepareStatement over Statement? PreparedStatements are precompiled and so performance is better. PreparedStatement objects can be reused with passing different values to the queries.

23) What is the use of CallableStatement? CallableStatement is used to execute Stored Procedures.

24) Name the method, which is used to prepare CallableStatement? CallableStament.prepareCall().

25) What do mean by Connection pooling? Opening and closing of database connections is a costly excercise. So a pool of database connections is obtained at start up by the application server and maintained in a pool. When there is a request for a connection from the application, the application server gives the connection from the pool and when closed by the application is returned back to the pool. Min and max size of the connection pool is configurable. This technique provides better handling of database connectivity.

Pls send in your feedback and contributions to [email protected]

Page 33: Java Questions and Answers

© Copyright JGuide 2006, All Rights Reserved.

Home Question&Answers Revision Notes Resources Interview Tips Interview Samples

Java Fundamentals

Exception Handling

Multithreading

Collections

AWT/Swing

Garbage Collection

Lang Package

SERVLETS INTERVIEW QUESTIONS AND ANSWERS

1) What is a Servlet? A Servlet is a server side java program which processes client requests and generates dynamic web content.

2) Explain the architechture of a Servlet? javax.servlet.Servlet interface is the core abstraction which has to be implemented by all servlets either directly or indirectly. Servlet run on a server side JVM ie the servlet container.Most servlets implement the interface by extending either javax.servlet.GenericServlet or javax.servlet.http.HTTPServlet.A single servlet object serves multiple requests using multithreading.

3) What is the difference between an Applet and a Servlet? An Applet is a client side java program that runs within a Web browser on the client machine whereas a servlet is a server side component which runs on the web server. An applet can use the user interface classes like AWT or Swing while the servlet does not have a user interface. Servlet waits for client's HTTP requests from a browser and generates a response that is displayed in the browser.

4) What is the difference between GenericServlet and HttpServlet? GenericServlet is a generalised and protocol independent servlet which defined in javax.servlet package. Servlets extending GenericServlet should override service() method. javax.servlet.http.HTTPServlet extends GenericServlet. HTTPServlet is http protocol specific ie it services only those requests thats coming through http.A subclass of HttpServlet must override at least one method of doGet(), doPost(),doPut(), doDelete(), init(), destroy() or getServletInfo().

5) Explain life cycle of a Servlet? On client's initial request, Servlet Engine loads the servlet and invokes the init() methods to initialize the servlet. The servlet object then handles subsequent client requests by invoking the service() method. The server removes the servlet by calling destry() method.

6) What is the difference between doGet() and doPost()? doGET Method : Using get method we can able to pass 2K data from HTML All data we are passing to Server will be displayed in URL (request string).

doPOST Method : In this method we does not have any size limitation. All data passed to server will be hidden, User cannot able to see this info on the browser.

Page 34: Java Questions and Answers

7) What is the difference between ServletConfig and ServletContext? ServletConfig is a servlet configuration object used by a servlet container to pass information to a servlet during initialization. All of its initialization parameters can only be set in deployment descriptor. The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized. ServletContext is an interface which defines a set of methods which the servlet uses to interact with its servlet container. ServletContext is common to all servlets within the same web application. Hence, servlets use ServletContext to share context information.

8) What is the difference between using getSession(true) and getSession(false) methods? getSession(true) method will check whether already a session is existing for the user. If a session is existing, it will return the same session object, Otherwise it will create a new session object and return taht object.

getSession(false) method will check for the existence of a session. If a session exists, then it will return the reference of that session object, if not, it will return null.

9) What is meant by a Web Application? A Web Application is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.

10) What is a Server Side Include ? Server Side Include is a Web page with an embedded servlet tag. When the Web page is accessed by a browser, the web server pre-processes the Web page by replacing the servlet tag in the web page with the hyper text generated by that servlet.

11) What is Servlet Chaining?Servlet Chaining is a method where the output of one servlet is piped into a second servlet. The output of the second servlet could be piped into a third servlet, and so on. The last servlet in the chain returns the output to the Web browser.

12) How do you find out what client machine is making a request to your servlet? The ServletRequest class has functions for finding out the IP address or host name of the client machine. getRemoteAddr() gets the IP address of the client machine and getRemoteHost()gets the host name of the client machine.

13) What is the structure of the HTTP response? The response can have 3 parts: 1) Status Code - describes the status of the response. For example, it could indicate that the request was successful, or that the request failed because the resource was not available. If your servlet does not return a status code, the success status code, HttpServletResponse.SC_OK, is returned by default.2) HTTP Headers - contains more information about the response. For example, the header could specify the method used to compress the response body. 3) Body - contents of the response. The body could contain HTML code, an image, etc.

14) What is a cookie? A cookie is a bit of information that the Web server sends to the browser which then saves the cookie to a file. The browser sends the cookie back to the same server in every request that it makes. Cookies are often used to keep track of

Page 35: Java Questions and Answers

sessions.

15) Which code line must be set before any of the lines that use the PrintWriter? setContentType() method must be set.

16) Which protocol will be used by browser and servlet to communicate ? HTTP

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

18) How can a servlet refresh automatically if some new data has entered the database? You can use a client-side Refresh or Server Push

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

20) What is HTTP Tunneling? HTTP tunneling is used to encapsulate other protocols within the HTTP or HTTPS protocols. Normally the intra-network of an organization is blocked by a firewall and the network is exposed to the outer world only through a specific web server port , that listens for only HTTP requests. To use any other protocol, that by passes the firewall, the protocol is embedded in HTTP and sent as HttpRequest. The masking of other protocol requests as http requests is HTTP Tunneling.

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

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

23) Is it true that servlet containers service each request by creating a new thread? If that is true, how does a container handle a sudden dramatic surge in incoming requests without significant performance degradation? The implementation depends on the Servlet engine. For each request generally, a new Thread is created. But to give performance boost, most containers, create and maintain a thread pool at the server startup time. To service a request,

Page 36: Java Questions and Answers

they simply borrow a thread from the pool and when they are done, return it to the pool. For this thread pool, upper bound and lower bound is maintained. Upper bound prevents the resource exhaustion problem associated with unlimited thread allocation. The lower bound can instruct the pool not to keep too many idle threads, freeing them if needed.

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

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

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

28) How to determine the client browser version? Another name for "browser" is "user agent." You can read the User-Agent header using request.getUserAgent() or request.getHeader("User-Agent")

Pls send in your feedback and contributions to [email protected]

© Copyright JGuide 2006, All Rights Reserved.

Home Question&Answers Revision Notes Resources Interview Tips Interview Samples

Page 37: Java Questions and Answers

Java

OOPS

Java Fundamentals

Exception Handling

Multithreading

Collections

AWT/Swing

Garbage Collection

Applets

Lang Package

JDBC

RMI

J2EE

Servlets

JSP

EJB

JMS

JSP INTERVIEW QUESTIONS AND ANSWERS

1) Briefly explain about Java Server Pages technology? JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically-generated content. The JSP specification, developed through an industry-wide initiative led by Sun Microsystems, defines the interaction between the server and the JSP page, and describes the format and syntax of the page.

2) What is a JSP Page? A JSP page is a text document that contains two types of text: static data, which can be expressed in any text-based format (such as HTML,WML,XML,etc), and JSP elements, which construct dynamic content.JSP is a technology that lets you mix static content with dynamically-generated content.

3) Why do I need JSP technology if I already have servlets? JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based applications. However, JSP technology was designed to simplify the process of creating pages by separating web presentation from web content. In many applications, the response sent to the client is a combination of template data and dynamically-generated data. In this situation, it is much easier to work with JSP pages than to do everything with servlets.

4) How are the JSP requests handled? The following sequence of events happens on arrival of jsp request:a. Browser requests a page with .jsp file extension in webserver.b. Webserver reads the request. c. Using jsp compiler,webserver converts the jsp into a servlet class that implement the javax.servletjsp.jsp page interface.the jsp file compiles only when the page is first requested or when the jsp file has been changed. d. The generated jsp page servlet class is invoked to handle the browser request.e. The response is sent to the client by the generated servlet.

5) What are the advantages of JSP? Ans : The following are the advantages of using JSP:a. JSP pages easily combine static templates, including HTML or XML fragments, with code that generates dynamic content. b. JSP pages are compiled dynamically into servlets when requested, so page authors can easily make updates to presentation code. JSP pages can also be precompiled if desired. c. JSP tags for invoking JavaBeans components manage these components completely, shielding the page author from the complexity of application logic. d. Developers can offer customized JSP tag libraries that page authors access using an XML-like syntax. e. Web authors can change and edit the fixed template portions of pages without affecting the application logic. Similarly, developers can make logic changes at the component level without editing the individual pages that use the logic.

6) How is a JSP page invoked and compiled?

Page 38: Java Questions and Answers

Pages built using JSP technology are typically implemented using a translation phase that is performed once, the first time the page is called. The page is compiled into a Java Servlet class and remains in server memory, so subsequent calls to the page have very fast response times.

7) What are Directives? Directives are instructions that are processed by the JSP engine when the page is compiled to a servlet. Directives are used to set page-level instructions, insert data from external files, and specify custom tag libraries. Directives are defined between < %@ and % >. < %@ page language=="java" imports=="java.util.*" % > < %@ include file=="banner.html" % >

8) What are the different types of directives available in JSP? Ans : The following are the different types of directives: a. include directive : used to include a file and merges the content of the file with the current pageb. page directive : used to define page specific attributes like scripting language, error page, buffer, thread safety, etcc. taglib : used to declare a custom tag library which is used in the page.

9) What are JSP actions? JSP actions are executed when a JSP page is requested. Action are inserted in the jsp page using XML syntax to control the behavior of the servlet engine. Using action, we can dynamically insert a file, reuse bean components, forward the user to another page, or generate HTML for the Java plugin. Some of the available actions are as follows: <jsp:include> - include a file at the time the page is requested.<jsp:useBean> - find or instantiate a JavaBean.<jsp:setProperty> - set the property of a JavaBean. <jsp:getProperty> - insert the property of a JavaBean into the output.<jsp:forward> - forward the requester to a new page. <jsp:plugin> - generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin.

10) What are Scriptlets? Scriptlets are blocks of programming language code (usually java) embedded within a JSP page. Scriptlet code is inserted into the servlet generated from the page. Scriptlet code is defined between <% and %>

11) What are Decalarations? Declarations are similar to variable declarations in Java.Variables are defined for subsequent use in expressions or scriptlets. Declarations are defined between <%! and %>. < %! int i=0; %>

12) How to declare instance or global variables in jsp? Instance variables should be declared inside the declaration part. The variables declared with JSP declaration element will be shared by all requests to the jsp page.

Page 39: Java Questions and Answers

< %@ page language=="java" contentType="text/html"% > < %! int i=0; %>

13) What are Expressions? Expressions are variables or constants that are inserted into the data returned by the web server. Expressions are defined between <% = and % > < %= scorer.getScore() %>

14) What is meant by implicit objects? And what are they?Ans : Implicit objects are those objects which are avaiable by default. These objects are instances of classesdefined by the JSP specification. These objects could be used within the jsp page without being declared.

The following are the implicit jsp objects:1. application 2. page 3. request 4. response 5. session 6. exception 7. out 8. config 9. pageContext

15) How do I use JavaBeans components (beans) from a JSP page? The JSP specification includes standard tags for bean use and manipulation. The <jsp:useBean> tag creates an instance of a specific JavaBean class. If the instance already exists, it is retrieved. Otherwise, a new instance of the bean is created. The <jsp:setProperty> and <jsp:getProperty> tags let you manipulate properties of a specific bean.

16) What is the difference between <jsp:include> and <%@include:>Both are used to insert files into a JSP page. <%@include:> is a directive which statically inserts the file at the time the JSP page is translated into a servlet.<jsp:include> is an action which dynamically inserts the file at the time the page is requested.

17) What is the difference between forward and sendRedirect?Both requestDispatcher.forward() and response.sendRedirect() is used to redirect to new url.

forward is an internal redirection of user request within the web container to a new URL without the knowledge of the user(browser). The request object and the http headers remain intact.

sendRedirect is normally an external redirection of user request outside the web container. sendRedirect sends response header back to the browser with the new URL. The browser send

Page 40: Java Questions and Answers

the request to the new URL with fresh http headers. sendRedirect is slower than forward because it involves extra server call.

18) Can I create XML pages using JSP technology? Yes, the JSP specification does support creation of XML documents. For simple XML generation, the XML tags may be included as static template portions of the JSP page. Dynamic generation of XML tags occurs through bean components or custom tags that generate XML output.

19) How is Java Server Pages different from Active Server Pages?JSP is a community driven specification whereas ASP is a similar proprietary technology from Microsoft. In JSP, the dynamic part is written in Java, not Visual Basic or other MS-specific language. JSP is portable to other operating systems and non-Microsoft Web servers whereas it is not possible with ASP

20) Can't Javascript be used to generate dynamic content rather than JSP? JavaScript can be used to generate dynamic content on the client browser. But it can handle only handles situations where the dynamic information is based on the client's environment. It will not able to harness server side information directly.

Pls send in your feedback and contributions to [email protected]

© Copyright JGuide 2006, All Rights Reserved.

Home Question&Answers Revision Notes Resources Interview Tips Interview Samples

Java

OOPS

Java Fundamentals

Exception Handling

Multithreading

Collections

EJB INTERVIEW QUESTIONS AND ANSWERS

1) What are Enterprise Java Beans?Enterprise Java Beans (EJB) is a specification which defines a component architecture for developing distributed systems. Applications written using the Enterprise JavaBeans architecture are resusable,scalable, transactional, and secure. Enterprise Java Bean's allow the developer to only focus on implementing the business logic of the application.

3) How many types of Enterprise beans are there and what are they?There are 3 types EJB's and they are: 1. Entity Bean's 2. Session Bean's 3. Message Driven Bean's(MDB's)

Page 41: Java Questions and Answers

AWT/Swing

Garbage Collection

Applets

Lang Package

JDBC

RMI

J2EE

Servlets

JSP

EJB

JMS

4) How many types of Entity beans are there and what are they?There are 2 types Entity bean's and they are: 1. Container Managed Persistence(CMP) Entity Bean's 2. Bean Managed Persistence(BMP) Entity Bean's

5) How many types of Session beans are there and what are they?There are 2 types Session bean's and they are: 1. Statefull Session Bean's 2. Stateless Session Bean's

6) How many types of MDB's are there and what are they?There are no different kinds of Message driven beans.

2) How is a enterprise bean different from a java bean?Both the enterprise bean and the java bean are designed to be highly reusable. But other than being reusable there is no similarity between them. Java bean is mostly a simple client-side component whereas enterprise bean is a complex server side component.

7) How many java files should a developer code to develop a session bean? 3 java files has to be provided by the developer. They are: 1) an Home Interface 2) a Remote Interface 3) And a Session Bean implementation class.

8) Explain the role of Home Interface. Home interface contains factory methods for locating, creating and removing instances of EJB's.

9) Explain the role of Remote Interface. Remote interface defines the business methods callable by a client. All methods defined in the remote interface must throw RemoteException.

10) What is the need for a separate Home interface and Remote Interface. Can't they be defined in one interface? EJB doesn't allow the client to directly communicate with an enterprise bean. The client has to use home and remote interfaces for any communication with the bean. The Home Interface is for communicating with the container for bean's life cycle operations like creating, locating,removing one or more beans. While the remote interface is used for remotely accessing the business methods.

11) What are callback methods? Callback methods are bean's methods, which are called by the container. These are called to notify the bean, of it's life cycle events.

12) How will you make a session bean as stateful or stateless?

Page 42: Java Questions and Answers

We have to specify the it in the deployment descriptor(ejb-jar.xml) using <session-type> tag.

13) What is meant by Activation? The process of transferring an enterprise bean from secondary storage to memory.

14) What is meant by Passivation? The process of transferring an enterprise bean from memory to secondary storage.

15) What is a re-entrant Entity Bean? An re-entrant Entity Bean is one that can handle multiple simultaneous, interleaved, or nested invocations which will not interfere with each other.

16) Why are ejbActivate() and ejbPassivate() included for stateless session bean even though they are never required as it is a nonconversational bean? To have a consistent interface, so that there is no different interface that you need to implement for Stateful Session Bean and Stateless Session Bean. Both Stateless and Stateful Session Bean implement javax.ejb.SessionBean and this would not be possible if stateless session bean is to remove ejbActivate and ejbPassivate from the interface.

17) What is an EJBContext?EJBContext is an object that allows an enterprise bean to invoke services provided by the container and to obtain the information about the caller of a client-invoked method.

18) Explain the role of EJB Container? EJB Container implements the EJB component contract of the J2EE architecture. It provides a runtime environment for enterprise beans that includes security, concurrency, life cycle management, transactions, deployment, naming, and other services. An EJB Container is provided by an EJB Server.

19) What are Entity Bean's?Entity Bean is an enterprise bean that represents persistent data maintained in a database. An entity bean can manage its own persistence or can delegate this function to its container. An entity bean is identified by a primary key. If the container in which an entity bean is hosted crashes, the entity bean, its primary key, and any remote references survive the crash.

20) What is a Primary Key? Primary Key is an object that uniquely identifies an entity bean within a home.

20) Can we specify primitive data type be as a primary key? Primitive data type cannot be directly used as primary key, it should be wrapped using a wrapper class.

21) What is a Deployment Descriptor? Deployment Descriptor is a XML file provided with each module and application that describes how they should be deployed. The deployment descriptor directs a deployment tool to deploy a module or application with specific container options and describes specific

Page 43: Java Questions and Answers

configuration requirements that a deployer must resolve.

22) What are the new features that were introduced in EJB version 2.0 specification? 1. New CMP Model. It is based on a new contract called the abstract persistence schema, that will allow to the container to handle the persistence automatically at runtime. 2. EJB Query Language. It is a sql-based language that will allow the new persistence schema to implement and execute finder methods. 3. Message Driven Beans. It is a new bean type, that is introduced to handle asynchronous messaging. 4. Local interfaces. Enabales beans in the same EJB Container to communicate directly. 5. ejbHome methods. Entity beans can declare ejbHome methods that perform operations related to the EJB component but that are not specific to a bean instance.

23) What are the difference's between a Local Interface and a Remote Interface?Local Interfaces are new mechanism introduced in EJB 2.0 specification which enables components in the same container to bypass RMI and call each other's methods directly. In general, direct local method calls are faster than remote method calls. The downside is a loss of flexibility: because bean and client must run in the same container, the location of the bean is not transparent to the client (as it is with remote interfaces). remote interfaces pass parameters by value, while local interfaces pass them by reference.

24) Can a bean be defined both as a Local and a Remote?Yes.

25) What are ejbHome methods or Home Business Methods?EJB 2.0 allows entity beans to declare ejbHome methods in the home interface. These methods perform operations that are not specific to a particular bean instance.

26) What is a transaction?A transaction is a sequence of operations that must all complete successfully, or leave system in the state it had been before the transaction started.

27) What do mean by ACID properties of a transaction?ACID is the acronym for the four properties guaranteed by transactions: atomicity, consistency, isolation, and durability.

28) Where will you mention whether the transaction is container managed or bean managed? Transaction management is specified in the deployment descriptor(ejb-jar.xml) using <transaction-type> tag.

29) What are container managed transactions?In an enterprise bean with container-managed transactions, the EJB container sets the boundaries of the transactions. You can use container-managed transactions with any type of enterprise bean: session, entity, or message-driven. Container-managed transactions simplify development because the enterprise bean code does not explicitly mark the transaction's

Page 44: Java Questions and Answers

boundaries. The code does not include statements that begin and end the transaction.

30) What methods are restricted being called inside a method decalred as container managed? We should not invoke any method that might interfere with the transaction boundaries set by the container. The list of restricted methods are as follows: 1) The commit, setAutoCommit, and rollback methods of java.sql.Connection 2) The getUserTransaction method of javax.ejb.EJBContext 3) Any method of javax.transaction.UserTransaction

31) What are bean managed transactions? For bean-managed transactions, the bean specifies transaction demarcations using methods in the javax.transaction.UserTransaction interface. Bean-managed transactions include any stateful or stateless session beans with a transaction-type set to Bean. Entity beans cannot use bean-managed transactions.

For stateless session beans, the entering and exiting transaction contexts must match. For stateful session beans, the entering and exiting transaction contexts may or may not match. If they do not match, EJB container maintains associations between the bean and the nonterminated transaction.

Session beans with bean-managed transactions cannot use the setRollbackOnly and getRollbackOnly methods of the javax.ejb.EJBContext interface.

32) What is the difference between container managed and bean managed transaction? In container-managed transaction, the transaction boundaries are defined by the container while in bean managed transaction, the transaction boundaries are defined by the bean. Entity Beans transactions are always container managed.

32) Why entity bean's transaction can't be managed by the bean? Entity bean's represent the data and responsible for the integrity of the data. Entity bean's doesn't represent business operations to manage transactions. So there is no requirement for an entity bean managing it's transaction.

33) How many types of transaction attributes are available in EJB and what are they?There 6 types of Transaction Atributes defined in EJB. They are as follows: 1. NotSupported : If the method is called within a transaction, this transaction is suspended during the time of the method execution. 2. Required : If the method is called within a transaction, the method is executed in the scope of this transaction; otherwise, a new transaction is started for the execution of the method and committed before the method result is sent to the caller. 3. RequiresNew : The method will always be executed within the scope of a new transaction. The new transaction is started for the execution of the method, and committed before the method result is sent to the caller. If the method is called within a transaction, this transaction is suspended before the new one is started and resumed when the new transaction has completed.

Page 45: Java Questions and Answers

4. Mandatory: The method should always be called within the scope of a transaction, else the container will throw the TransactionRequired exception. 5. Supports : The method is invoked within the caller transaction scope; if the caller does not have an associated transaction, the method is invoked without a transaction scope. 6. Never : The client is required to call the bean without any transaction context; if it is not the case, a java.rmi.RemoteException is thrown by the container.

34) How many types of Isolation Level's are available in EJB and what are they?

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

36) Are enterprise beans allowed to use Thread.sleep()? Enterprise beans are restricted from invoking multithreading thread functionality.

37) Can a bean be attached to more than one JNDI name? Yes. A same bean can be deployed multiple times in the same server with different JNDI names.

38) Can a client program directly access an Enterprise bean?No. EJB Clients never access an EJB directly. The container insulates the beans from direct access from client applications. Every time a bean is requested, created, or deleted, the container manages the whole process.

39) When is an application said to be distributed?An application is distributed when its components are running in separate runtime environments(JVM's), usually on different platforms connected via a network.Distributed applications are usually of 3 types. They are : 1. two tier (client and a server) 2.three tier (client and a middleware and a server)3. multitier (client and multiple middleware and multiple servers).

40) What is an EAR file? EAR is Enterprise Archive file. A archive file that contains a J2EE application.

41) What do mean by business method? A method of an enterprise bean that implements the business logic or rules of an application.

42) What is a finder method? A method defined in the home interface and invoked by a client to locate an entity bean.

Pls send in your feedback and contributions to [email protected]

Page 46: Java Questions and Answers

© Copyright JGuide 2006, All Rights Reserved.

Bookmark Us!

Home Question&Answers Revision Notes Resources Interview Tips Interview Samples

Java

OOPS

Java Fundamentals

Exception Handling

Multithreading

Collections

AWT/Swing

Garbage Collection

Applets

Lang Package

JDBC

RMI

J2EE

Servlets

JSP

EJB

JMS

RMI INTERVIEW QUESTIONS AND ANSWERS

1) What is RMI? Remote Method Invocation (RMI) is the process of activating a method on a remotely running object. RMI offers location transparency in the sense that it gives the feel that a method is executed on a locally running object.

2) What is the basic principle of RMI architecture? The RMI architecture is based on one important principle: the definition of behavior and the implementation of that behavior are separate concepts. RMI allows the code that defines the behavior and the code that implements the behavior to remain separate and to run on separate JVMs.

3) What are the layers of RMI Architecture? The RMI is built on three layers. a. Stub and Skeleton layerThis layer lies just beneath the view of the developer. This layer intercepts method calls made by the client to the interface reference variable and redirects these calls to a remote RMI service.

b. Remote Reference Layer. This layer understands how to interpret and manage references made from clients to the remote service objects. The connection is a one-to-one (unicast) link.

c. Transport layer This layer is based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies.

4) What is the role of Remote Interface in RMI? The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. Methods that are to be invoked remotely must be identified in Remote Interface. All Remote methods should throw RemoteException.

5) What is the role java.rmi.Naming Class? The Naming class provides methods for storing and obtaining references to remote objects in

Page 47: Java Questions and Answers

the remote object registry.

6) What is the default port used by RMI Registry? 1099

7) What is meant by binding in RMI? Binding is a process of associating or registering a name for a remote object that can be used at a later time to look up that remote object. A remote object can be associated with a name using the Naming class's bind or rebind methods.

8) What is the difference between using bind() and rebind() methods of Naming Class? bind method(String name) binds the specified name to a remote object while rebind(String name) method rebinds the specified name to a new remote object,any existing binding for the name is replaced.

9) When is AlreadyBoundException thrown and by which method? AlreadyBoundException is thrown by bind(String name) method when a remote object is already registered with the registry with the same name. Note: rebind method doesn't throw AlreadyBoundException because it replaces the existing binding with same name.

10) How to get all the registered objects in a rmiregistry? Using list method of Naming Class.

21) Can a class implementing a Remote interface have non remote methods? Yes. Those methods behave as normal java methods operating within the JVM.

22) What is the protocol used by RMI? JRMP(java remote method protocol)

23) What is the use of UnicastRemoteObject in RMI? The UnicastRemoteObject class provides support for point-to-point active object references using TCP streams. Objects that require remote behavior should extend UnicastRemoteObject.

24) What does the exportObject of UnicastRemoteObject do? Exports the remote object to make it available to receive incoming calls, using the particular supplied port. If port not specified receives calls from any anonymous port.

25) What is PortableRemoteObject.narrow() method and what is used for? Java RMI-IIOP provides a mechanism to narrow the the Object you have received from from your lookup, to the appropriate type. This is done through the javax.rmi.PortableRemoteObject class and, more specifically, using the narrow() method.

26) In a RMI Client Program, what are the excpetions which might have to handled? a. MalFormedURLException

Page 48: Java Questions and Answers

b. NotBoundException c. RemoteException

Pls send in your feedback and contributions to [email protected]

© Copyright JGuide 2006, All Rights Reserved.

Home Question&Answers Revision Notes Resources Interview Tips Interview Samples

Java

OOPS

Java Fundamentals

Exception Handling

Multithreading

Collections

AWT/Swing

Garbage Collection

Applets

Lang Package

JDBC

RMI

J2EE

Servlets

JSP

JMS INTERVIEW QUESTIONS AND ANSWERS

1) What is Messaging?Messaging is a method of communication between software components or applications

2) What is JMS?Java Message Service is a Java API that allows applications to create, send, receive, and read messages.

3) Is JMS a specification or a product?JMS is a specification.

4) What are the features of JMS?The following are the important features of JMS: a. Asynchronous Processing. b. Store and forwarding. c. Guaranteed delivery.d. Provides location transparency.e. Service based Architecture.

5) What are two messaging models or messaging domains?a. Point-to-Point Messaging domain.b. Publish/Subscribe Messaging domain

6) Explain Point-to-Point Messaging model.A point-to-point (PTP) product or application is built around the concept of message queues, senders, and receivers. Each message is addressed to a specific queue, and receiving clients extract messages from the queue(s) established to hold their messages. Queues retain all messages sent to them until the messages are consumed or until the messages expire.Point-to-Point Messaging has the following characteristics:

Page 49: Java Questions and Answers

EJB

JMS

a. Each Message has only one consumer. b. The receiver can fetch the message whether or not it was running when the client sent the message. c. The receiver acknowledges the successful processing of a message.

7) Explain Pub/Sub Messaging model.In a publish/subscribe (pub/sub) product or application, clients address messages to a topic. Publishers and subscribers are generally anonymous and may dynamically publish or subscribe to the content hierarchy. The system takes care of distributing the messages arriving from a topic's multiple publishers to its multiple subscribers. Topics retain messages only as long as it takes to distribute them to current subscribers.Pub/sub messaging has the following characteristics: a. Each message may have multiple consumers. b. Publishers and subscribers have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages.

8) What are the two types of Message Consumption?a. Synchronous Consumption :A subscriber or a receiver explicitly fetches the message from the destination by calling the receive method. The receive method can block until a message arrives or can time out if a message does not arrive within a specified time limit.

b. Asynchronous Consumption : A client can register a message listener with a consumer. A message listener is similar to an event listener. Whenever a message arrives at the destination, the JMS provider delivers the message by calling the listener's onMessage method, which acts on the contents of the message.

9) What is a connection factory?A connection factory is the object a client uses to create a connection with a provider. A connection factory encapsulates a set of connection configuration parameters that has been defined by an administrator.Each connection factory is an instance of either the QueueConnectionFactory or the TopicConnectionFactory interface.

10) What is a destination?A destination is the object a client uses to specify the target of messages it produces and the source of messages it consumes. In the PTP messaging domain, destinations are called queues and in the pub/sub messaging domain, destinations are called topics.

11) What is a message listener?A message listener is an object that acts as an asynchronous event handler for messages. This object implements the MessageListener interface, which contains one method, onMessage. In the onMessage method, you define the actions to be taken when a message arrives.

12) What is a message selector?Message selector filters the messages received by the consumer based on a criteria. Message

Page 50: Java Questions and Answers

selectors assign the work of filtering messages to the JMS provider rather than to the application. A message selector is a String that contains an expression. The syntax of the expression is based on a subset of the SQL92 conditional expression syntax. The message consumer then receives only messages whose headers and properties match the selector.

13) Can a message selector select messages on the basis of the content of the message body?No. The message selection is only based on message header and message properties.

14) What are the parts of a JMS message?A JMS message has three parts: a. header b. Properties (optional) c. body (optional)

15) What is a message header?A JMS message header contains a number of predefined fields that contain values that both clients and providers use to identify and to route messages.Each header field has associated setter and getter methods, which are documented in the description of the Message interface.

16) What are message properties?Message properties are additional user defined properties other than those that are defined in the header.

17) What is the root exception of JMS?JMSException is the root class for exceptions thrown by JMS API methods.

18) Name few subclasses of JMSException.a. MessageFormatException b. MessageEOFException c. InvalidClientIDException d. InvalidDestinationException e. InvalidSelectorException

19) What is a Message?A message is a package of business data that is sent from one application to another over the network. The message should be self-describing in that it should contain all the necessary context to allow the recipients to carry out their work independently.

20) How many types are there and What are they?There are 5 types of Messages. They are:a. TextMessage : A java.lang.String object (for example, the contents of an Extensible Markup Language file).b. MapMessage : A set of name/value pairs, with names as String objects and values as primitive types in the Java programming language. The entries can be accessed sequentially by enumerator or randomly by name. The order of the entries is undefined.

Page 51: Java Questions and Answers

c. BytesMessage : A stream of uninterpreted bytes. This message type is for literally encoding a body to match an existing message format.d. StreamMessage: A stream of primitive values in the Java programming language, filled and read sequentially. e. ObjectMessage: A Serializable object in the Java programming language.

21) What is a Topic?

22) What is a Queue?

23) What is a Message Driven Bean?

24) Do MDB's have component interfaces?

25) Do MDB's have JNDI?

26) Why do MDB's dont have component interfaces or JNDI?

27) Can be MDB be attached to different listeners in the same EAR?

27) What are the two parts of a message and explain them?A message basically has two parts : a header and payload. The header is comprised of special fields that are used to identify the message, declare attributes of the message, and provide information for routing. Payload is the type of application data the message contains.

28) What are the two types of delivery modes?

29)What is the method that would be called on arrival of a message and what is its argument?

Pls send in your feedback and contributions to [email protected]

© Copyright JGuide 2006, All Rights Reserved.


Recommended