Você está na página 1de 37

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 layer This 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 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. 11) What are the steps involved to make work a RMI program? Ans: a. Compile the source files. b. Generate the stubs using rmic. c. Start the rmiregistry. d. Start the RMIServer. e. Run the client program. 12) What is the role of stub in RMI? Ans: A stub for a remote object acts as a client's local representative or proxy for the remote object. The caller invokes a method on the local stub which is responsible for carrying out the method all on the remote object. When a stub's method is invoked, it does the following: a. initiates a connection with the remote JVM containing the remote object. b. marshals (writes and transmits) the parameters to the remote JVM. c. waits for the result of the method invocation d. unmarshals (reads) the return value or exception returned e. returns the value to the caller. 13) What is a skeleton in RMI? Ans: Skeleton was the server side component of stub. But skeleton has been deprecated from JDK1.2 onwards and its not required anymore. 14) What is DGC? And how does it work? Ans: DGC is Distributed Garbage Collection. RMI is uses DGC for automatic garbage collection. Since RMI involve remote object references across JVM's, garbage collection is a bit tricky. DGC uses a reference counting algorithm to provide automatic memory management for remote objects. 15) What is the purpose of using RMISecurityManager in RMI? Ans: RMISecurityManager provides a security manager for use by RMI applications that use downloaded code. RMI's class loader will not download any classes from remote locations if no security manager has been set. The following statment sets it: System.setSecurityManager(new RMISecurityManager()); 16) What is the difference between Pass By Value and Pass By Reference? Ans: When an Object is "Passed by Value", it means a copy of the object is passed. So even if changes are made to that Object/datatype, it doesn't affect the original value. When an Object is "Passed by Refernce", it means the object is not passed but a reference of the object is passed. so any changes made in the external method gets reflected in all places. 17) In RMI, Objects are passed by Value or Reference? Ans: In RMI, Objects are Passed by Value. 18) What are marker interfaces? Ans: A so-called marker interface is a Java interface which doesn't actually define any fields or methods. It is just used to "mark" Java classes which support a certain capability -- the class marks itself as implementing the interface. For example, the java.rmi.Remote and java.lang.Cloneable interface. 19) What do u mean by marshalling and demarshalling? Ans: When objects in memory are to be passed across a network to another host or persisted to storage, their in-memory representation must be converted to a suitable out-of-memory format. This process is called marshalling, and converting back to an in memory representation is called demarshalling. 20) What is meant by Serialisation and Deserialisation? Ans: Serialization is a way of "flattening", "pickling" or "freeze-drying" objects so that they can be stored on disk, and later read back and reconstituted, with all the links between objects intact. Deserialisation is the

reverse process of converting a object from flattened state to live object. 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 b. NotBoundException c. RemoteException

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. 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 crisplydefined 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. 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.

JAVA THREADS 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.

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() 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.

Main method and Java File Structure


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 the entry point for a Java application and main method is called by the JVM even before the instantiation of the class hence it is declared as static. static methods can be called even before the creation of objects. What is the argument of main method? main method accepts an array of String objects as argument. How to pass an argument to main method? You should pass the argument as a command line argument. Command line arguments are seprated by a space. The following is an example: java Hello Tom Jerry In the above command line Hello is the class, Tom is the first argument and Jerry is the second argument. What will happen if no argument is passed to the main method? If you dont access the argument, the main method will execute without any problem. If try to access the argument, NullPointerException will be thrown. 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. If a source file has 2 class declaration in it, on compilation how many class files will be created? 2 class files will be generated by the compiler. Can the first line of the source code be a comment? Yes. Comments can appear anywhere in the code. It is just a "skip this line" instruction to the conpiler. Can the source file name and the class name in the file be different? If the class in the source is not of public access, then the name can be anything but should confirm to identifier rules. Will the below statement result in compilation error or runtime error? System.out.println("Hi");;; The statement will compile and execute without any problem. Semicolon is just a statement terminator.

Java Language FeatureWhat are the most important features of Java?


Java is object oriented, platform independent,secure,robust,simple,etc Which one of them do you consider the best feature of Java? Platform independence. 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). What is byte code? Byte code is a set of instructions generated by the compiler. JVM executes the byte code. How does Java acheive platform independence? A Java source file on compilation produces an intermediary .class rather than a executable file. This .class file is interpreted by the JVM. Since JVM acts as an intermediary layer. What is a JVM? JVM is Java Virtual Machine which is a run time environment for the compiled java class files. Are JVM's platform independent? JVM's are not platform independent. JVM's are platform specific run time implementation provided by the vendor. A Windows JVM cannot be installed in Linux. Who provides the JVM? Any software vendor can provide a JVM but it should comply to the Java langauge specification. 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. How is an object reference different from a pointer? Both object reference and pointer point to the memory location of the object. You can manipulate pointers but not object references. Does Java support multiple inheritance? Java doesn't support multiple inheritance. Why Java doesn't support multiple inheritance? When a class inherits from more than class, it will lead to the diamond problem - say A is the super class of B and C & D is a subclass of both B and C. D inherits properties of A from two different inheritance paths ie via both B & C. This leads to ambiguity and related problems, so multiple inheritance is not allowed in Java. Is Java a pure object oriented language? Java is a pure object oriented language. Except for the primitives everything else are objects in Java. What is the 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 location .class files. 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.

Interfaces
What is an Interface? Interfaces say what a class must do but does not say how a class must do it. Interfaces are 100% abstract.

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 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. Can we define private and protected modifiers for variables in interfaces? No. Always all variables declared inside a interface are of public access. What modifiers are allowed for methods in an Interface? Only public and abstract modifiers are allowed for methods in interfaces. When can an object reference be cast to an interface reference? An object reference can be cast to an interface reference when the object implements the referenced interface.

Inner Classes
What are Inner Classes? Inner classes are classes which are defined inside another class. What are Nested Classes? Static Inner classes are called sometimes referred as nested classes because these classes can exist without any relationship with the containing class. What is the super class of all Inner Classes? Inner class is just a concept and can be applied to any class, hence there is no common super class for inner classes. What are the disadvantages of Inner classes? 1. Inner classes are not reusable hence defeats one of the fundamental feature of Java. 2. Highly confusing and difficult syntax which leads poor code maintainability. Name the different types of Inner Classes? The following are the different types of Inner classes: Regular Inner Class Method Local Inner Class Static Inner Class Anonymous Inner Class

What are Regular Inner Classes? A Regular inner class is declared inside the curly braces of another class outside any method or other code block. This is the simplest form of inner classes. Can a regular inner class access a private member of the enclosing class? Yes. Since inner classes are treated as a member of the outer class they can access private members of the outer class. How will you instantiate a regular inner class from outside the enclosing class? Outer out=new Outer(); Outer.Inner in=out.new Inner(); What is the impact of marking an Inner Class as abstract?

Explain how "this" works with respect to inner classes? Within the inner classes "this" refers to the current object but if an inner class needs to access an current outer class object, then it should outer class name along with this. The below is an example for the same. <Program needs to be given> What are Local Inner Classes or Method Local Inner Classes? A method-local inner class is defined within a method of the enclosing class. What are the constraints on Method Local Inner Classes? The following are the restrictions for Method Inner Classes:

Method Local Inner classes cannot acccess local variables but can access final variables. Only abstract and final modifiers can be applied to Method Local Inner classes Method Local Inner classes can be instantiated only within the method in which it is contained that too after the class definition.

What are Anonymous Inner Classes? Name the various forms of Anonymous Inner Classes. Anonymous Inner Classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface. The following are the different forms of inner classes: Anonymous subclass(i.e. extends a class) Anonymous implementer (i.e. implements an interface) Argument-Defined Anonymous Inner Classes

How many classes can an Anonymous Inner classes inherit from? One. How many Interfaces can an Anonymous Inner classes implement? One. Normal classes and other inner classes can implement more than one interface whereas anonymous inner classes can either implement a single interface or extend a single class. In which scenarios are Anonymous Inner classes frequently used? What are Static Inner Classes? Static Inner Classes are inner classes which marked with a static modifier. These classes need not have any relationship with the outer class. These can be instantiated even without the existence of the outer class object. Can you instantiate the static Inner Class without the existence of the outer class object? If Yes, Write a sample statement. Yes. It can be instantiated as follows by referencing the Outer class. Outer.Inner in = new Outer.Inner(); What are the constraints on Static Inner Classes? It cannot access non-static members of the outer class. It cannot use this reference to the outer class.

On many class files are produced for source file having one Outer class and one Inner class? Two class files will be produced as follows: Outer.class Outer$Inner.class

Identifiers, Keywords, Variables, Data Types and Arrays


What are keywords?
Keywords cannot be used as identifiers.

Which of the below are not keywords?


default Ans :

What are reserved keywords? And can you name few reserved keywords?
Few of the words are reserved as keywords for future usage. Compiler forces the developer not to use a reserved keyword. const and

What is the overhead of introducing a new keyword?


When a new keyword is used in a new version of the JDK, there is high chances that has been used by developers as identifiers. This make tougher for the code base to migrate to new version since it requires code change, recompilation,testing and release cycle.

Have you come across difficulties due to introduction of a new keyword?


Yes. enum keyword was used extensively as identifier in one of our project - we had to change the code in a lot of places to migrate it to newer v ersion.

What are identifiers?


Identifiers are names given to a variable, method, class and interface. Identifiers must conform to the following rules: a. The identifiers can contain a to z, A to Z,0 to 9,_ and $. b. Special characters other than _ and $ cannot be used in identifiers. c. Identifiers cannot start with numbers. d. keywords cannot be used as identifiers.

What is meant by naming conventions? And what are the naming conventions followed in Java?
Naming conventions are part of coding standards which are prescribed for better readability and maintenance. The following are simple conventions followed in Java: 1. Instance and local Variables should start with a lowercase and subsequent word should start with a capital letter. Examples: int quantity; double unitPrice; 2. Class level variables ie constants should be in capital letters and _ is used word seprator final static double PI = 3.14; final static int MAX_PRIORITY = 10; 3. Method names should start with small case and subsequent word should be capital letter. public double getAvailableBalance(String accountNo) throws InvalidAccountException{} 4. Classes and Interfaces should start with a capital letter and subsequent words should also be capital letters. public class HelloWorld{}

If you dont follow coding standards, will it result in compilation error?


No. These are standards. Each company or fot that matter each software unit might have its own coding standards. These are not enforced by the compiler.

How to make sure that all programmers are following the coding standards?
The best and simple way is to do peer reviews and code walkthroughs. You can use external plugins to your IDE (integrated development environment) to enforce during coding itself.

What are literals?


Literals are source code representation of primitive data types.

Name the eight data types which are available in Java?


boolean, byte, short, int, long, float, double and char.

Are primitive data types objects in Java?


Primitive data types are not objects.

What are all the number data types? And are they signed or unsigned?
Excpet boolean and char, others are number data types and they are all signed which means that they can hold both positive and negative values.

What are the possible values that a boolean data type can hold?
The boolean is the simplest data type which can hold true or false.

What are default values?


Values which are defaulted during object initialisation are called default values. Each data type has a default value.

What are the default values of primitive data types?


For boolean data type, it is false. For byte,short,int and long, it is 0. For float and double, it is 0.0. For char, the default value is '\u000'.

Are object references defaulted?


Yes. Object references are defaulted to null.

Are arrays defaulted?


If arrays is just declared but not initialised then the array reference will be defaulted to null. This is because arrays are objects in Java. int arr[]; // Here the arr reference is defaulted to null. If array values are not assigned, then will be defaulted to their respective default values. double priceRange[] = new double[3]; // Here all the elements in the array will be defaulted to 0.0 - the default value of double. String str[] = new String[3]; // Here all the elements will be defaulted to null - the default value for object references.

Can you explain keyword , identifier and literal with an example?


Consider the below statement: int i = 10; Here int is the keyword which has special meaning attached Java programming langauge ie whatever is declared is an integer value. i is the identifier or the variable name. 10 is the literal or the actual value.

What are the 3 ways to represent an integer value?


The following are the 3 different ways to represent an integer value: int i = 123 // this is the usual decimal representation. int i = 0123 // this is octal representation. Octal values start with a zero. int i = 0XCAAD // this is hexadecimal representation. Hexadecimal values start with 0X.

In how many ways a char value be represented?


Char value can be represented in 3 ways. They are as follows: char ch = 'A'; // represented using single quotes. char ch = '\u0041'; // represented using unicode representation. char ch = 41; // represented using integer value.

How is it possible to represent char using a integer value?


char is internally represented as a unsigned 16 bit integer value ie it will accept integer values from 0 to 65536.

Can char be used when an integer value is expected?


Yes. A fine example is switch statement will accept char value for multiway condition checking.

Can char be manipulated like integers?


Yes possible. The below is an example. char ch = 'A'; System.out.println(ch++); The above statement will print B. ++ is a numeral operand and since char is internally represented as integer, ++ operand can be applied on char value.

What is Unicode? How many languages are supported by the unicode? What should i have to do if i have to print my name in Hindi? How will the below literal value be internally represented?
float f = 21.22; Ans: It will be represented as a double value. Floating point literals are always double by default. If you want a float, you must append an F or f to the literal.

Give your observation on the below statement.


int i = 10/0; Ans: The statement will result in RuntimeException (DivideByZeroException). Integer values cannot be divided by zero.

Give your observation on the below statement.


double d = 10.12/0; Ans : This will compile and execute fine. The result will be ...

What is a Variable? What are the 3 types of variables?


There are 3 types of variables in Java. They are : 1. Local variables. 2. Instance variables.

3. Class variables.

What are Local variables?


Local varaiables are those which are declared within a block of code like methods, loops, exception blocks, etc. Local variables should be initialised before accessing them. Local variables are stored on the stack, hence they are sometimes called stack variables. They are also called as method variables or block variables.

When are local variables eligible for garbage collection?


As soon as the block is completed the variables are eligible for GC. Block could be a condition, a loop, a exception block or a method Consider the below class: public class Test { public static void main (String str[]){ String name = str[0]; for (int i=0; i<=10; i++){ System.out.println(name + i); } } } In the above the class, the variable i is eligible for garbage collection immediately after the completion of for loop. name string variable and str[] argument are eligible for GC after the completion of main method.

What are Instance variables?


Instance variables are those which are defined at the class level. As we know, object have identity and behaviour - the identity is provided by the instance variables. These are also called as object variables. Instance variables need not be initialized before using them. Instance variables will be initialized to their default values automatically when not initialized.

Are arrays primitive data types?


No. Arrays are not primitives - they are objects.

What are different ways to declare an array?


Object obj[]; // most frequently used form of array declaration. Object []obj; // nothing wrong with this. Object[] obj; // nothing wrong with this. int i[][]; // most frequently form multi-dimensional array int[] i[]; // nothing wrong with this. int[] i[],j; // nothing wrong with this. Important : i is double dimensional whereas j is single dimensional. ***** Need to be verified.

How many array dimensions does Java support? What are the 3 steps in defining arrays?
declaration,initialization and assignment int i[]; // array declaration. i[] = new int[2]; // array initialization. i[0] = 10; i[1] = 7; i[2] = 9; // element value assignment.

What is the simplest way to defining an primitive array?


The below statement merges declaration,initialization and assignment into a single step: int i [] = {10, 20, 30 40};

What is wrong with the below code segment?


int i[] = new int[5] System.out.println(i.length()) Ans: length is an instance variable of array object - here it is given a method.

What is wrong with the below code segment?


int i[5] = new int[] System.out.println(i.length) Ans: length of an array should be given when it is initialized. Here it is given during declaration. It will result in compilation error.

What will be the output of the below code segment?


int i[] = new int[5] System.out.println(i.length) Ans: It will print 6. Remember array indexes start with 0.

Is there any limit for a length of an array? What are the frequent RuntimeException's encountered because of improper coding?
ArrayIndexOutOfBoundsException and NullPointerException.

Constructors, Inheritance and Polymorphism


Explain Inheritance? Inheritance is a concept where the properties and behaviour of a class is reused in another class. The class which is being reused or inherited is called the super class or the parent class. The class which is inheriting is called the subclass or the child class of the inherited class. Does Java support multiple inheritance? No. Java Supports only single inheritance. Why Java doesnt support muliple inheritance? When a class inherits from more than class, it will lead to inheritance path amibiguity (this is normally calledthe diamond problem). Say A is the super class of B and C & D is a subclass of both B and C. D inherits properties of A from two different inheritance paths ie via both B & C. This leads to ambiguity and related problems, so multiple inheritance is not allowed in Java. Which keyword is used for inheriting from another class? extends keyword is used for inheritance.

Can a subclass be referenced for a super class object? No. If Vehicle is super class and Car is the subclass then the following reference would be wrong Car c = new Vehicle(); Can a parent class be referenced for a subclass object? Yes. The below is an example : Vehicle v = new Car(); Can an interface be referenced for any object? Yes. We can create a object reference for an interface. The object should have provided the implementation for the object. Runnable r = new Test(); Test class should have implemented the runnable interface and overridded the run method. What are constructors? Constructors are used to initialise an object. Constructors are invoked when the new operator on the class are called. What are the decalaration of a constructor? Constructor name should be the same as class name. Constructors doesnt return anything not even void. Does constructors throw exceptions? Yes. Like methods constructors can also throw exceptions. Can constructors be overloaded? Yes. Constructors can be overloaded. Is it compulsory to define a constructor for a class? No. If you dont define a constructor, the compiler will provide a default constructor. What is a default constructor? Default constructor is a no argument constructor which initialises the instance variables to their default values. This will be provided by the compiler at the time of compilation. Default constructor will be provided only when you dont have any constructor defined. Explain about this operator? this is used to refer the currently executing object and its state. this is also used for chaining constructors and methods. Explain about super operator? super is used to refer to the parent object of the currently running object. super is also to invoke super class methods and classes. What is the sequence of constructor invocation? Can a constructor be defined for an interface? Explain Polymorphism? What is Overloading? Explain Overriding? What is the difference between Overloading and Overriding?

When overriding a static method, can it be changed to non-static method? Can the overriding method change the exceptions in the throws clause of the method?

Access Modifiers
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. Can a final variable be declared inside a method? No. Local variables cannot be declared as final. What is the impact of declaring a method as final? A method declared as final can't be overridden. A sub-class doesn't have the independence to provide different implementation to the method. I don't want my class to be inherited by any other class. What should i do? You should declared your class as final. A class declared as final can't be inherited by any other class. When will you declare a class as final? When a class is independent and completely concrete in nature, then the class has to be marked as final. Can you give few examples of final classes defined in Java API? java.lang.String,java.lang.Math are final classes. 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 = 3.14; is an example for constant. 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. 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. What is the use of a static code block?

static code blocks could be used for one time initialisation activities. Cant you use the constructor for initialisation rather than static block? Constructors are used for object level initialisation whereas the static block are used for class level initialisation ie to initialise constants. Will the static block be executed for each object? No. It will be executed only once for each class ie at the time of loading a class. 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. It cannot use "this" or "super". A static method can acces only static variables or static methods. When overriding a static method, can it be converted to a non-static method? No. It should be static only. 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. What is the use of a abstract variable? Variables can't be declared as abstract. only classes and methods can be declared as abstract. Can a abstract class be declared final? Not possible. An abstract class without being inherited is of no use and a final class cannot be inherited. So if a abstract class is declared as final, it will result in compile time error. What is an abstract method? An abstract method is a method whose implementation is deferred to a subclass. Can a abstract class be defined without any abstract methods? Yes it's possible. This is basically to avoid instance creation of the class. What happens if a subclass has inherited a abstract class but has not provided implementation for all the abstract methods of the super class? Then the subclass also becomes abstract. This will be enforced by the compiler. What happens if a class has implemented an interface but has not provided implementation for a method in a interface? Its the same as the earlier answer. The class has to be marked as abstract. This will be enforced by the compiler. Can you create an object of an abstract class? Not possible. Abstract classes are not concrete and hence can't be instantiated. If you try instantiating, you will get compilation error.

Can i create a reference for a an abstract class? Yes. You can create a reference for an abstract class only when the object being has provided the implementation for the abstract class - it means that the object should be of a concrete subclass of the abstract class. This applies to interfaces also. Below is an example for the same: java.sql.Connection con = java.sql.DriverManager.getConnection(""); Can a class be marked as native? No. Only methods can be marked as native. What is the use of native methods? When a java method accesses native library written in someother programming language then the method has to be marked as native. What is the disadvantage of native methods? By using native methods, the java program loses platform independence - the accessed platform might be tightly coupled with a operating system hence java program also loses OS independence. What is the purpose of transient modifier? Only variables can be marked as transient. Variables marked as transient will not be persisted during object persistence. What is the purpose of volatile modifier? Only variables can be marked as volatile. Volatile variables might be modified asynchronously.

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. 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.

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 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.

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? 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. 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 eventlistener 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? 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 Manager Grid Layout Manager Border Layout Manager Box Layout Manager Card Layout Manager GridBag Layout Manager

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? 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/user1 You 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=/tmp You 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 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 client c. applets loaded via the file system are allowed to exec processes d. applets loaded via the file system are allowed to exit the virtual machine e. 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? 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.

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? 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: 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.