Saturday, July 3, 2010

Java Interview Questions

Interview Questions on Java
What if the main method is declared as private?


The program compiles properly but at runtime it will give “Main method not public.” message.
What is meant by pass by reference and pass by value in Java?
Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value.
If you’re overriding the method equals() of an object, which other method you might also consider?
hashCode()
What is Byte Code?
Or
What gives java it’s “write once and run anywhere” nature?
All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.
Expain the reason for each keyword of public static void main(String args[])?
public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.
static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.
void: main does not return anything so the return type must be void
The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line.


What are the differences between == and .equals() ?
Or
what is difference between == and equals
Or
Difference between == and equals method
Or
What would you use to compare two String variables - the operator == or the method equals()?
Or
How is it possible for two String objects with identical values not to be equal under the == operator?
The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.
== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.
public class EqualsTest {

public static void main(String[] args) {

String s1 = “abc”;
String s2 = s1;
String s5 = “abc”;
String s3 = new String(”abc”);
String s4 = new String(”abc”);
System.out.println(”== comparison : ” + (s1 == s5));
System.out.println(”== comparison : ” + (s1 == s2));
System.out.println(”Using equals method : ” + s1.equals(s2));
System.out.println(”== comparison : ” + s3 == s4);
System.out.println(”Using equals method : ” + s3.equals(s4));
}
}
Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true
What if the static modifier is removed from the signature of the main method?
Or
What if I do not provide the String array as the argument to the method?
Program compiles. But at runtime throws an error “NoSuchMethodError”.
Why oracle Type 4 driver is named as oracle thin driver?
Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.
What is the difference between final, finally and finalize? What do you understand by the java final keyword?
Or
What is final, finalize() and finally?
Or
What is finalize() method?
Or
What is the difference between final, finally and finalize?
Or
What does it mean that a class or member is final?
o final - declare constant
o finally - handles exception
o finalize - helps in garbage collection
Variables defined in an interface are implicitly final. A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.
What is the Java API?
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.
What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
What is the ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.
Why there are no global variables in Java?
Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:
• The global variables breaks the referential transparency
• Global variables creates collisions in namespace.
How to convert String to Number in java program?
The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = “1000″;
int id=Integer.valueOf(numString).intValue();
What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.
What is the difference between a while statement and a do statement?
A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) 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 loop body at least once.
What is the Locale class?
The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region.
Describe the principles of OOPS.
There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.
Explain the Inheritance principle.
Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places
What is implicit casting?
Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.
Example
int i = 1000;
long j = i; //Implicit casting
Is sizeof a keyword in java?
The sizeof operator is not a keyword.
What is a native method?
A native method is a method that is implemented in a language other than Java.
In System.out.println(), what is System, out and println?
System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.
What are Encapsulation, Inheritance and Polymorphism
Or
Explain the Polymorphism principle. Explain the different forms of Polymorphism.
Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation.
Polymorphism exists in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface
What is explicit casting?
Explicit casting in the process in which the complier are specifically informed to about transforming the object.
Example
long i = 700.20;
int j = (int) i; //Explicit casting
What is the Java Virtual Machine (JVM)?
The Java Virtual Machine is software that can be ported onto various hardware-based platforms
What do you understand by downcasting?
The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy
What are Java Access Specifiers?
Or
What is the difference between public, private, protected and default Access Specifiers?
Or
What are different types of access modifiers?
Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing
privileges to parts of a program such as functions and variables. These are:
• Public : accessible to all classes
• Protected : accessible to the classes within the same package and any subclasses.
• Private : accessible only to the class to which they belong
• Default : accessible to the class to which they belong and to subclasses within the same package
Which class is the superclass of every class?
Object.
Name primitive Java types.
The 8 primitive types are byte, char, short, int, long, float, double, and boolean.
What is the difference between static and non-static variables?
Or
What are class variables?
Or
What is static in java?
Or
What is a static method?
A static variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static variables i.e. there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class. These are declared outside a class and stored in static memory. Class variables are mostly used for constants. Static variables are always called by the class name. This variable is created when the program starts and gets destroyed when the programs stops. The scope of the class variable is same an instance variable. Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than any object of the class and doesn’t apply to an object or even require that any objects of the class have been instantiated.
Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can’t override a static method with a non-static method. In other words, you can’t change a static method into an instance method in a subclass.
Non-static variables take on unique values with each object instance.
What is the difference between the boolean & operator and the && operator?
If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. 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. If the first operand evaluates to false, the evaluation of the second operand is skipped.
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 if I write static public void instead of public static void?
Program compiles and runs properly.
What is the difference between declaring a variable and defining a variable?
In declaration we only mention the type of the variable and its name without initializing it. Defining means declaration + initialization. E.g. String s; is just a declaration while String s = new String (”bob”); Or String s = “bob”; are both definitions.
What type of parameter passing does Java support?
In Java the arguments (primitives and objects) are always passed by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.
Explain the Encapsulation principle.
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. Objects allow procedures to be encapsulated with their data to reduce potential interference. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.
What do you understand by a variable?
Variable is a named memory location that can be easily referred in the program. The variable is used to hold the data and it can be changed during the course of the execution of the program.
What do you understand by numeric promotion?
The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integral and floating-point operations may take place. In the numerical promotion process the 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 do you understand by casting in java language? What are the types of casting?
The process of converting one data type to another is called Casting. There are two types of casting in Java; these are implicit casting and explicit casting.
What is the first argument of the String array in main method?
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name. If we do not provide any arguments on the command line, then the String array of main method will be empty but not null.
How can one prove that the array is not null but empty?
Print array.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print array.length.
Can an application have multiple classes having main method?
Yes. While starting the application we mention the class name to be run. The JVM will look for the main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.
When is static variable loaded? Is it at compile time or runtime? When exactly a static block is loaded in Java?
Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks. Static block is not member of a class, they do not have a return statement and they cannot be called directly. Cannot contain this or super. They are primarily used to initialize static fields.
Can I have multiple main methods in the same class?
We can have multiple overloaded main methods but there can be only one main method with the following signature :
public static void main(String[] args) {}
No the program fails to compile. The compiler says that the main method is already defined in the class.
Explain working of Java Virtual Machine (JVM)?
JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte codes.
How can I swap two variables without using a third variable?
Add two variables and assign the value into First variable. Subtract the Second value with the result Value. and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable. Example:
int a=5,b=10;a=a+b; b=a-b; a=a-b;
An other approach to the same question
You use an XOR swap.
for example:

int a = 5; int b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;
What is data encapsulation?
Encapsulation may be used by creating ‘get’ and ’set’ methods in a class (JAVABEAN) which are used to access the fields of the object. Typically the fields are made private while the get and set methods are public. Encapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using javabeans in Struts, for instance). Wrapping of data and function into a single unit is called as data encapsulation. Encapsulation is nothing but wrapping up the data and associated methods into a single unit in such a way that data can be accessed with the help of associated methods. Encapsulation provides data security. It is nothing but data hiding.
What is reflection API? How are they implemented?
Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method.
Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK.
What is phantom memory?
Phantom memory is false memory. Memory that does not exist in reality.
Can a method be static and synchronized?
A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.
Class instance associated with the object. It is similar to saying:
synchronized(XYZ.class) {
}
What is difference between String and StringTokenizer?
A StringTokenizer is utility class used to break up string.
Example:
StringTokenizer st = new StringTokenizer(”Hello World”);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Output:
Hello
World
Java Package’s Interview Questions
Do I need to import java.lang package any time? Why?
Or
Which package is always imported by default?
No. It is by default loaded internally by the JVM. The java.lang package is always imported by default.
Can I import same package/class twice? Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM complains anything about it. And the JVM will internally load the class only once no matter how many times you import the same class.


Does importing a package imports the sub packages as well? E.g. Does importing com.bob.* also import com.bob.code.*?
No you will have to import the sub packages explicitly. Importing com.bob.* will import classes in the package bob only. It will not import any class in any of its sub package’s.
What is a Java package and how is it used?
Or
Explain the usage of Java packages.
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.
For example: The Java API is grouped into libraries of related classes and interfaces; these libraries are known as package.
Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.BOB compile?
Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying, cannot resolve symbol.

Java Classes and Objects Interview Questions
What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.
What is the difference between String and StringBuffer?
String objects are immutable whereas StringBuffer objects are not. StringBuffer unlike Strings support growable and modifiable strings.
Can a private method of a superclass be declared within a subclass?
Sure. A private field or method or inner class belongs to its declared class and hides from its subclasses.
There is no way for private stuff to have a runtime overloading or overriding (polymorphism) features.


What is the default value of an object reference declared as an instance variable?
null unless we define it explicitly.
What is the difference between a constructor and a method?
Or
How can a subclass call a method or a constructor defined in a superclass?
A constructor is a member function of a class that is used to create objects of that class, invoked using the new operator. It has the same name as the class and has no return type. They are only called once, whereas member functions can be called many times. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.
super.method(); is used to call a super class method from a sub class. To call a constructor of the super class, we use the super(); statement as the first line of the subclass’s constructor.
Can a top-level class be private or protected?
No. A top-level class cannot be private or protected. It can have either “public” or no modifier. If it does not have a modifier it is supposed to have a default access. If a top level class is declared as private/protected the compiler will complain that the “modifier private is not allowed here”.
Why Java does not support multiple inheritance?
Java does support multiple inheritance via interface implementation.
Where and how can you use a private constructor?
Private constructor can be used if you do not want any other class to instantiate the class. This concept is generally used in Singleton Design Pattern. The instantiation of such classes is done from a static public 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 is Method Overriding? What restrictions are placed on method overriding?
When a class defines a method using the same name, return type, and argument list as that of a method in its superclass, the method in the subclass is said to override the method present in the Superclass. When the method is invoked for an object of the
class, it is the new definition of the method that is called, and not the method definition from superclass.
Restrictions 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. Methods may be overridden to be more public, not more private.
• The overriding method may not throw any exceptions that may not be thrown by the overridden method.
What are the Object and Class classes used for? Which class should you use to obtain design information about an object?
Differentiate between a Class and an Object?
The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program. The Class class is used to obtain information about an object’s design. A Class is only a definition or prototype of real life object. Whereas an object is an instance or living representation of real life object. Every object belongs to a class and every class contains one or more related objects.
What is a singleton class?
Or
What is singleton pattern?
This design pattern is used by an application to ensure that at any time there is only one instance of a class created. You can achieve this by having the private constructor in the class and having a getter method which returns an object of the class and creates one for the first time if its null.
What is method overloading and method overriding?
Or
What is difference between overloading and overriding?
Method overloading: When 2 or more methods in a class have the same method names with different arguments, it is said to be method overloading. Overloading does not block inheritance from the superclass. Overloaded methods must have different method signatures
Method overriding : When a method in a class has the same method name with same arguments as that of the superclass,
it is said to be method overriding. Overriding blocks inheritance from the superclass. Overridden methods must have same signature.
Basically overloading and overriding are different aspects of polymorphism.
static/early binding polymorphism: overloading
dynamic/late binding polymorphism: overriding
If a class is declared without any access modifiers, where may the class be accessed?
A class that is declared without any access modifiers is said to have package or default 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 super classes.
Which java.util classes and interfaces support event handling?
The EventObject class and the EventListener interface support event processing
Can an object’s finalize() method be invoked while it is reachable?
An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects.
What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.
It returns the runtime information like memory availability.
* Runtime.freeMemory() –> Returns JVM Free Memory
* Runtime.maxMemory() –> Returns the maximum amount of memory that the JVM will attempt to use. It also helps to run the garbage collector
* Runtime.gc()
What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.
Can an unreachable object become reachable again?
An unreachable object may become reachable again. This can happen when the object’s finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable object.
What is a bean? Where can it be used?
A Bean is a reusable and self-contained software component. Beans created using java take advantage of all the security and platform independent features of java. Bean can be plugged into any software application. Bean is a simple class which has set and get methods. It could be used within a JSP using JSP tags to use them.
What is the functionality of instanceOf() ?
instanceOf opertaor is used to check whether an object can be cast to a specific type without throwing ClassCastException.
What would happen if you say this = null?
It will come up with Error Message
“The left-hand side of an assignment must be a variable”.
I want to create two instances of a class ,But when trying for creating third instance it should not allow me to create . What i have to do for making this?
One way of doing this would be:
public class test1
{
static int cntr=0;
test1()
{ cntr++;
if(cntr>2)
throw new NullPointerException();//u can define a new exception // for this
}
public static void main(String args[])
{
test1 t1= new test1();
System.out.println(”hello 1″);
test1 t2= new test1();
System.out.println(”hello 2″);
test1 t3= new test1();
}
}
What is the difference between an object and an instance?
An Object May not have a class definition. eg int a[] where a is an array.
An Instance should have a class definition.
eg MyClass my=new MyClass();
my is an instance.
What is heap in Java?
It is a memory area which stores all the objects created by an executing program.
Why default constructor of base class will be called first in java?
A subclass inherits all the methods and fields (eligible one) from the base class, so base class is constructed in the process of creation of subclass object (subclass is also an object of superclass). Hence before initializing the default value of sub class the super class should be initialized using the default constructor.
What are the other ways to create an object other than creating as new object?
We can create object in different ways;
1.new operator
2.class.forName: Classname obj = Class.forName(”Fully Qualified class Name”).newInstance();
3.newInstance
4.object.clone
What is the difference between instance, object, reference and a class?
Class: A class is a user defined data type with set of data members & member functions
Object: An Object is an instance of a class
Reference: A reference is just like a pointer pointing to an object
Instance: This represents the values of data members of a class at a particular time






Java Garbage Collection Interview Questions
Explain garbage collection?
Or
How you can force the garbage collection?
Or
What is the purpose of garbage collection in Java, and when is it used?
Or
What is Garbage Collection and how to call it explicitly?
Or
Explain Garbage collection mechanism in Java?
Garbage collection is one of the most important features of Java. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is an automatic process and can’t be forced. There is no guarantee that Garbage collection will start immediately upon request of System.gc().


What kind of thread is the Garbage collector thread?
It is a daemon thread.
Can an object’s finalize() method be invoked while it is reachable?
An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects.
Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.
What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup, before the object gets garbage collected. For example, closing an opened database Connection.
If an object is garbage collected, can it become reachable again?
Once an object is garbage collected, It can no longer become reachable again.


Java Object Serialization Interview Questions
How many methods in the Serializable interface? Which methods of Serializable interface should I implement?
There is no method in the Serializable interface. It’s an empty interface which does not contain any methods. The Serializable interface acts as a marker, telling the object serialization tools that the class is serializable. So we do not implement any methods.
What is the difference between Serializalble and Externalizable interface? How can you control over the serialization process i.e. how can you customize the seralization process?
When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class’s serialization process. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.




How to make a class or a bean serializable? How do I serialize an object to a file?
Or
What interface must an object implement before it can be written to a stream as an object?
An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
What happens to the object references included in the object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original object.
What is serialization?
The serialization is a kind of mechanism that makes a class or a bean persistent by having its properties or fields and state information saved and restored to and from storage. That is, it is a mechanism with which you can save the state of an object by converting it to a byte stream.
Common Usage of serialization.
Whenever an object is to be sent over the network or saved in a file, objects are serialized.
What happens to the static fields of a class during serialization?
There are three exceptions in which serialization doesn’t necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of any particular state.
2. Base class fields are only handled if the base class itself is serializable.
3. Transient fields.
What one should take care of while serializing the object?
One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.
What is a transient variable?
Or
Explain the usage of the keyword transient?
Or
What are Transient and Volatile Modifiers
A transient variable is a variable that may not be serialized i.e. the value of the variable can’t be written to the stream in a Serializable class. If you don’t want some field to be serialized, you can mark that field transient or static. In such a case when the class is retrieved from the ObjectStream the value of the variable is null.
Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.
What is Serialization and deserialization?
Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.
What is Externalizable?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.

Java Collections Interview Questions
What is HashMap and Map?
Map is Interface and Hashmap is class that implements this interface.
What is the significance of ListIterator?
Or
What is the difference b/w Iterator and ListIterator?
Iterator : Enables you to cycle through a collection in the forward direction only, for obtaining or removing elements
ListIterator : It extends Iterator, allow bidirectional traversal of list and the modification of elements
Difference between HashMap and HashTable? Can we make hashmap synchronized?


1. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.
Note on Some Important Terms
1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object “structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke “set” method since it doesn’t modify the collection “structurally”. However, if prior to calling “set”, the collection has been modified structurally, “IllegalArgumentException” will be thrown.
HashMap can be synchronized by
Map m = Collections.synchronizeMap(hashMap);
What is the difference between set and list?
A Set stores elements in an unordered way and does not contain duplicate elements, whereas a list stores elements in an ordered way but may contain duplicate elements.
Difference between Vector and ArrayList? What is the Vector class?
Vector is synchronized whereas ArrayList is not. The Vector class provides the capability to implement a growable array of objects. ArrayList and Vector class both implement the List interface. Both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. In vector the data is retrieved using the elementAt() method while in ArrayList, it is done using the get() method. ArrayList has no default size while vector has a default size of 10. when you want programs to run in multithreading environment then use concept of vector because it is synchronized. But ArrayList is not synchronized so, avoid use of it in a multithreading environment.
What is an Iterator interface? Is Iterator a Class or Interface? What is its use?
The Iterator is an interface, used to traverse through the elements of a Collection. It is not advisable to modify the collection itself while traversing an Iterator.
What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
What is the List interface?
The List interface provides support for ordered collections of objects.
How can we access elements of a collection?
We can access the elements of a collection using the following ways:
1.Every collection object has get(index) method to get the element of the object. This method will return Object.
2.Collection provide Enumeration or Iterator object so that we can get the objects of a collection one by one.
What is the Set interface?
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.
What’s the difference between a queue and a stack?
Stack is a data structure that is based on last-in-first-out rule (LIFO), while queues are based on First-in-first-out (FIFO) rule.
What is the Map interface?
The Map interface is used associate keys with values.
What is the Properties class?
The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.
Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
a. Vector
b. ArrayList
c. LinkedList
d. None of the above
ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.
How can we use hashset in collection interface?
This class implements the set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the Null element.
This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.
What are differences between Enumeration, ArrayList, Hashtable and Collections and Collection?
Enumeration: It is series of elements. It can be use to enumerate through the elements of a vector, keys or values of a hashtable. You can not remove elements from Enumeration.
ArrayList: It is re-sizable array implementation. Belongs to ‘List’ group in collection. It permits all elements, including null. It is not thread -safe.
Hashtable: It maps key to value. You can use non-null value for key or value. It is part of group Map in collection.
Collections: It implements Polymorphic algorithms which operate on collections.
Collection: It is the root interface in the collection hierarchy.
What is difference between array & arraylist?
An ArrayList is resizable, where as, an array is not. ArrayList is a part of the Collection Framework. We can store any type of objects, and we can deal with only objects. It is growable. Array is collection of similar data items. We can have array of primitives or objects. It is of fixed size. We can have multi dimensional arrays.
Array: can store primitive ArrayList: Stores object only
Array: fix size ArrayList: resizable
Array: can have multi dimensional
Array: lang ArrayList: Collection framework
Can you limit the initial capacity of vector in java?
Yes you can limit the initial capacity. We can construct an empty vector with specified initial capacity
public vector(int initialcapacity)
What method should the key class of Hashmap override?
The methods to override are equals() and hashCode().
What is the difference between Enumeration and Iterator?
The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn’t. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects.
So Enumeration is used when ever we want to make Collection objects as Read-only.


Java Exceptions Questions
Explain the user defined Exceptions?
User defined Exceptions are custom Exception classes defined by the user for specific purpose. A user defined exception can be created by simply sub-classing an Exception class or a subclass of an Exception class. This allows custom exceptions to be generated (using throw clause) and caught in the same way as normal exceptions.
Example:
class CustomException extends Exception {
}
What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Errors are generally irrecoverable conditions


What is the difference between exception and error?
Error’s are irrecoverable exceptions. Usually a program terminates when an error is encountered.
What is the difference between throw and throws keywords?
The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as an argument. The exception will be caught by an enclosing try-catch block or propagated further up the calling hierarchy. The throws keyword is a modifier of a method that denotes that an exception may be thrown by the method. An exception can be rethrown.
What class of exceptions are generated by the Java run-time system?
The Java runtime system generates Runtime Exceptions and Errors.
What is the base class for Error and Exception?
Throwable
What are Checked and Unchecked Exceptions?
A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the exception may be thrown. Checked exceptions must be caught at compile time. Example: IOException.
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn’t force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBoundsException. Errors are often irrecoverable conditions.
Does the code in finally block get executed if there is an exception and a return statement in a catch block?
Or
What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(0) statement is executed earlier or on system shut down earlier or the memory is used up earlier before the thread goes to finally block.
try{
//some statements
}
catch{
//statements when exception is caught
}
finally{
//statements executed whether exception occurs or not
}
Does the order of placing catch statements matter in the catch block?
Yes, it does. The FileNoFoundException is inherited from the IOException. So FileNoFoundException is caught before IOException. Exception’s subclasses have to be caught first before the General Exception

Java Swing Interview Questions
What is the difference between Swing and AWT components?
AWT components are heavy-weight, whereas Swing components are lightweight. Hence Swing works faster than AWT. Heavy weight components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component. Pluggable look and feel possible using java Swing. Also, we can switch from one look and feel to another at runtime in swing which is not possible in AWT.
Name the containers which use Border Layout as their default layout?
window, Frame and Dialog classes.
Name Container classes.


Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane
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.
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.
Which package has light weight components?
javax.Swing package contains light weight components. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.
What are peerless components?
The peerless components are called light weight components.
What is a Container in a GUI?
A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determine where components should go as a function of the size of the container.
How are the elements of a GridBagLayout organized?
Or
What is a layout manager and what are different types of layout managers available in java Swing?
Or
How are the elements of different layouts organized?
A layout manager is an object that is used to organize components in a container. The different layouts available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout.
FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container.
CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards.
GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid.
GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements may be different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.
What advantage do Java’s layout managers provide over traditional windowing systems?
Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.
What method is used to specify a container’s layout?
The setLayout() method is used to specify a container’s layout. For example, setLayout(new FlowLayout()); will be set the layout as FlowLayout.
Which Container method is used to cause a container to be laid out and redisplayed?
validate()
Name Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.
What is the purpose of the enableEvents() method?
The enableEvents() method is used to enable an event for a particular component. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.
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.
What do heavy weight components mean?
Heavy weight components like Abstract Window Toolkit (AWT) depend on the local windowing toolkit. For example, java.awt .Button is a heavy weight component.
What is the difference between a Scrollbar and a ScrollPane?
A Scrollbar is just a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.
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.
Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.


Java Threads Interview Questions
What are three ways in which a thread can enter the waiting state?
Or
What are different ways in which a thread can enter the waiting state?
A thread can enter the waiting state by the following ways:
1. Invoking its sleep() method,
2. By blocking on I/O
3. By unsuccessfully attempting to acquire an object’s lock
4. By invoking an object’s wait() method.
5. It can also enter the waiting state by invoking its (deprecated) suspend() method.
What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state, either from waiting, running or after its creation. When a task invokes its sleep() method, it returns to the waiting state from a running state.


How to create multithreaded program? Explain different ways of using thread? When a thread is created and started, what is its initial state?
Or
Extending Thread class or implementing Runnable Interface. Which is better?
You have two ways to do so. First, making your class “extends” Thread class. The other way is making your class implement “Runnable” interface. The latter is more advantageous, cause when you are going for multiple inheritance, then only interface can help. . If you are already inheriting a different class, then you have to go for Runnable Interface. Otherwise you can extend Thread class. Also, if you are implementing interface, it means you have to implement all methods in the interface. Both Thread class and Runnable interface are provided for convenience and use them as per the requirement. But if you are not extending any class, better extend Thread class as it will save few lines of coding. Otherwise performance wise, there is no distinguishable difference. A thread is in the ready state after it has been created and started.
What is mutual exclusion? How can you take care of mutual exclusion using Java threads?
Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.
What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then re-enters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
What invokes a thread’s run() method?
After a thread is started, via its start() method of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.
What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(), notify() and notifyAll() methods are used to provide an efficient way for thread inter-communication.
What is thread? What are the high-level thread states?
Or
What are the states associated in the thread?
A thread is an independent path of execution in a system. The high-level thread states are ready, running, waiting and dead.
What is deadlock?
When two threads are waiting for each other and can’t proceed until the first thread obtains a lock on the other thread or vice versa, the program is said to be in a deadlock.
How does multithreading take place on a computer with a single CPU?
The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.
What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
Can Java object be locked down for exclusive use by a given thread?
Or
What happens when a thread cannot acquire a lock on an object?
Yes. You can lock an object by putting it in a “synchronized” block. The locked object is inaccessible to any thread other than the one that explicitly claimed it. If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.
What’s the difference between the methods sleep() and wait()?
The sleep method is used when the thread has to be put aside for a fixed amount of time. Ex: sleep(1000), puts the thread aside for exactly one second. The wait method is used to put the thread aside for up to the specified time. It could wait for much lesser time if it receives a notify() or notifyAll() call. Ex: wait(1000), causes a wait of up to one second. The method wait() is defined in the Object and the method sleep() is defined in the class Thread.
What is the difference between process and thread?
A thread is a separate path of execution in a program. A Process is a program in execution.
What is daemon thread and which method is used to create the daemon thread?
Daemon threads are threads with low priority and runs in the back ground doing the garbage collection operation for the java runtime system. The setDaemon() method is used to create a daemon thread. These threads run without the intervention of the user. To determine if a thread is a daemon thread, use the accessor method isDaemon()
When a standalone application is run then as long as any user threads are active the JVM cannot terminate, otherwise the JVM terminates along with any daemon threads which might be active. Thus a daemon thread is at the mercy of the runtime system. Daemon threads exist only to serve user threads.
What do you understand by Synchronization?
Or
What is synchronization and why is it important?
Or
Describe synchronization in respect to multithreading?
Or
What is synchronization?
With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object’s value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.
E.g. synchronizing a function:
public synchronized void Method1 () {
// method code.
}
E.g. synchronizing a block of code inside a function:
public Method2 (){
synchronized (this) {
// synchronized code here.
}
}
When you will synchronize a piece of your code?
When you expect that your shared code will be accessed by different threads and these threads may change a particular data causing data corruption, then they are placed in a synchronized construct or a synchronized method.
Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.
What is an object’s lock and which objects have locks?
Answer: 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.
Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.
What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
How would you implement a thread pool?
public class ThreadPool implements ThreadPoolInt
This class is an generic implementation of a thread pool, which takes the following input
a) Size of the pool to be constructed
b) Name of the class which implements Runnable and constructs a thread pool with active threads that are waiting for activation. Once the threads have finished processing they come back and wait once again in the pool.
This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is preferable that the thread engine be locked. Locking ensures that no new threads are issued by the engine. However, the currently executing threads are allowed to continue till they come back to the passivePool.
Is there a separate stack for each thread in Java?
Yes. Every thread maintains its own separate stack, called Runtime Stack but they share the same memory. Elements of the stack are the method invocations,
called activation records or stack frame. The activation record contains pertinent information about a method like local variables.
Java Wrapper Classes Interview Questions

What are Wrapper Classes? Describe the wrapper classes in Java.
Wrapper classes are classes that allow primitive types to be accessed as objects. Wrapper class is wrapper around a primitive data type.
Following table lists the primitive types and the corresponding wrapper classes:


Primitive Wrapper
Boolean java.lang.Boolean
Byte java.lang.Byte
Char java.lang.Character
double java.lang.Double
Float java.lang.Float
Int java.lang.Integer
Long java.lang.Long
Short java.lang.Short
Void java.lang.Void















Master list of Java interview questions - 115 questions
1. What is the difference between procedural and object-oriented programs?- a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code. b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.
2. What are Encapsulation, Inheritance and Polymorphism?- Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions.
3. What is the difference between Assignment and Initialization?- Assignment can be done as many times as desired whereas initialization can be done only once.
4. What is OOPs?- Object oriented programming organizes a program around its data, i. e. , objects and a set of well defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.
5. What are Class, Constructor and Primitive data types?- Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform. Constructor is a special kind of method that determines how an object is initialized when created. Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean, char.
6. What is an Object and how do you allocate memory to it?- Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using new operator, memory is allocated to it.
7. What is the difference between constructor and method?- Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.
8. What are methods and how are they defined?- Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes. Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method’s signature is a combination of the first three parts mentioned above.
9. What is the use of bin and lib in JDK?- Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.
10. What is casting?- Casting is used to convert the value of one type to another.
11. How many ways can an argument be passed to a subroutine and explain them?- An argument can be passed in two ways. They are passing by value and passing by reference. Passing by value: This method copies the value of an argument into the formal parameter of the subroutine.
Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.
12. What is the difference between an argument and a parameter?- While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.
13. What are different types of access modifiers?- public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private can’t be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package.
14. What is final, finalize() and finally?- final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can’t be overridden. A final variable can’t change from its initialized value. finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection. finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.
15. What is UNICODE?- Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.
16. What is Garbage Collection and how to call it explicitly?- When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.
17. What is finalize() method?- finalize () method is used just before an object is destroyed and can be called just prior to garbage collection.
18. What are Transient and Volatile Modifiers?- Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.
19. What is method overloading and method overriding?- Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.
20. What is difference between overloading and overriding?- a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method. b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass. d) Overloading must have different method signatures whereas overriding must have same signature.
21. What is meant by Inheritance and what are its advantages?- Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.
22. What is the difference between this() and super()?- this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.
23. What is the difference between superclass and subclass?- A super class is a class that is inherited whereas sub class is a class that does the inheriting.
24. What modifiers may be used with top-level class?- public, abstract and final can be used for top-level class.
25. What are inner class and anonymous class?- Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.
26. What is a package?- A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.
27. What is a reflection package?- java. lang. reflect package has the ability to analyze itself in runtime.
28. What is interface and its use?- Interface is similar to a class which may contain method’s signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for: a)Declaring methods that one or more classes are expected to implement b)Capturing similarities between unrelated classes without forcing a class relationship. c)Determining an object’s programming interface without revealing the actual body of the class.
29. What is an abstract class?- An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.
30. What is the difference between Integer and int?- a) Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other. b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.
31. What is a cloneable interface and how many methods does it contain?- It is not having any method because it is a TAGGED or MARKER interface.
32. What is the difference between abstract class and interface?- a) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be concrete or abstract. b) In abstract class, key word abstract must be used for the methods whereas interface we need not use that keyword for the methods. c) Abstract class must have subclasses whereas interface can’t have subclasses.
33. Can you have an inner class inside a method and what variables can you access?- Yes, we can have an inner class inside a method and final variables can be accessed.
34. What is the difference between String and String Buffer?- a) String objects are constants and immutable whereas StringBuffer objects are not. b) String class supports constant strings whereas StringBuffer class supports growable and modifiable strings.
35. What is the difference between Array and vector?- Array is a set of related data type and static whereas vector is a growable array of objects and dynamic.
36. What is the difference between exception and error?- The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file, which does not exist, the network connection is disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested in loading is missing. The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.
37. What is the difference between process and thread?- Process is a program in execution whereas thread is a separate path of execution in a program.
38. What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?- Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.
39. What is the class and interface in java to create thread and which is the most advantageous method?- Thread class and Runnable interface can be used to create threads and using Runnable interface is the most advantageous method to create threads because we need not extend thread class here.
40. What are the states associated in the thread?- Thread contains ready, running, waiting and dead states.
41. What is synchronization?- Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time.
42. When you will synchronize a piece of your code?- When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.
43. What is deadlock?- When two threads are waiting each other and can’t precede the program is said to be deadlock.
44. What is daemon thread and which method is used to create the daemon thread?- Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.
45. Are there any global variables in Java, which can be accessed by other part of your program?- No, it is not the main method in which you define variables. Global variables is not possible because concept of encapsulation is eliminated here.
46. What is an applet?- Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser.
47. What is the difference between applications and applets?- a)Application must be run on local machine whereas applet needs no explicit installation on local machine. b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser. d)Application starts execution with its main method whereas applet starts execution with its init method. e)Application can run with or without graphical user interface whereas applet must run within a graphical user interface.
48. How does applet recognize the height and width?- Using getParameters() method.
49. When do you use codebase in applet?- When the applet class file is not in the same directory, codebase is used.
50. What is the lifecycle of an applet?- init() method - Can be called when an applet is first loaded start() method - Can be called each time an applet is started. paint() method - Can be called when the applet is minimized or maximized. stop() method - Can be used when the browser moves off the applet’s page. destroy() method - Can be called when the browser is finished with the applet.
51. How do you set security in applets?- using setSecurityManager() method
52. What is an event and what are the models available for event handling?- An event is an event object that describes a state of change in a source. In other words, event occurs when an action is generated, like pressing button, clicking mouse, selecting a list, etc. There are two types of models for handling events and they are: a) event-inheritance model and b) event-delegation model
53. What are the advantages of the model over the event-inheritance model?- The event-delegation model has two advantages over the event-inheritance model. They are: a)It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component’s design and its use. b)It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to be repeatedly process unhandled events as is the case of the event-inheritance.
54. What is source and listener?- source : A source is an object that generates an event. This occurs when the internal state of that object changes in some way. listener : A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.
55. What is adapter class?- An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act listener by extending one of the adapter classes and implementing only those events in which you are interested. For example, the MouseMotionAdapter class has two methods, mouseDragged()and mouseMoved(). The signatures of these empty are exactly as defined in the MouseMotionListener interface. If you are interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mouseDragged() .
56. What is meant by controls and what are different types of controls in AWT?- Controls are components that allow a user to interact with your application and the AWT supports the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.
57. What is the difference between choice and list?- A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices and only one item may be selected from a choice. A List may be displayed in such a way that several list items are visible and it supports the selection of one or more list items.
58. What is the difference between scrollbar and scrollpane?- A Scrollbar is a Component, but not a Container whereas Scrollpane is a Conatiner and handles its own events and perform its own scrolling.
59. What is a layout manager and what are different types of layout managers available in java AWT?- A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout.
60. How are the elements of different layouts organized?- FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion. BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container. CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards. GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid. GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements are of different size and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.
61. Which containers use a Border layout as their default layout?- Window, Frame and Dialog classes use a BorderLayout as their layout.
62. Which containers use a Flow layout as their default layout?- Panel and Applet classes use the FlowLayout as their default layout.
63. What are wrapper classes?- Wrapper classes are classes that allow primitive types to be accessed as objects.
64. What are Vector, Hashtable, LinkedList and Enumeration?- Vector : The Vector class provides the capability to implement a growable array of objects. Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable indexes and stores objects in a dictionary using hash codes as the object’s keys. Hash codes are integer values that identify objects. LinkedList: Removing or inserting elements in the middle of an array can be done using LinkedList. A LinkedList stores each object in a separate link whereas an array stores object references in consecutive locations. Enumeration: An object that implements the Enumeration interface generates a series of elements, one at a time. It has two methods, namely hasMoreElements() and nextElement(). HasMoreElemnts() tests if this enumeration has more elements and nextElement method returns successive elements of the series.
65. What is the difference between set and list?- Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements.
66. What is a stream and what are the types of Streams and classes of the Streams?- A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are: Byte Streams: Provide a convenient means for handling input and output of bytes. Character Streams: Provide a convenient means for handling input & output of characters. Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream. Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer.
67. What is the difference between Reader/Writer and InputStream/Output Stream?- The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented.
68. What is an I/O filter?- An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
69. What is serialization and deserialization?- Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.
70. What is JDBC?- JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications.
71. What are drivers available?- a) JDBC-ODBC Bridge driver b) Native API Partly-Java driver c) JDBC-Net Pure Java driver d) Native-Protocol Pure Java driver
72. What is the difference between JDBC and ODBC?- a) OBDC is for Microsoft and JDBC is for Java applications. b) ODBC can’t be directly used with Java because it uses a C interface. c) ODBC makes use of pointers which have been removed totally from Java. d) ODBC mixes simple and advanced features together and has complex options for simple queries. But JDBC is designed to keep things simple while allowing advanced capabilities when required. e) ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and portable on all platforms. f) JDBC API is a natural Java interface and is built on ODBC. JDBC retains some of the basic features of ODBC.
73. What are the types of JDBC Driver Models and explain them?- There are two types of JDBC Driver Models and they are: a) Two tier model and b) Three tier model Two tier model: In this model, Java applications interact directly with the database. A JDBC driver is required to communicate with the particular database management system that is being accessed. SQL statements are sent to the database and the results are given to user. This model is referred to as client/server configuration where user is the client and the machine that has the database is called as the server. Three tier model: A middle tier is introduced in this model. The functions of this model are: a) Collection of SQL statements from the client and handing it over to the database, b) Receiving results from database to the client and c) Maintaining control over accessing and updating of the above.
74. What are the steps involved for making a connection with a database or how do you connect to a database?a) Loading the driver : To load the driver, Class. forName() method is used. Class. forName(”sun. jdbc. odbc. JdbcOdbcDriver”); When the driver is loaded, it registers itself with the java. sql. DriverManager class as an available database driver. b) Making a connection with database: To open a connection to a given database, DriverManager. getConnection() method is used. Connection con = DriverManager. getConnection (”jdbc:odbc:somedb”, “user”, “password”); c) Executing SQL statements : To execute a SQL query, java. sql. statements class is used. createStatement() method of Connection to obtain a new Statement object. Statement stmt = con. createStatement(); A query that returns data can be executed using the executeQuery() method of Statement. This method executes the statement and returns a java. sql. ResultSet that encapsulates the retrieved data: ResultSet rs = stmt. executeQuery(”SELECT * FROM some table”); d) Process the results : ResultSet returns one row at a time. Next() method of ResultSet object can be called to move to the next row. The getString() and getObject() methods are used for retrieving column values: while(rs. next()) { String event = rs. getString(”event”); Object count = (Integer) rs. getObject(”count”);
75. What type of driver did you use in project?- JDBC-ODBC Bridge driver (is a driver that uses native(C language) libraries and makes calls to an existing ODBC driver to access a database engine).
76. What are the types of statements in JDBC?- Statement: to be used createStatement() method for executing single SQL statement PreparedStatement — To be used preparedStatement() method for executing same SQL statement over and over. CallableStatement — To be used prepareCall() method for multiple SQL statements over and over.
77. What is stored procedure?- Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.
78. How to create and call stored procedures?- To create stored procedures: Create procedure procedurename (specify in, out and in out parameters) BEGIN Any multiple SQL statement; END; To call stored procedures: CallableStatement csmt = con. prepareCall(”{call procedure name(?,?)}”); csmt. registerOutParameter(column no. , data type); csmt. setInt(column no. , column name) csmt. execute();
79. What is servlet?- Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database.
80. What are the classes and interfaces for servlets?- There are two packages in servlets and they are javax. servlet and
81. What is the difference between an applet and a servlet?- a) Servlets are to servers what applets are to browsers. b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.
82. What is the difference between doPost and doGet methods?- a) doGet() method is used to get information, while doPost() method is used for posting information. b) doGet() requests can’t send large amount of information and is limited to 240-255 characters. However, doPost()requests passes all of its data, of unlimited length. c) A doGet() request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.
83. What is the life cycle of a servlet?- Each Servlet has the same life cycle: a) A server loads and initializes the servlet by init () method. b) The servlet handles zero or more client’s requests through service() method. c) The server removes the servlet through destroy() method.
84. Who is loading the init() method of servlet?- Web server
85. What are the different servers available for developing and deploying Servlets?- a) Java Web Server b) JRun g) Apache Server h) Netscape Information Server i) Web Logic
86. How many ways can we track client and what are they?- The servlet API provides two ways to track client state and they are: a) Using Session tracking and b) Using Cookies.
87. What is session tracking and how do you track a user session in servlets?- Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are: a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password. b) Hidden form fields - fields are added to an HTML form that are not displayed in the client’s browser. When the form containing the fields is submitted, the fields are sent back to the server. c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change. d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser. e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session. maxresidents property.
88. What is Server-Side Includes (SSI)?- Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with an . shtml extension.
89. What are cookies and how will you use them?- Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user. a) Create a cookie with the Cookie constructor: public Cookie(String name, String value) b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse: public void HttpServletResponse. addCookie(Cookie cookie) c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest: public Cookie[ ] HttpServletRequest. getCookie().
90. Is it possible to communicate from an applet to servlet and how many ways and how?- Yes, there are three ways to communicate from an applet to servlet and they are: a) HTTP Communication(Text-based and object-based) b) Socket Communication c) RMI Communication
91. What is connection pooling?- With servlets, opening a database connection is a major bottleneck because we are creating and tearing down a new connection for every page request and the time taken to create connection will be more. Creating a connection pool is an ideal approach for a complicated servlet. With a connection pool, we can duplicate only the resources we need to duplicate rather than the entire servlet. A connection pool can also intelligently manage the size of the pool and make sure each connection remains valid. A number of connection pool packages are currently available. Some like DbConnectionBroker are freely available from Java Exchange Works by creating an object that dispenses connections and connection Ids on request. The ConnectionPool class maintains a Hastable, using Connection objects as keys and Boolean values as stored values. The Boolean value indicates whether a connection is in use or not. A program calls getConnection() method of the ConnectionPool for getting Connection object it can use; it calls returnConnection() to give the connection back to the pool.
92. Why should we go for interservlet communication?- Servlets running together in the same server communicate with each other in several ways. The three major reasons to use interservlet communication are: a) Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object) b) Servlet reuse - allows the servlet to reuse the public methods of another servlet. c) Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation)
93. Is it possible to call servlet with parameters in the URL?- Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).
94. What is Servlet chaining?- Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request. In servlet chaining, one servlet’s output is piped to the next servlet’s input. This process continues until the last servlet is reached. Its output is then sent back to the client.
95. How do servlets handle multiple simultaneous requests?- The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost() and service()) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.
96. What is the difference between TCP/IP and UDP?- TCP/IP is a two-way communication between the client and the server and it is a reliable and there is a confirmation regarding reaching the message to the destination. It is like a phone call. UDP is a one-way communication only between the client and the server and it is not a reliable and there is no confirmation regarding reaching the message to the destination. It is like a postal mail.
97. What is Inet address?- Every computer connected to a network has an IP address. An IP address is a number that uniquely identifies each computer on the Net. An IP address is a 32-bit number.
98. What is Domain Naming Service(DNS)?- It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters. For example, www. mascom. com implies com is the domain name reserved for US commercial sites, moscom is the name of the company and www is the name of the specific computer, which is mascom’s server.
99. What is URL?- URL stands for Uniform Resource Locator and it points to resource files on the Internet. URL has four components: http://www. address. com:80/index.html, where http - protocol name, address - IP address or host name, 80 - port number and index.html - file path.
100. What is RMI and steps involved in developing an RMI object?- Remote Method Invocation (RMI) allows java object that executes on one machine and to invoke the method of a Java object to execute on another machine. The steps involved in developing an RMI object are: a) Define the interfaces b) Implementing these interfaces c) Compile the interfaces and their implementations with the java compiler d) Compile the server implementation with RMI compiler e) Run the RMI registry f) Run the application
101. What is RMI architecture?- RMI architecture consists of four layers and each layer performs specific functions: a) Application layer - contains the actual object definition. b) Proxy layer - consists of stub and skeleton. c) Remote Reference layer - gets the stream of bytes from the transport layer and sends it to the proxy layer. d) Transportation layer - responsible for handling the actual machine-to-machine communication.
102. what is UnicastRemoteObject?- All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make objects available from remote machines.
103. Explain the methods, rebind() and lookup() in Naming class?- rebind() of the Naming class(found in java. rmi) is used to update the RMI registry on the server machine. Naming. rebind(”AddSever”, AddServerImpl); lookup() of the Naming class accepts one argument, the rmi URL and returns a reference to an object of type AddServerImpl.
104. What is a Java Bean?- A Java Bean is a software component that has been designed to be reusable in a variety of different environments.
105. What is a Jar file?- Jar file allows to efficiently deploying a set of classes and their associated resources. The elements in a jar file are compressed, which makes downloading a Jar file much faster than separately downloading several uncompressed files. The package java. util. zip contains classes that read and write jar files.
106. What is BDK?- BDK, Bean Development Kit is a tool that enables to create, configure and connect a set of set of Beans and it can be used to test Beans without writing a code.
107. What is JSP?- JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to be embedded into a web file (HTML/XML, etc). The suffix traditionally ends with .jsp to indicate to the web server that the file is a JSP files. JSP is a server side technology - you can’t do any client side validation with it. The advantages are: a) The JSP assists in making the HTML more functional. Servlets on the other hand allow outputting of HTML but it is a tedious process. b) It is easy to make a change and then let the JSP capability of the web server you are using deal with compiling it into a servlet and running it.
108. What are JSP scripting elements?- JSP scripting elements lets to insert Java code into the servlet that will be generated from the current JSP page. There are three forms: a) Expressions of the form <%= expression %> that are evaluated and inserted into the output, b) Scriptlets of the form<% code %>that are inserted into the servlet’s service method, and c) Declarations of the form <%! Code %>that are inserted into the body of the servlet class, outside of any existing methods.
109. What are JSP Directives?- A JSP directive affects the overall structure of the servlet class. It usually has the following form:<%@ directive attribute=”value” %> However, you can also combine multiple attribute settings for a single directive, as follows:<%@ directive attribute1=”value1″ attribute 2=”value2″ . . . attributeN =”valueN” %> There are two main types of directive: page, which lets to do things like import classes, customize the servlet superclass, and the like; and include, which lets to insert a file into the servlet class at the time the JSP file is translated into a servlet
110. What are Predefined variables or implicit objects?- To simplify code in JSP expressions and scriptlets, we can use eight automatically defined variables, sometimes called implicit objects. They are request, response, out, session, application, config, pageContext, and page.
111. What are JSP ACTIONS?- JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include: 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 newpage. Jsp: plugin - Generate browser-specific code that makes an OBJECT or EMBED
112. How do you pass data (including JavaBeans) to a JSP from a servlet?- (1) Request Lifetime: Using this technique to pass beans, a request dispatcher (using either “include” or forward”) can be called. This bean will disappear after processing this request has been completed. Servlet: request. setAttribute(”theBean”, myBean); RequestDispatcher rd = getServletContext(). getRequestDispatcher(”thepage. jsp”); rd. forward(request, response); JSP PAGE:(2) Session Lifetime: Using this technique to pass beans that are relevant to a particular session (such as in individual user login) over a number of requests. This bean will disappear when the session is invalidated or it times out, or when you remove it. Servlet: HttpSession session = request. getSession(true); session. putValue(”theBean”, myBean); /* You can do a request dispatcher here, or just let the bean be visible on the next request */ JSP Page: 3) Application Lifetime: Using this technique to pass beans that are relevant to all servlets and JSP pages in a particular app, for all users. For example, I use this to make a JDBC connection pool object available to the various servlets and JSP pages in my apps. This bean will disappear when the servlet engine is shut down, or when you remove it. Servlet: GetServletContext(). setAttribute(”theBean”, myBean); JSP PAGE:
113. How can I set a cookie in JSP?- response. setHeader(”Set-Cookie”, “cookie string”); To give the response-object to a bean, write a method setResponse (HttpServletResponse response) - to the bean, and in jsp-file:<% bean. setResponse (response); %>
114. How can I delete a cookie with JSP?- Say that I have a cookie called “foo, ” that I set a while ago & I want it to go away. I simply: <% Cookie killCookie = new Cookie(”foo”, null); KillCookie. setPath(”/”); killCookie. setMaxAge(0); response. addCookie(killCookie); %>
115. How are Servlets and JSP Pages related?- JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.






Java Interview questions
1. How could Java classes direct program messages to the system console, but error messages, say to a file?
The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st =
new Stream (new
FileOutputStream (”techinterviews_com.txt”));
System.setErr(st);
System.setOut(st);
2. What’s the difference between an interface and an abstract class?
An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.
3. Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.
4. Explain the usage of the keyword transient?
This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).
5. How can you force garbage collection?
You can’t force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.
6. How do you know if an explicit object casting is needed?
If you assign a superclass object to a variable of a subclass’s data type, you need to do explicit casting. For example:
Object a;Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.
7. What’s the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
8. Can you write a Java class that could be used both as an applet as well as an application?
Yes. Add a main() method to the applet.
9. What’s the difference between constructors and other methods?
Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.
10. Can you call one constructor from another if a class has multiple constructors
Yes. Use this() syntax.
11. Explain the usage of Java packages.
This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.
12. If a class is located in a package, what do you need to change in the OS environment to be able to use it?
You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let’s say a class Employee belongs to a package com.xyz.hr; and is located in the file c:/dev/com.xyz.hr.Employee.java. In this case, you’d need to add c:/dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee
13. What’s the difference between J2SDK 1.5 and J2SDK 5.0?
There’s no difference, Sun Microsystems just re-branded this version.
14. What would you use to compare two String variables - the operator == or the method equals()?
I’d use the method equals() to compare the values of the Strings and the = = to check if two variables point at the same instance of a String object.
15. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception’s subclasses have to be caught first.
16. Can an inner class declared inside of a method access local variables of this method?
It’s possible if these variables are final.
17. What can go wrong if you replace && with & in the following code:
String a=null;
if (a!=null && a.length()>10)
{…}
A single ampersand here would lead to a NullPointerException.
18. What’s the main difference between a Vector and an ArrayList
Java Vector class is internally synchronized and ArrayList is not.
19. When should the method invokeLater()be used?
This method is used to ensure that Swing components are updated through the event-dispatching thread.
20. How can a subclass call a method or a constructor defined in a superclass?
Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass’s constructor.
21. What’s the difference between a queue and a stack?
Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule.
22. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?
Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.
23. What comes to mind when you hear about a young generation in Java?
Garbage collection.
24. What comes to mind when someone mentions a shallow copy in Java?
Object cloning.
25. If you’re overriding the method equals() of an object, which other method you might also consider?
hashCode()
26. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use: ArrayList or LinkedList?
ArrayList
27. How would you make a copy of an entire Java object with its state?
Have this class implement Cloneable interface and call its method clone().
28. How can you minimize the need of garbage collection and make the memory use more effective?
Use object pooling and weak object references.
29. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
If these classes are threads I’d consider notify() or notifyAll(). For regular classes you can use the Observer interface.
30. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
You do not need to specify any access level, and Java will use a default package access level.




Java interview questions and answers
Describe what happens when an object is created in Java?
Several things happen in a particular order to ensure the object is constructed properly:
1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implementation-specific data includes pointers to class and method data.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its uppercase. This process continues until the constructor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
In Java, you can create a String object as below : String str = "abc"; & String str = new String("abc"); Why cant a button object be created as : Button bt = "abc"? Why is it compulsory to create a button object as: Button bt = new Button("abc"); Why this is not compulsory in String’s case?
Button bt1= "abc"; It is because "abc" is a literal string (something slightly different than a String object, by-the-way) and bt1 is a Button object. That simple. The only object in Java that can be assigned a literal String is java.lang.String. Important to not that you are NOT calling a java.lang.String constuctor when you type String s = "abc"; For example String x = "abc"; String y = "abc"; refer to the same object. While String x1 = new String("abc");
String x2 = new String("abc"); refer to two different objects.
What is the advantage of OOP?
You will get varying answers to this question depending on whom you ask. Major advantages of OOP are:
1. Simplicity: software objects model real world objects, so the complexity is reduced and the program structure is very clear;
2. Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system;
3. Modifiability: it is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods;
4. Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones;
5. Maintainability: objects can be maintained separately, making locating and fixing problems easier;
6. Re-usability: objects can be reused in different programs
What are the main differences between Java and C++?
Everything is an object in Java( Single root hierarchy as everything gets derived from java.lang.Object). Java does not have all the complicated aspects of C++ ( For ex: Pointers, templates, unions, operator overloading, structures etc..) The Java language promoters initially said "No pointers!", but when many programmers questioned how you can work without pointers, the promoters began saying "Restricted pointers." You can make up your mind whether it’s really a pointer or not. In any event, there’s no pointer arithmetic. There are no destructors in Java. (automatic garbage collection), Java does not support conditional compile (#ifdef/#ifndef type). Thread support is built into java but not in C++. Java does not support default arguments. There’s no scope resolution operator :: in Java. Java uses the dot for everything, but can get away with it since you can define elements only within a class. Even the method definitions must always occur within a class, so there is no need for scope resolution there either. There’s no "goto " statement in Java. Java doesn’t provide multiple inheritance (MI), at least not in the same sense that C++ does. Exception handling in Java is different because there are no destructors. Java has method overloading, but no operator overloading. The String class does use the + and += operators to concatenate strings and String expressions use automatic type conversion, but that’s a special built-in case. Java is interpreted for the most part and hence platform independent
What are interfaces?
Interfaces provide more sophisticated ways to organize and control the objects in your system.
The interface keyword takes the abstract concept one step further. You could think of it as a “pure” abstract class. It allows the creator to establish the form for a class: method names, argument lists, and return types, but no method bodies. An interface can also contain fields, but The interface keyword takes the abstract concept one step further. You could think of it as a “pure” abstract class. It allows the creator to establish the form for a class: method names, argument lists, and return types, but no method bodies. An interface can also contain fields, but an interface says: “This is what all classes that implement this particular interface will look like.” Thus, any code that uses a particular interface knows what methods might be called for that interface, and that’s all. So the interface is used to establish a “protocol” between classes. (Some object-oriented programming languages have a keyword called protocol to do the same thing.) Typical example from "Thinking in Java":
import java.util.*;
interface Instrument {
int i = 5; // static & final
// Cannot have method definitions:
void play(); // Automatically public
String what();
void adjust();
}
class Wind implements Instrument {
public void play() {
System.out.println("Wind.play()");
public String what() { return "Wind"; }
public void adjust() {}
}
How can you achieve Multiple Inheritance in Java?
Java’s interface mechanism can be used to implement multiple inheritance, with one important difference from c++ way of doing MI: the inherited interfaces must be abstract. This obviates the need to choose between different implementations, as with interfaces there are no implementations.
interface CanFight {
void fight();
interface CanSwim {
void swim();
interface CanFly {
void fly();
class ActionCharacter {
public void fight() {}
class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly {
public void swim() {}
public void fly() {}
}
You can even achieve a form of multiple inheritance where you can use the *functionality* of classes rather than just the interface:
interface A {
void methodA();
}
class AImpl implements A {
void methodA() { //do stuff }
}
interface B {
void methodB();
}
class BImpl implements B {
void methodB() { //do stuff }
}
class Multiple implements A, B {
private A a = new A();
private B b = new B();
void methodA() { a.methodA(); }
void methodB() { b.methodB(); }
}
This completely solves the traditional problems of multiple inheritance in C++ where name clashes occur between multiple base classes. The coder of the derived class will have to explicitly resolve any clashes. Don’t you hate people who point out minor typos? Everything in the previous example is correct, except you need to instantiate an AImpl and BImpl. So class Multiple would look like this:
class Multiple implements A, B {
private A a = new AImpl();
private B b = new BImpl();
void methodA() { a.methodA(); }
void methodB() { b.methodB(); }
}
What is the difference between StringBuffer and String class?
A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. The String class represents character strings. All string literals in Java programs, such as "abc" are constant and implemented as instances of this class; their values cannot be changed after they are created. Strings in Java are known to be immutable. What it means is that every time you need to make a change to a String variable, behind the scene, a "new" String is actually being created by the JVM. For an example: if you change your String variable 2 times, then you end up with 3 Strings: one current and 2 that are ready for garbage collection. The garbage collection cycle is quite unpredictable and these additional unwanted Strings will take up memory until that cycle occurs. For better performance, use StringBuffers for string-type data that will be reused or changed frequently. There is more overhead per class than using String, but you will end up with less overall classes and consequently consume less memory. Describe, in general, how java’s garbage collector works? The Java runtime environment deletes objects when it determines that they are no longer being used. This process is known as garbage collection. The Java runtime environment supports a garbage collector that periodically frees the memory used by objects that are no longer needed. The Java garbage collector is a mark-sweep garbage collector that scans Java’s dynamic memory areas for objects, marking those that are referenced. After all possible paths to objects are investigated, those objects that are not marked (i.e. are not referenced) are known to be garbage and are collected. (A more complete description of our garbage collection algorithm might be "A compacting, mark-sweep collector with some conservative scanning".) The garbage collector runs synchronously when the system runs out of memory, or in response to a request from a Java program. Your Java program can ask the garbage collector to run at any time by calling System.gc(). The garbage collector requires about 20 milliseconds to complete its task so, your program should only run the garbage collector when there will be no performance impact and the program anticipates an idle period long enough for the garbage collector to finish its job. Note: Asking the garbage collection to run does not guarantee that your objects will be garbage collected. The Java garbage collector runs asynchronously when the system is idle on systems that allow the Java runtime to note when a thread has begun and to interrupt another thread (such as Windows 95). As soon as another thread becomes active, the garbage collector is asked to get to a consistent state and then terminate.
What’s the difference between == and equals method?
equals checks for the content of the string objects while == checks for the fact that the two String objects point to same memory location ie they are same references.
What are abstract classes, abstract methods?
Simply speaking a class or a method qualified with "abstract" keyword is an abstract class or abstract method. You create an abstract class when you want to manipulate a set of classes through a common interface. All derived-class methods that match the signature of the base-class declaration will be called using the dynamic binding mechanism. If you have an abstract class, objects of that class almost always have no meaning. That is, abstract class is meant to express only the interface and sometimes some default method implementations, and not a particular implementation, so creating an abstract class object makes no sense and are not allowed ( compile will give you an error message if you try to create one). An abstract method is an incomplete method. It has only a declaration and no method body. Here is the syntax for an abstract method declaration: abstract void f(); If a class contains one or more abstract methods, the class must be qualified an abstract. (Otherwise, the compiler gives you an error message.). It’s possible to create a class as abstract without including any abstract methods. This is useful when you’ve got a class in which it doesn’t make sense to have any abstract methods, and yet you want to prevent any instances of that class. Abstract classes and methods are created because they make the abstractness of a class explicit, and tell both the user and the compiler how it was intended to be used.
For example:
abstract class Instrument {
int i; // storage allocated for each
public abstract void play();
public String what() {
return "Instrument";
public abstract void adjust();
}
class Wind extends Instrument {
public void play() {
System.out.println("Wind.play()");
}
public String what() { return "Wind"; }
public void adjust() {}
Abstract classes are classes for which there can be no instances at run time. i.e. the implementation of the abstract classes are not complete. Abstract methods are methods which have no defintion. i.e. abstract methods have to be implemented in one of the sub classes or else that class will also become Abstract.
What is the difference between an Applet and an Application?
A Java application is made up of a main() method declared as public static void that accepts a string array argument, along with any other classes that main() calls. It lives in the environment that the host OS provides. A Java applet is made up of at least one public class that has to be subclassed from java.awt.Applet. The applet is confined to living in the user’s Web browser, and the browser’s security rules, (or Sun’s appletviewer, which has fewer restrictions). The differences between an applet and an application are as follows:
1. Applets can be embedded in HTML pages and downloaded over the Internet whereas Applications have no special support in HTML for embedding or downloading.
2. Applets can only be executed inside a java compatible container, such as a browser or appletviewer whereas Applications are executed at command line by java.exe or jview.exe.
3. Applets execute under strict security limitations that disallow certain operations(sandbox model security) whereas Applications have no inherent security restrictions.
4. Applets don’t have the main() method as in applications. Instead they operate on an entirely different mechanism where they are initialized by init(),started by start(),stopped by stop() or destroyed by destroy().
Java says "write once, run anywhere". What are some ways this isn’t quite true?
As long as all implementaions of java are certified by sun as 100% pure java this promise of "Write once, Run everywhere" will hold true. But as soon as various java core implemenations start digressing from each other, this won’t be true anymore. A recent example of a questionable business tactic is the surreptitious behavior and interface modification of some of Java’s core classes in their own implementation of Java. Programmers who do not recognize these undocumented changes can build their applications expecting them to run anywhere that Java can be found, only to discover that their code works only on Microsoft’s own Virtual Machine, which is only available on Microsoft’s own operating systems.
What is the difference between a Vector and an Array. Discuss the advantages and disadvantages of both?
Vector can contain objects of different types whereas array can contain objects only of a single type.
- Vector can expand at run-time, while array length is fixed.
- Vector methods are synchronized while Array methods are not
What are java beans?
JavaBeans is a portable, platform-independent component model written in the Java programming language, developed in collaboration with industry leaders. It enables developers to write reusable components once and run them anywhere — benefiting from the platform-independent power of Java technology. JavaBeans acts as a Bridge between proprietary component models and provides a seamless and powerful means for developers to build components that run in ActiveX container applications. JavaBeans are usual Java classes which adhere to certain coding conventions:
1. Implements java.io.Serializable interface
2. Provides no argument constructor
3. Provides getter and setter methods for accessing it’s properties
What is RMI?
RMI stands for Remote Method Invocation. Traditional approaches to executing code on other machines across a network have been confusing as well as tedious and error-prone to implement. The nicest way to think about this problem is that some object happens to live on another machine, and that you can send a message to the remote object and get a result as if the object lived on your local machine. This simplification is exactly what Java Remote Method Invocation (RMI) allows you to do. Above excerpt is from "Thinking in java". For more information refer to any book on Java.
What does the keyword "synchronize" mean in java. When do you use it? What are the disadvantages of synchronization?
Synchronize is used when you want to make your methods thread safe. The disadvantage of synchronize is it will end up in slowing down the program. Also if not handled properly it will end up in dead lock.
What gives java it’s "write once and run anywhere" nature?
Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platorm specific and hence can be fed to any platform. After being fed to the JVM, which is specific to a particular operating system, the code platform specific machine code is generated thus making java platform independent.
What are native methods? How do you use them?
Native methods are methods written in other languages like C, C++, or even assembly language. You can call native methods from Java using JNI. Native methods are used when the implementation of a particular method is present in language other than Java say C, C++. To use the native methods in java we use the keyword native
public native method_a(). This native keyword is signal to the java compiler that the implementation of this method is in a language other than java. Native methods are used when we realize that it would take up a lot of rework to write that piece of already existing code in other language to Java.
What is JDBC? Describe the steps needed to execute a SQL query using JDBC.
We can connect to databases from java using JDBC. It stands for Java DataBase Connectivity.
Here are the steps:
1. Register the jdbc driver with the driver manager
2. Establish jdbc connection
3. Execute an sql statement
4. Process the results
5. Close the connection
Before doing these do import java.sql.*
JDBC is java based API for accessing data from the relational databases. JDBC provides a set of classes and interfaces for doing various database operations. The steps are:
Register/load the jdbc driver with the driver manager.
Establish the connection thru DriverManager.getConnection();
Fire a SQL thru conn.executeStatement();
Fetch the results in a result set
Process the results
Close statement/result set and connection object.
How many different types of JDBC drivers are present? Discuss them.
There are four JDBC driver types.
Type 1: JDBC-ODBC Bridge plus ODBC Driver:
The first type of JDBC driver is the JDBC-ODBC Bridge. It is a driver that provides JDBC access to databases through ODBC drivers. The ODBC driver must be configured on the client for the bridge to work. This driver type is commonly used for prototyping or when there is no JDBC driver available for a particular DBMS.
Type 2: Native-API partly-Java Driver:
The Native to API driver converts JDBC commands to DBMS-specific native calls. This is much like the restriction of Type 1 drivers. The client must have some binary code loaded on its machine. These drivers do have an advantage over Type 1 drivers because they interface directly with the database.
Type 3: JDBC-Net Pure Java Driver:
The JDBC-Net drivers are a three-tier solution. This type of driver translates JDBC calls into a database-independent network protocol that is sent to a middleware server. This server then translates this DBMS-independent protocol into a DBMS-specific protocol, which is sent
to a particular database. The results are then routed back through the middleware server and sent back to the client. This type of solution makes it possible to implement a pure Java client. It also makes it possible to swap databases without affecting the client.
Type 4: Native-Protocol Pure Java Driver
These are pure Java drivers that communicate directly with the vendor’s database. They do this by converting JDBC commands directly into the database engine’s native protocol. This driver has no additional translation or middleware layer, which improves performance tremendously.
What does the "static" keyword mean in front of a variable? A method? A class? Curly braces {}?
static variable
- means a class level variable
static method:
-does not have "this". It is not allowed to access the not static members of the class.
can be invoked enev before a single instance of a class is created.
eg: main
static class:
no such thing.
static free floating block:
is executed at the time the class is loaded. There can be multiple such blocks. This may be useful to load native libraries when using native methods.
eg:
native void doThis(){
static{
System.loadLibrary("myLibrary.lib");
}
Access specifiers: "public", "protected", "private", nothing?
In the case of Public, Private and Protected, that is used to describe which programs can access that class or method: Public – any other class from any package can instantiate and execute the classes and methods. Protected – only subclasses and classes inside of the package can access the classes and methods. Private – the original class is the only class allowed to executed the methods.
What does the "final" keyword mean in front of a variable? A method? A class?
FINAL for a variable : value is constant
FINAL for a method : cannot be overridden
FINAL for a class : cannot be derived
A final variable cannot be reassigned,
but it is not constant. For instance,
final StringBuffer x = new StringBuffer()
x.append("hello");
is valid. X cannot have a new value in it,but nothing stops operations on the object
that it refers, including destructive operations. Also, a final method cannot be overridden
or hidden by new access specifications.This means that the compiler can choose
to in-line the invocation of such a method.(I don’t know if any compiler actually does
this, but it’s true in theory.) The best example of a final class is
String, which defines a class that cannot be derived.
Does Java have "goto"?
No.
What synchronization constructs does Java provide? How do they work?
The two common features that are used are:
1. Synchronized keyword - Used to synchronize a method or a block of code. When you synchronize a method, you are in effect synchronizing the code within the method using the monitor of the current object for the lock.
The following have the same effect.
synchronized void foo() {
}
and
void foo() {
synchronized(this) {
}
If you synchronize a static method, then you are synchronizing across all objects of the same class, i.e. the monitor you are using for the lock is one per class, not one per object.
2. wait/notify. wait() needs to be called from within a synchronized block. It will first release the lock acquired from the synchronization and then wait for a signal. In Posix C, this part is equivalent to the pthread_cond_wait method, which waits for an OS signal to continue. When somebody calls notify() on the object, this will signal the code which has been waiting, and the code will continue from that point. If there are several sections of code that are in the wait state, you can call notifyAll() which will notify all threads that are waiting on the monitor for the current object. Remember that both wait() and notify() have to be called from blocks of code that are synchronized on the monitor for the current object.
Does Java have multiple inheritance?
Java does not support multiple inheritence directly but it does thru the concept of interfaces.
We can make a class implement a number of interfaces if we want to achieve multiple inheritence type of functionality of C++.
How does exception handling work in Java?
1.It separates the working/functional code from the error-handling code by way of try-catch clauses.
2.It allows a clean path for error propagation. If the called method encounters a situation it can’t manage, it can throw an exception and let the calling method deal with it.
3.By enlisting the compiler to ensure that "exceptional" situations are anticipated and accounted for, it enforces powerful coding.
4.Exceptions are of two types: Compiler-enforced exceptions, or checked exceptions. Runtime exceptions, or unchecked exceptions. Compiler-enforced (checked) exceptions are instances of the Exception class or one of its subclasses — excluding the RuntimeException branch. The compiler expects all checked exceptions to be appropriately handled. Checked exceptions must be declared in the throws clause of the method throwing them — assuming, of course, they’re not being caught within that same method. The calling method must take care of these exceptions by either catching or declaring them in its throws clause. Thus, making an exception checked forces the us to pay heed to the possibility of it being thrown. An example of a checked exception is java.io.IOException. As the name suggests, it throws whenever an input/output operation is abnormally terminated.
Does Java have destructors?
Garbage collector does the job working in the background
Java does not have destructors; but it has finalizers that does a similar job.
the syntax is
public void finalize(){
}
if an object has a finalizer, the method is invoked before the system garbage collects the object
What does the "abstract" keyword mean in front of a method? A class?
Abstract keyword declares either a method or a class.
If a method has a abstract keyword in front of it,it is called abstract method.Abstract method hs no body.It has only arguments and return type.Abstract methods act as placeholder methods that are implemented in the subclasses.
Abstract classes can’t be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class contains any abstract method it must be declared as abstract
Are Java constructors inherited ? If not, why not?
You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor of one of it’s superclasses. One of the main reasons is because you probably don’t want to overide the superclasses constructor, which would be possible if they were inherited. By giving the developer the ability to override a superclasses constructor you would erode the encapsulation abilities of the language.





Java threads question set
1. Do I need to use synchronized on setValue(int)? - It depends whether the method affects method local variables, class static or instance variables. If only method local variables are changed, the value is said to be confined by the method and is not prone to threading issues.
2. Do I need to use synchronized on setValue(int)? - It depends whether the method affects method local variables, class static or instance variables. If only method local variables are changed, the value is said to be confined by the method and is not prone to threading issues.
3. What is the SwingUtilities.invokeLater(Runnable) method for? - The static utility method invokeLater(Runnable) is intended to execute a new runnable thread from a Swing application without disturbing the normal sequence of event dispatching from the Graphical User Interface (GUI). The method places the runnable object in the queue of Abstract Windowing Toolkit (AWT) events that are due to be processed and returns immediately. The runnable object’s run() method is only called when it reaches the front of the queue. The deferred effect of the invokeLater(Runnable) method ensures that any necessary updates to the user interface can occur immediately, and the runnable work will begin as soon as those high priority events are dealt with. The invoke later method might be used to start work in response to a button click that also requires a significant change to the user interface, perhaps to restrict other activities, while the runnable thread executes.
4. What is the volatile modifier for? - The volatile modifier is used to identify variables whose values should not be optimized by the Java Virtual Machine, by caching the value for example. The volatile modifier is typically used for variables that may be accessed or modified by numerous independent threads and signifies that the value may change without synchronization.
5. Which class is the wait() method defined in? - The wait() method is defined in the Object class, which is the ultimate superclass of all others. So the Thread class and any Runnable implementation inherit this method from Object. The wait() method is normally called on an object in a multi-threaded program to allow other threads to run. The method should should only be called by a thread that has ownership of the object’s monitor, which usually means it is in a synchronized method or statement block.
6. Which class is the wait() method defined in? I get incompatible return type for my thread’s getState( ) method! - It sounds like your application was built for a Java software development kit before Java 1.5. The Java API Thread class method getState() was introduced in version 1.5. Your thread method has the same name but different return type. The compiler assumes your application code is attempting to override the API method with a different return type, which is not allowed, hence the compilation error.
7. What is a working thread? - A working thread, more commonly known as a worker thread is the key part of a design pattern that allocates one thread to execute one task. When the task is complete, the thread may return to a thread pool for later use. In this scheme a thread may execute arbitrary tasks, which are passed in the form of a Runnable method argument, typically execute(Runnable). The runnable tasks are usually stored in a queue until a thread host is available to run them. The worker thread design pattern is usually used to handle many concurrent tasks where it is not important which finishes first and no single task needs to be coordinated with another. The task queue controls how many threads run concurrently to improve the overall performance of the system. However, a worker thread framework requires relatively complex programming to set up, so should not be used where simpler threading techniques can achieve similar results.
8. What is a green thread? - A green thread refers to a mode of operation for the Java Virtual Machine (JVM) in which all code is executed in a single operating system thread. If the Java program has any concurrent threads, the JVM manages multi-threading internally rather than using other operating system threads. There is a significant processing overhead for the JVM to keep track of thread states and swap between them, so green thread mode has been deprecated and removed from more recent Java implementations. Current JVM implementations make more efficient use of native operating system threads.
9. What are native operating system threads? - Native operating system threads are those provided by the computer operating system that plays host to a Java application, be it Windows, Mac or GNU/Linux. Operating system threads enable computers to run many programs simultaneously on the same central processing unit (CPU) without clashing over the use of system resources or spending lots of time running one program at the expense of another. Operating system thread management is usually optimised to specific microprocessor architecture and features so that it operates much faster than Java green thread processing.










30 simple Java questions
1. How could Java classes direct program messages to the system console, but error messages, say to a file?
The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st =
new Stream (new
FileOutputStream ("techinterviews_com.txt"));
System.setErr(st);
System.setOut(st);
2. What’s the difference between an interface and an abstract class?
An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.
3. Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.
4. Explain the usage of the keyword transient?
This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).
5. How can you force garbage collection?
You can’t force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.
6. How do you know if an explicit object casting is needed?
If you assign a superclass object to a variable of a subclass’s data type, you need to do explicit casting. For example:
Object a;Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.
7. What’s the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
8. Can you write a Java class that could be used both as an applet as well as an application?
Yes. Add a main() method to the applet.
9. What’s the difference between constructors and other methods?
Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.
10. Can you call one constructor from another if a class has multiple constructors
Yes. Use this() syntax.
11. Explain the usage of Java packages.
This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.
12. If a class is located in a package, what do you need to change in the OS environment to be able to use it?
You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let’s say a class Employee belongs to a package com.xyz.hr; and is located in the file c:/dev/com.xyz.hr.Employee.java. In this case, you’d need to add c:/dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee
13. What’s the difference between J2SDK 1.5 and J2SDK 5.0?
There’s no difference, Sun Microsystems just re-branded this version.
14. What would you use to compare two String variables - the operator == or the method equals()?
I’d use the method equals() to compare the values of the Strings and the = = to check if two variables point at the same instance of a String object.
15. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception’s subclasses have to be caught first.
16. Can an inner class declared inside of a method access local variables of this method?
It’s possible if these variables are final.
17. What can go wrong if you replace && with & in the following code:
18. String a=null;
19. if (a!=null && a.length()>10)
{...}
A single ampersand here would lead to a NullPointerException.
20. What’s the main difference between a Vector and an ArrayList
Java Vector class is internally synchronized and ArrayList is not.
21. When should the method invokeLater()be used?
This method is used to ensure that Swing components are updated through the event-dispatching thread.
22. How can a subclass call a method or a constructor defined in a superclass?
Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass’s constructor.
23. What’s the difference between a queue and a stack?
Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule.
24. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?
Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.
25. What comes to mind when you hear about a young generation in Java?
Garbage collection.
26. What comes to mind when someone mentions a shallow copy in Java?
Object cloning.
27. If you’re overriding the method equals() of an object, which other method you might also consider?
hashCode()
28. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use: ArrayList or LinkedList?
ArrayList
29. How would you make a copy of an entire Java object with its state?
Have this class implement Cloneable interface and call its method clone().
30. How can you minimize the need of garbage collection and make the memory use more effective?
Use object pooling and weak object references.
31. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
If these classes are threads I’d consider notify() or notifyAll(). For regular classes you can use the Observer interface.
32. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
You do not need to specify any access level, and Java will use a default package access level.




64 Java questions for any job interview
1. Which
of the following are valid definitions of an application’s main( ) method?
a) public static void main();
b) public static void main( String args );
c) public static void main( String args[] );
d) public static void main( Graphics g );
e) public static boolean main( String args[] );
2. If MyProg.java were compiled as an
application and then run from the command line as:
java MyProg I like tests
what would be the value of args[ 1 ] inside
the main( ) method?
a) MyProg
b) "I"
c) "like"
d) 3
e) 4
f) null until a value is assigned

3. Which of the following are Java keywords?
a) array
b) boolean
c) Integer
d) protect
e) super
4. After the declaration:
char[] c = new char[100];
what is the value of c[50]?
a) 50
b) 49
c) ‘\u0000′
d) ‘\u0020′
e) " "
f) cannot be determined
g) always null until a value is
assigned
5. After the declaration:
int x;
the range of x is:
a) -231 to 231-1

b) -216 to 216 -
1
c) -232 to 232
d) -216 to 216
e) cannot be determined; it depends on
the machine
6. Which identifiers are valid?
a) _xpoints
b) r2d2
c) bBb$
d) set-flow
e) thisisCrazy
7. Represent the number 6 as a hexadecimal
literal.

8. Which of the following statements assigns "Hello Java" to the
String variable s?
a) String s = "Hello Java";
b) String s[] = "Hello Java";
c) new String s = "Hello Java";
d) String s = new String("Hello Java");
9. An integer, x has a binary value (using 1
byte) of 10011100. What is the binary value of z after these statements:
int y = 1 << 7;
int z = x & y;
a) 1000 0001
b) 1000 0000
c) 0000 0001
d) 1001 1101
e) 1001 1100
10. Which statements are accurate:
a) >>
performs signed shift while >>> performs an unsigned shift.
b) >>> performs a
signed shift while >> performs an unsigned shift.
c) << performs a
signed shift while <<< performs an insigned shift.
d) <<< performs a
signed shift while << performs an unsigned shift.
11. The statement …
String s = "Hello" +
"Java";
yields the same value for s as …
String s = "Hello";
String s2= "Java";
s.concat( s2 );
True
False
12. If you compile and execute an application
with the following code in its main() method:
String s = new String( "Computer" );

if( s == "Computer" )
System.out.println( "Equal A" );
if( s.equals( "Computer" ) )
System.out.println( "Equal B" );
a) It will not compile because the
String class does not support the = = operator.
b) It will compile and run, but
nothing is printed.
c) "Equal A" is the only
thing that is printed.
d) "Equal B" is the only
thing that is printed.
e) Both "Equal A" and
"Equal B" are printed.
13. Consider the two statements:
1. boolean passingScore = false && grade == 70;
2. boolean passingScore = false & grade == 70;
The expression
grade == 70
is evaluated:
a) in both 1 and 2
b) in neither 1 nor 2
c) in 1 but not 2
d) in 2 but not 1
e) invalid because false should be
FALSE
14. Given the variable declarations below:
byte myByte;
int myInt;
long myLong;
char myChar;
float myFloat;
double myDouble;
Which one of the following assignments would
need an explicit cast?
a) myInt
= myByte;
b) myInt
= myLong;
c) myByte
= 3;
d) myInt
= myChar;
e) myFloat
= myDouble;
f) myFloat
= 3;
g) myDouble
= 3.0;
15. Consider this class example:
class MyPoint
{ void myMethod()
{ int x, y;
x = 5; y = 3;
System.out.print( " ( " + x + ", " + y + " ) " );
switchCoords( x, y );
System.out.print( " ( " + x + ", " + y + " ) " );
}
void switchCoords( int x, int y )
{ int temp;
temp = x;
x = y;
y = temp;
System.out.print( " ( " + x + ", " + y + " ) " );
}
}
What is printed to standard output if myMethod()
is executed?
a) (5, 3) (5, 3) (5, 3)
b) (5, 3) (3, 5) (3, 5)
c) (5, 3) (3, 5) (5, 3)
16. To declare an array of 31 floating
point numbers representing snowfall for each day of March in Gnome, Alaska,
which declarations would be valid?
a) double
snow[] = new double[31];
b) double
snow[31] = new array[31];
c) double
snow[31] = new array;
d) double[]
snow = new double[31];
17. If arr[] contains only positive integer values, what does this
function do?
public int guessWhat( int arr[] )
{ int x= 0;
for( int i = 0; i < arr.length; i++ )
x = x < arr[i] ? arr[i] : x;
return x;
}
a) Returns the index of the highest
element in the array
b) Returns true/false if there
are any elements that repeat in the array
c) Returns how many even numbers are
in the array
d) Returns the highest element in the
array
e) Returns the number of question
marks in the array
18. Consider the code below:
arr[0] = new int[4];
arr[1] = new int[3];
arr[2] = new int[2];
arr[3] = new int[1];
for( int n = 0; n < 4; n++ )
System.out.println( /* what goes here? */ );
Which statement below, when inserted as the
body of the for loop, would print the number of values in each row?
a) arr[n].length();
b) arr.size;
c) arr.size-1;
d) arr[n][size];
e) arr[n].length;
19. If size = 4, triArraylooks like:

int[][] makeArray( int size)
{ int[][] triArray = new int[size] [];
int val=1;
for( int i = 0; i < triArray.length; i++ )
{ triArray[i] = new int[i+1];
for( int j=0; j < triArray[i].length; j++ )
{ triArray[i][j] = val++;
}
}
return triArray;
}

a)
1 2 3 4
5 6 7
8 9
10
b)
1 4 9 16
c)
1 2 3 4
d)
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
e)
1
2 3
4 5 6
7 8 9 10
20. Which of the following are legal
declarations of a two-dimensional array of integers?
a) int[5][5]a = new int[][];
b) int a = new int[5,5];
c) int[]a[] = new int[5][5];
d) int[][]a = new[5]int[5];
21. Which of the following are correct methods
for initializing the array "dayhigh" with 7 values?
a) int dayhigh = { 24, 23, 24, 25, 25, 23, 21 };
b) int dayhigh[] = { 24, 23, 24, 25, 25, 23, 21 };
c) int[] dayhigh = { 24, 23, 24, 25, 25, 23, 21 };
d) int dayhigh [] = new int[24, 23, 24, 25, 25, 23, 21];
e) int dayhigh = new[24, 23, 24, 25, 25, 23, 21];
22. If you want subclasses to access, but not to
override a superclass member method, what keyword should precede the name of
the superclass method?

23. If you want a member variable to not be accessible outside the current
class at all, what keyword should precede the name of the variable when
declaring it?

24. Consider the code below:

public static void main( String args[] )
{ int a = 5;
System.out.println( cube( a ) );
}
int cube( int theNum )
{
return theNum * theNum * theNum;
}

What will happen when you attempt to compile and run this code?
a) It will not compile because cube is
already defined in the java.lang.Math class.
b) It will not compile because cube is
not static.
c) It will compile, but throw an
arithmetic exception.
d) It will run perfectly and print
"125" to standard output.
25. Given the variables defined below:
int one = 1;
int two = 2;
char initial = ‘2′;
boolean flag = true;
Which of the following are valid?
a) if(
one ){}
b) if(
one = two ){}
c) if(
one == two ){}
d) if(
flag ){}
e) switch(
one ){}
f) switch(
flag ){}
g) switch(
initial ){}
26. If val = 1 in the code below:

switch( val )
{ case 1: System.out.print( "P" );
case 2:
case 3: System.out.print( "Q" );
break;
case 4: System.out.print( "R" );
default: System.out.print( "S" );
}

Which values would be printed?
a) P
b) Q
c) R
d) S
27. Assume that val has been defined as an int for the
code below:

if( val > 4 )
{ System.out.println( "Test A" );
}
else if( val > 9 )
{ System.out.println( "Test B" );
}
else System.out.println( "Test C" );

Which values of val will
result in "Test C" being printed:
a) val < 0
b) val between 0 and 4
c) val between 4 and 9
d) val > 9
e) val = 0
f) no values for val will be satisfactory
28. What exception might a wait()
method throw?

29. For the code:

m = 0;
while( m++ < 2 )
System.out.println( m );

Which of the following are printed to
standard output?
a) 0
b) 1
c) 2
d) 3
e) Nothing and an exception
is thrown
30. Consider the code fragment below:

outer: for( int i = 1; i <3; i++ )
{ inner: for( j = 1; j < 3; j++ )
{ if( j==2 )
continue outer;
System.out.println( "i = " +i ", j = " + j );
}
}

Which of the following would be printed to standard output?
a) i = 1, j = 1
b) i = 1, j = 2
c) i = 1, j = 3
d) i = 2, j = 1
e) i = 2, j = 2
f) i = 2, j = 3
g) i = 3, j = 1
h) i = 3, j = 2
31. Consider the code below:
void myMethod()
{ try
{
fragile();
}
catch( NullPointerException npex )
{
System.out.println( "NullPointerException thrown " );
}
catch( Exception ex )
{
System.out.println( "Exception thrown " );
}
finally
{
System.out.println( "Done with exceptions " );
}
System.out.println( "myMethod is done" );
}
What is printed to standard output if fragile()
throws an IllegalArgumentException?
a) "NullPointerException thrown"
b) "Exception thrown"
c) "Done with exceptions"
d) "myMethod is done"
e) Nothing is printed
32. Consider the following code sample:
class Tree{}
class Pine extends Tree{}
class Oak extends Tree{}
public class Forest
{ public static void main( String[] args )
{ Tree tree = new Pine();

if( tree instanceof Pine )
System.out.println( "Pine" );

if( tree instanceof Tree )
System.out.println( "Tree" );

if( tree instanceof Oak )
System.out.println( "Oak" );

else System.out.println( "Oops" );
}
}
Select all choices that will be printed:
a) Pine
b) Tree
c) Forest
d) Oops
e) (nothing printed)
33. Consider the classes defined below:
import java.io.*;
class Super
{
int methodOne( int a, long b ) throws IOException
{ // code that performs some calculations
}
float methodTwo( char a, int b )
{ // code that performs other calculations
}
}
public class Sub extends Super
{

}
Which of the following are legal method
declarations to add to the class Sub? Assume that each method is the only one being added.
a) public static void main( String args[] ){}
b) float methodTwo(){}
c) long methodOne( int c, long d ){}
d) int methodOne( int c, long d ) throws
ArithmeticException{}
e) int methodOne( int c, long d ) throws
FileNotFoundException{}
34. Assume that Sub1 and Sub2 are both
subclasses of class Super.
Given the declarations:
Super super = new Super();
Sub1 sub1 = new Sub1();
Sub2 sub2 = new Sub2();
Which statement best describes the result of
attempting to compile and execute the following statement:
super = sub1;
a) Compiles and definitely legal at
runtime
b) Does not compile
c) Compiles and may be illegal at
runtime
35. For the following code:
class Super
{ int index = 5;
public void printVal()
{ System.out.println( "Super" );
}
}
class Sub extends Super
{ int index = 2;
public void printVal()
{ System.out.println( "Sub" );
}
}
public class Runner
{ public static void main( String argv[] )
{ Super sup = new Sub();
System.out.print( sup.index + "," );
sup.printVal();
}
}
What will be printed to standard output?
a) The code will not compile.
b) The code compiles and "5,
Super" is printed to standard output.
c) The code compiles and "5,
Sub" is printed to standard output.
d) The code compiles and "2,
Super" is printed to standard output.
e) The code compiles and "2,
Sub" is printed to standard output.
f) The code compiles, but throws an
exception.
36. How many objects are eligible for garbage
collection once execution has reached the line labeled Line A?
String name;
String newName = "Nick";
newName = "Jason";
name = "Frieda";
String newestName = name;
name = null;
//Line A
a) 0
b) 1
c) 2
d) 3
e) 4
37. Which of the following statements about
Java’s garbage collection are true?
a) The garbage
collector can be invoked explicitly using a Runtime object.
b) The finalize method is
always called before an object is garbage collected.
c) Any class that includes
a finalize method should invoke its superclass’ finalize method.
d) Garbage collection
behavior is very predictable.
38. What line of code would begin execution of a
thread named myThread?

39. Which methods are required to implement the interface Runnable.
a) wait()
b) run()
c) stop()
d) update()
e) resume()
40. What class defines the wait() method?

41. For what reasons might a thread stop execution?
a) A thread with higher priority
began execution.
b) The thread’s wait() method was invoked.
c) The thread invoked its yield() method.
d) The thread’s pause() method was invoked.
e) The thread’s sleep() method was invoked.
42. Which method below can change a String object, s ?
a) equals( s )
b) substring(
s )
c) concat(
s )
d) toUpperCase(
s )
e) none of the above will change s
43. If s1 is declared as:
String s1 =
"phenobarbital";
What will be the value of s2 after
the following line of code:
String s2 = s1.substring( 3, 5 );
1. a) null
b) "eno"
c) "enoba"
d) "no"
44. What method(s)
from the java.lang.Math class might method() be if the statement
method( -4.4 )
== -4;
is true.
a)
round()
b) min()
c) trunc()
d) abs()
e) floor()
f) ceil()
45. Which methods
does java.lang.Math include for trigonometric computations?
a)
sin()
b) cos()
c) tan()
d) aSin()
e) aCos()
f) aTan()
g) toDegree()
46. This piece of
code:
TextArea ta =
new TextArea( 10, 3 );
Produces (select
all correct statements):
a)
a TextArea with 10 rows and up to 3 columns
b) a TextArea with a
variable number of columns not less than 10 and 3 rows
c) a TextArea that may not
contain more than 30 characters
d) a TextArea that can be
edited
47. In the list below, which subclass(es) of Component cannot be directly
instantiated:
a)
Panel
b) Dialog
c) Container
d) Frame
48. Of the five Component methods listed below, only one is also a method
of the class MenuItem. Which one?
a)
setVisible(
boolean b )
b) setEnabled( boolean b )
c) getSize()
d) setForeground( Color c )
e) setBackground( Color c )
49. If a font with
variable width is used to construct the string text for a column, the
initial size of the column is:
a)
determined by the number of characters in the string, multiplied by the
width of a character in this font
b) determined by the number of
characters in the string, multiplied by the average width of a character
in this font
c) exclusively determined by the
number of characters in the string
d) undetermined
50. Which of the
following methods from the java.awt.Graphics class would be used to draw the outline of a
rectangle with a single method call?
a)
fillRect()
b)
drawRect()
c) fillPolygon()
d) drawPolygon()
e) drawLine()

51. The Container methods add( Component comp ) and add( String name, Component comp) will throw an IllegalArgumentException
if comp is a:

a) button
b) list
c) window
d) textarea
e) container that contains
this container
52. Of the following AWT classes, which one(s) are responsible for implementing the components layout?

a)
LayoutManager
b) GridBagLayout
c) ActionListener
d) WindowAdapter
e) FlowLayout
53. A component that should resize vertically but not horizontally should
be placed in a:
a)
BorderLayout in the North or South location
b) FlowLayout as the first
component
c) BorderLayout in the
East or West location
d) BorderLayout in the
Center location
e) GridLayout
54. What type of object is the parameter for all methods of the
MouseListener interface?

55. Which of the following statements about event handling in JDK 1.1 and
later are true?
a)
A class can implement multiple listener interfaces
b) If a class implements a listener
interface, it only has to overload the methods it uses
c) All of the MouseMotionAdapter class
methods have a void return type.
56. Which of the
following describe the sequence of method calls that result in a component
being redrawn?
a)
invoke paint() directly
b) invoke update which
calls paint()
c) invoke repaint() which invokes update(),
which in turn invokes paint()
d) invoke repaint() which invokes paint directly
57. Which of these is a correct fragment within the
web-app element of deployment descriptor. Select the two correct
answer.
A.
404
/error.jsp

B.
mypackage.MyException
404
/error.jsp

C. mypackage.MyException
404

D.
mypackage.MyException
/error.jsp

58. A
bean with a property color is loaded using the following statement
id="fruit" class="Fruit"/>
Which of the following statements may be used to set the of color
property of the bean. Select the one correct answer.
1. id="fruit" property="color" value="white"/>
2. name="fruit" property="color" value="white"/>
3. name="fruit" property="color" value="white"/>
4. name="fruit" property="color" value="white">
5. name="fruit" property="color" value="white"/>
6.
property="color" value="white">
59. What gets printed when the following JSP code is
invoked in a browser. Select the one correct answer.
<%=
if(Math.random() < 0.5){ %>
hello
<%=
} else { %>
hi
<%=
} %>
a.
The browser will print either hello or
hi based upon the return value of random.
b.
The string hello will always get
printed.
c.
The string hi will always get printed.
d.
The JSP file will not compile.
60. Given the following web application deployment descriptor:
MyServlet
...


myServlet
*.jsp

Which statements are true?
• 1) servlet-mapping element should be inside servlet element
• 2) url-pattern can’t be defined that way.
• 3) if you make the http call:
href="http://host/servlet/Hello.do">http://host/Hello.jsp the servlet container will execute MyServlet.
• 4) It would work with any extension excepting jsp,html,htm
61.Name the class that includes the getSession method that is used to get the HttpSession object.
A. HttpServletRequest
B. HttpServletResponse
C. SessionContext
D. SessionConfig
62. What will be the result of running the following jsp
file taking into account that the Web server has just been started and this is
the first page loaded by the server?

<%=
request.getSession(false).getId() %>

1)It won’t
compile
2)It will
print the session id.
3)It will produce a NullPointerException as the
getSession(false) method’s call returns null, cause no session had been
created.
4)It will
produce an empty page.
63. The
page directive is used to convey information about the page to JSP container.
Which of these are legal syntax of page directive. Select the two correct
statement
A. <% page info="test page" %>
B. <%@ page info="test page"
session="false"%>
C. <%@ page session="true" %>
D. <%@ page
isErrorPage="errorPage.jsp" %>
E. <%@ page isThreadSafe=true %>
64. Which
of the following are methods of the Cookie Class?
1) setComment
2) getVersion
3) setMaxAge
4) getSecure












Java interview questions and answers
1. What is garbage collection? What is the process that is responsible for doing that in java? - Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process
2. What kind of thread is the Garbage collector thread? - It is a daemon thread.
3. What is a daemon thread? - These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly.
4. How will you invoke any external process in Java? - Runtime.getRuntime().exec(….)
5. What is the finalize method do? - Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected.
6. What is mutable object and immutable object? - If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …)
7. What is the basic difference between string and stringbuffer object? - String is an immutable object. StringBuffer is a mutable object.
8. What is the purpose of Void class? - The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.
9. What is reflection? - Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.
10. What is the base class for Error and Exception? - Throwable
11. What is the byte range? -128 to 127
12. What is the implementation of destroy method in java.. is it native or java code? - This method is not implemented.
13. What is a package? - To group set of classes into a single unit is known as packaging. Packages provides wide namespace ability.
14. What are the approaches that you will follow for making a program very efficient? - By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more.
15. What is a DatabaseMetaData? - Comprehensive information about the database as a whole.
16. What is Locale? - A Locale object represents a specific geographical, political, or cultural region
17. How will you load a specific locale? - Using ResourceBundle.getBundle(…);
18. What is JIT and its use? - Really, just a very fast compiler… In this incarnation, pretty much a one-pass compiler — no offline computations. So you can’t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, it’s an on-line problem.
19. Is JVM a compiler or an interpreter? - Interpreter
20. When you think about optimization, what is the best way to findout the time/memory consuming process? - Using profiler
21. What is the purpose of assert keyword used in JDK1.4.x? - In order to validate certain expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing.
22. How will you get the platform dependent values like line separator, path separator, etc., ? - Using Sytem.getProperty(…) (line.separator, path.separator, …)
23. What is skeleton and stub? what is the purpose of those? - Stub is a client side representation of the server, which takes care of communicating with the remote server. Skeleton is the server side representation. But that is no more in use… it is deprecated long before in JDK.
24. What is the final keyword denotes? - final keyword denotes that it is the final implementation for that method or variable or class. You can’t override that method/variable/class any more.
25. What is the significance of ListIterator? - You can iterate back and forth.
26. What is the major difference between LinkedList and ArrayList? - LinkedList are meant for sequential accessing. ArrayList are meant for random accessing.
27. What is nested class? - If all the methods of a inner class is static then it is a nested class.
28. What is inner class? - If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.
29. What is composition? - Holding the reference of the other class within some other class is known as composition.
30. What is aggregation? - It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation.
31. What are the methods in Object? - clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString
32. Can you instantiate the Math class? - You can’t instantiate the math class. All the methods in this class are static. And the constructor is not public.
33. What is singleton? - It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods … }
34. What is DriverManager? - The basic service to manage set of JDBC drivers.
35. What is Class.forName() does and how it is useful? - It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( “class-instance”.newInstance() ).
36. Inq adds a question: Expain the reason for each keyword of
public static void main(String args[])



































General Java Servlet questions
1. What is the servlet?
2. What are the JSP atrributes?
3. What is the need of super.init(config) in servlets?
4. How to know whether we have to use jsp or servlet in our project?
5. Can we call destroy() method on servlets from service method?
6. What is the Servlet Interface?
7. What is the difference between GenericServlet and HttpServlet?
8. How we can check in particular page the session will be alive or not?
9. What is the importance of deployment descriptor in servlet?
10. When we increase the buffer size in our project using page directive attribute ‘buffer’ what changes we observe?
11. What is the difference between ServetConfig and ServletContext..?
12. When a servlet accepts a call from a client, it receives two objects. What are they?
13. What are the differences between GET and POST service methods?
14. In which conditions we have to use the ServletContext?
15. What methods will be called in which order?((i.e)service(),doget(),dopost())
16. Servlet is Java class. Then why there is no constructor in Servlet? Can we write the constructor in Servlet
17. What is the use of ServletConfig and ServletContext..?
18. What information that the ServletRequest interface allows the servlet access to?
19. What is the difference between ServletContext and ServletConfig?
20. When do you have action=get?
21. What is a Singleton class. How do you write it?
22. What is difference between sendRedirect() and forward()..? Which one is faster then other and which works on server?
23. What information that the ServletResponse interface gives the servlet methods for replying to the client?
24. Can I invoke a JSP error page from a servlet?
25. Can a init(ServletConfig config) method be overrided in servlets?
26. How many ServletConfig and servlet context objects are present in one application?
27. Do we have a constructor in servlet? can we explictly provide a constructor in servlet programme as in java program?
28. What are the uses of Servlets?
29. Can I just abort processing a JSP?
30. Is servlet is used to create a dynamic webpage or Static webpage or both?
31. If you want a servlet to take the same action for both GET and POST request, what should you do?
32. What is the difference between JSP and SERVLETS?
33. What are the advantages using servlets than using CGI?
34. What is a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or synchronization?
35. We have two applications in that we have two servlets each.How they(servlets) communicate with each other?
36. How the server will know (i.e) when it can invoke init, service,destroy methods of servlet life cycle?
37. How to communicate between two servlets?
38. What is the difference between servlets and applets?
39. How will u pass the argument from one servlet to another servlet?
40. What method used to add a jsp to the servlet?
41. How HTTP Servlet handles client requests?
42. How to get one Servlet’s Context Information in another Servlet?
43. Difference between single thread and multi thread model servlet
44. What is the super class of All servlets?
45. How are Servlet Applet communication achieved?
46. What is servlet context and what it takes actually as parameters?
47. What is the servlet life cycle?
48. Types of Servlets?
49. Why is that we deploy servlets in a webserver.What exactly is a webserver?
50. Which code line must be set before any of the lines that use the PrintWriter?















Newbie Java questions
1. If Runnable interface is better than Thread class, than why we are using Thread class? What is the need for Thread class?
2. Why we are calling System.gc() method to garbage collection of unused object, if garbage collection is automatically done in Java by daemon thread in background process with regular interval?
3. What is the significance of Marker interface? Why are we using, even though it has no method?
4. Why we are always doing rs.next() in first line of while loop in retrieving data from database through result set?
5. Please give me the details of synchronization? And which are the methods and elements used in it and why only that methods and variables?
6. Why we are not using Java in real time based application, but instead we are using C or C++?
7. Detail difference between 4 types of driver and their use in different different applications?
8. Is Java code with native methods platform-independent?
9. Why is the compiler platform-independent, while JVM is platform-dependent?\
10. Mention different type of compilers and interpreters in Java?













Simple Java questions
1. Meaning - Abstract classes, abstract methods
2. Difference - Java,C++
3. Difference between == and equals method
4. Explain Java security model
5. Explain working of Java Virtual Machine (JVM)
6. Difference: Java Beans, Servlets
7. Difference: AWT, Swing
8. Disadvantages of Java
9. What is BYTE Code ?
10. What gives java it’s “write once and run anywhere” nature?
11. Does Java have “goto”?
12. What is the meaning of “final” keyword?
13. Can I create final executable from Java?
14. Explain Garbage collection mechanism in Java
15. Why Java is not 100% pure object oriented language?
16. What are interfaces? or How to support multiple inhertance in Java?
17. How to use C++ code in Java Program?
18. Difference between “APPLET” and “APPLICATION”













J2EE interview questions and answers
1. What makes J2EE suitable for distributed multitiered Applications?
- The J2EE platform uses a multitiered distributed application model. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. The J2EE application parts are:
o Client-tier components run on the client machine.
o Web-tier components run on the J2EE server.
o Business-tier components run on the J2EE server.
o Enterprise information system (EIS)-tier software runs on the EIS server.
2. What is J2EE? - J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications.
3. What are the components of J2EE application?
- A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:
1. Application clients and applets are client components.
2. Java Servlet and JavaServer Pages technology components are web components.
3. Enterprise JavaBeans components (enterprise beans) are business components.
4. Resource adapter components provided by EIS and tool vendors.
4. What do Enterprise JavaBeans components contain? - Enterprise JavaBeans components contains Business code, which is logic
that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program.
5. Is J2EE application only a web-based? - No, It depends on type of application that client wants. A J2EE application can be web-based or non-web-based. if an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a servlet running in the web tier.
6. Are JavaBeans J2EE components? - No. JavaBeans components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture.
7. Is HTML page a web component? - No. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either.
8. What can be considered as a web component? - J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content.
9. What is the container? - Containers are the interface between a component and the low-level platform specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container.
10. What are container services? - A container is a runtime support of a system-level entity. Containers provide components with services such as lifecycle management, security, deployment, and threading.
11. What is the web container? - Servlet and JSP containers are collectively referred to as Web containers. It manages the execution of JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE server.
12. What is Enterprise JavaBeans (EJB) container? - It manages the execution of enterprise beans for J2EE applications.
Enterprise beans and their container run on the J2EE server.
13. What is Applet container? - IManages the execution of applets. Consists of a Web browser and Java Plugin running on the client together.
14. How do we package J2EE components? - J2EE components are packaged separately and bundled into a J2EE application for deployment. Each component, its related files such as GIF and HTML files or server-side utility classes, and a deployment descriptor are assembled into a module and added to the J2EE application. A J2EE application is composed of one or more enterprise bean,Web, or application client component modules. The final enterprise solution can use one J2EE application or be made up of two or more J2EE applications, depending on design requirements. A J2EE application and each of its modules has its own deployment descriptor. A deployment descriptor is an XML document with an .xml extension that describes a component’s deployment settings.
15. What is a thin client? - A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications.
16. What are types of J2EE clients? - Following are the types of J2EE clients:
o Applets
o Application clients
o Java Web Start-enabled rich clients, powered by Java Web Start technology.
o Wireless clients, based on Mobile Information Device Profile (MIDP) technology.
17. What is deployment descriptor? - A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a component’s deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizations
for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly.
18. What is the EAR file? - An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file.
19. What is JTA and JTS? - JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesn’t call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your application uses to control transaction. and JTS is a low level transaction interface and ejb uses behind the scenes (client code doesn’t directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA.
20. What is JAXP? - JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations.
21. What is J2EE Connector? - The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource adapter. Note: A resource adapter is a software component that allows J2EE application components to access and interact with the underlying resource manager. Because a resource adapter is specific to its resource manager, there is typically a different resource adapter for each type of database or enterprise information system.
22. What is JAAP? - The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization.
23. What is Java Naming and Directory Service? - The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and
directory services such as LDAP, NDS, DNS, and NIS.
24. What is Struts? - A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between.
25. How is the MVC design pattern used in Struts framework? - In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an application’s business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans.











JavaScript interview questions and answers
1. What’s relationship between JavaScript and ECMAScript? - ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3.
2. What are JavaScript types? - Number, String, Boolean, Function, Object, Null, Undefined.
3. How do you convert numbers between different bases in JavaScript? - Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16);
4. What does isNaN function do? - Return true if the argument is not a number.
5. What is negative infinity? - It’s a number in JavaScript, derived by dividing negative number by zero.
6. What boolean operators does JavaScript support? - &&, || and !
7. What does "1"+2+4 evaluate to? - Since 1 is a string, everything is a string, so the result is 124.
8. How about 2+5+"8"? - Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.
9. What looping structures are there in JavaScript? - for, while, do-while loops, but no foreach.
10. How do you create a new object in JavaScript? - var obj = new Object(); or var obj = {};
11. How do you assign object properties? - obj["age"] = 17 or obj.age = 17.
12. What’s a way to append a value to an array? - arr[arr.length] = value;
13. What is this keyword? - It refers to the current object.










Core Java Interview Questions
1 Q
Why threads block or enters to waiting state on I/O?
A Threads enters to waiting state or block on I/O because other threads can execute while the I/O operations are performed. 2 Q What are transient variables in java? A
Transient variables are variable that cannot be serialized.
3 Q How Observer and Observable are used? A
Subclass of Observable class maintain a list of observers. Whenever an Observable object is updated, it invokes the update() method of each of its observers to notify the observers that it has a changed state. An observer is any object that implements the interface Observer.
4 Q What is synchronization A
Synchronization is the ability to control the access of multiple threads to shared resources. Synchronization stops multithreading. With synchronization , at a time only one thread will be able to access a shared resource.
5 Q What is List interface ? A List is an ordered collection of objects. 6 Q What is a Vector A Vector is a grow able array of objects. 7 Q What is the difference between yield() and sleep()? A
When a object invokes yield() it returns to ready state. But when an object invokes sleep() method enters to not ready state.
8 Q What are Wrapper Classes ? A They are wrappers to primitive data types. They allow us to access primitives as objects. 9 Q Can we call finalize() method ? A Yes. Nobody will stop us to call any method , if it is accessible in our class. But a garbage collector cannot call an object's finalize method if that object is reachable. 10 Q
What is the difference between time slicing and preemptive scheduling ?
A
In preemptive scheduling, highest priority task continues execution till it enters a not running state or a higher priority task comes into existence. In time slicing, the task continues its execution for a predefined period of time and reenters the pool of ready tasks.
11 Q What is the initial state of a thread when it is created and started? A The thread is in ready state. 12 Q Can we declare an anonymous class as both extending a class and implementing an interface? A
No. An anonymous class can extend a class or implement an interface, but it cannot be declared to do both
13 Q What are the differences between boolean & operator and & operator A
When an expression containing the & operator is evaluated, both operands are evaluated. And the & operator is applied to the operand. When an expression containing && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then only the second operand is evaluated otherwise the second part will not get executed. && is also called short cut and.
14 Q What is the use of the finally block? A
Finally is the block of code that executes always. The code in finally block will execute even if an exception is occurred. finally will not execute when the user calls System.exit().
15 Q What is an abstract method ? A
An abstract method is a method that don't have a body. It is declared with modifier abstract.













SP, Servlets Interview question

Q What is the difference between JSP and Servlets ?
A JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc.

Q What is difference between custom JSP tags and beans?
A Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components: the tag handler class that defines the tag's behavior ,the tag library descriptor file that maps the XML element names to the tag implementations and the JSP file that uses the tag library

JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags

Custom tags and beans accomplish the same goals -- encapsulating complex behavior into simple and accessible forms. There are several differences:

Custom tags can manipulate JSP content; beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans. Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page. Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

Q What are the different ways for session tracking?
A Cookies, URL rewriting, HttpSession, Hidden form fields

Q What mechanisms are used by a Servlet Container to maintain session information?
A Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information

Q Difference between GET and POST
A In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL.

In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is more secure.

Q What is session?
A The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests. The session is stored on the server.

Q What is servlet mapping?
A The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets.

Q What is servlet context ?
A The servlet context is an object that contains a information about the Web application and container. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use.

Q What is a servlet ?
A servlet is a java program that runs inside a web container.

Q Can we use the constructor, instead of init(), to initialize servlet?
A Yes. But you will not get the servlet specific things from constructor. 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 constructor 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.

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

Q How do I include static files within a JSP page?
A Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase.

Q How can I implement a thread-safe JSP page?
A You can make your JSPs thread-safe adding the directive <%@ page isThreadSafe="false" % > within your JSP page.

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

Q What are the lifecycle

of JSP?

A When presented with JSP page the JSP engine does the following 7 phases.
o Page translation: -page is parsed, and a java file which is a servlet is created.
o Page compilation: page is compiled into a class file
o Page loading : This class file is loaded.
o Create an instance :- Instance of servlet is created
o jspInit() method is called
o _jspService is called to handle service calls
o _jspDestroy is called to destroy it when the servlet is not required.

Q What are context initialization parameters?
A Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application.

Q What is a Expression?
A Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed. This will be included in the service method of the generated servlet.

Q What is a Declaration?
A It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language used in the JSP file. This will be included in the declaration section of the generated servlet.

Q What is a Scriptlet?
A A scriptlet can contain any number of language statements, variable or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a . Generally a scriptlet can contain any java code that are valid inside a normal java method. This will become the part of generated servlet's service method.





























Enterprise JavaBeans (EJB) questions

In this section we are offering interview questions for EJB only. if you need interview questions for any other java related technologies , please check the relevant sections.
1 Q What is EJB? A
Enterprise JavaBeans (EJB) technology is the server-side component architecture for the Java 2 Platform, Enterprise Edition (J2EE) platform. EJB technology enables rapid and simplified development of distributed, transactional, secure and portable applications
based on Java technology.
2 Q What are the different type of Enterprise JavaBeans ? A There are 3 types of enterprise beans, namely: Session bean, Entity beans and Message driven beans. 3 Q What is Session Bean ? A
Session bean represents a single client inside the J2EE server. To access the application deployed in the server the client invokes methods on the session bean. The session bean performs the task shielding the client from the complexity of the business logic.

Session bean components implement the javax.ejb.SessionBean interface. Session beans can act as agents modeling workflow or provide access to special transient business services. Session beans do not normally represent persistent business concepts. A session bean corresponds to a client server session. The session bean is created when a client requests some query on the database and exists as long as the client server session exists.
4 Q What are different types of session bean ? A
There are two types of session beans, namely: Stateful and Stateless.
5 Q What is a Stateful Session bean? A
Stateful session bean maintain the state of the conversation between the client and itself. When the client invokes a method on the bean the instance variables of the bean may contain a state but only for the duration of the invocation.

A stateful session bean is an enterprise bean (EJB component) that acts as a server-side extension of the client that uses it. The stateful session bean is created by a client and will work for only that client until the client connection is dropped or the bean is explicitly removed. The stateful session bean is EJB component that implements the javax.ejb.SessionBean interface and is deployed with the declarative attribute "stateful". Stateful session beans are called "stateful" because they maintain a conversational state with the client. In other words, they have state or instance fields that can be initialized and changed by the client with each method invocation. The bean can use the conversational state as it process business methods invoked by the client.
6 Q What is stateless session bean ? A
Stateless session beans are of equal value for all instances of the bean. This means the container can assign any bean to any client, making it very scalable.

A stateless session bean is an enterprise bean that provides a stateless service to the client. Conceptually, the business methods on a stateless session bean are similar to procedural applications or static methods; there is no instance state, so all the data needed to execute the method is provided by the method arguments. The stateless session bean is an EJB component that implements the javax.ejb.SessionBean interface and is deployed with the declarative attribute "stateless". Stateless session beans are called "stateless" because they do not maintain conversational state specific to a client session. In other words, the instance fields in a stateless session bean do not maintain data relative to a client session. This makes stateless session beans very lightweight and fast, but also limits their behavior. Typically an application requires less number of stateless beans compared to stateful beans.
7 Q What is an Entity Bean? A
An entity bean represents a business object in a persistent storage mechanism. An entity bean typically represents a table in a relational database and each instance represents a row in the table. Entity bean differs from session bean by: persistence, shared access, relationship and primary key. T
8 Q What are different types of entity beans? A There are two types of entity beans available. Container Managed Persistence (CMP) , Bean managed persistence (BMP). 9 Q What is CMP (Container Managed Persistence) ? A
The term container-managed persistence means that the EJB container handles all database access required by the entity bean. The bean's code contains no database access (SQL) calls. As a result, the bean's code is not tied to a specific persistent storage mechanism (database). Because of this flexibility, even if you redeploy the same entity bean on different J2EE servers that use different databases, you won't need to modify or recompile the bean's code. So, your entity beans are more portable.
10 Q What is BMP (Bean managed persistence) ? A
Bean managed persistence (BMP) occurs when the bean manages its persistence. Here the bean will handle all the database access. So the bean's code contains the necessary SQLs calls. So it is not much portable compared to CMP. Because when we are changing the database we need to rewrite the SQL for supporting the new database.
11 Q What is abstract schema ? A In order to generate the data access calls, the container needs information that you provide in the entity bean's abstract schema. It is a part of Deployment Descriptor. It is used to define the bean's persistent fields and relation ships. 12 Q When we should use Entity Bean ? A
When the bean represents a business entity, not a procedure. we should use an entity bean. Also when the bean's state must be persistent we should use an entity bean. If the bean instance terminates or if the J2EE server is shut down, the bean's state still exists in persistent storage (a database).
13 Q When to Use Session Beans ? A
At any given time, only one client has access to the bean instance. The state of the bean is not persistent, existing only for a short period (perhaps a few hours). The bean implements a web service. Under all the above circumstances we can use session beans.
14 Q When to use Stateful session bean? A
The bean's state represents the interaction between the bean and a specific client. The bean needs to hold information about the client across method invocations. The bean mediates between the client and the other components of the application, presenting a simplified view to the client. Under all the above circumstances we can use a stateful session bean.
15 Q When to use a stateless session bean? A
The bean's state has no data for a specific client. In a single method invocation, the bean performs a generic task for all clients. For example, you might use a stateless session bean to send an email that confirms an online order. The bean fetches from a database a set of read-only data that is often used by clients. Such a bean, for example, could retrieve the table rows that represent the products that are on sale this month. Under all the above circumstance we can use a stateless session bean.










JMS Interview Questions
Here you can find out a list of interview questions for JMS. These questions are often asked by the interviewer for JMS (Java Message service) interview. We put our maximum effort to make this answers error free. But still there might be some errors. If you feel out any answer given for any question is wrong, please, please inform us by clicking on report bug button provided below.

In this section we are offering interview questions for JMS only. if you need interview questions for any other java related technologies , please check the relevant sections.
1 Q What is JMS? A The Java Message Service (JMS) API is a messaging standard that allows application components based on the Java 2 Platform, Enterprise Edition (J2EE) to create, send, receive, and read messages. It enables distributed communication that is loosely coupled, reliable, and asynchronous
2 Q What type messaging is provided by JMS A Both synchronous and asynchronous are provided by JMS.
3 Q What is messaging? A Messaging is a mechanism by which data can be passed from one application to another application.
4 Q What are the advantages of JMS? A One of the principal advantages of JMS messaging is that it's asynchronous. Thus not all the pieces need to be up all the time for the application to function as a whole.
5 Q What is synchronous messaging? A Synchronous messaging involves a client that waits for the server to respond to a message. So if one end is down the entire communication will fail. 6 Q What is asynchronous messaging? A Asynchronous messaging involves a client that does not wait for a message from the server. An event is used to trigger a message from a server. So even if the client is down , the messaging will complete successfully.
7 Q What is the difference between queue and topic ? A A topic is typically used for one to many messaging , while queue is used for one-to-one messaging. Topic .e. it supports publish subscribe model of messaging where queue supports Point to Point Messaging.
8 Q What is Stream Message ? A Stream messages are a group of java primitives. It contains some convenient methods for reading the data. However Stream Message prevents reading a long value as short. This is so because the Stream Message also writes the type information along with the value of the primitive type and enforces a set of strict conversion rules which actually prevents reading of one primitive type as another.
9 Q What is Map message?
A map message contains name value Pairs. The values can be of type primitives and its wrappers. The name is a string.
10 Q What is text message?
A Text messages contains String messages (since being widely used, a separate messaging Type has been supported) . It is useful for exchanging textual data and complex character data like XML.
11 Q What is object message ? A Object message contains a group of serializeable java object. So it allows exchange of Java objects between applications. sot both the applications must be Java applications.
12 Q What is Byte Message ? A Byte Messages contains a Stream of uninterrupted bytes. Byte Message contains an array of primitive bytes in it's payload. Thus it can be used for transfer of data between two applications in their native format which may not be compatible with other Message types. It is also useful where JMS is used purely as a transport between two systems and the message payload is opaque to the JMS client.
13 Q What is the difference between Byte Message and Stream Message? A Bytes Message stores data in bytes. Thus the message is one contiguous stream of bytes. While the Stream Message maintains a boundary between the different data types stored because it also stores the type information along with the value of the primitive being stored. Bytes Message allows data to be read using any type. Thus even if your payload contains a long value, you can invoke a method to read a short and it will return you something. It will not give you a semantically correct data but the call will succeed in reading the first two bytes of data. This is strictly prohibited in the Stream Message. It maintains the type information of the data being stored and enforces strict conversion rules on the data being read.
14 Q What is the Role of the JMS Provider? A The JMS provider handles security of the messages, data conversion and the client triggering. The JMS provider specifies the level of encryption and the security level of the message, the best data type for the non-JMS client.
15 Q What are the different parts of a JMS message ? A A JMS message contains three parts. a header, an optional properties and an optional body.












JDBC Interview Questions
Here you can find out a list of interview questions for JDBC. These questions are often asked by the interviewer for JDBC (Java Database Connectivity) interview. We put our maximum effort to make this answers error free. But still there might be some errors. If you feel out any answer given for any question is wrong, please, please inform us by clicking on report bug button provided below.

In this section we are offering interview questions for JDBC only. if you need interview questions for any other java related technologies , please check the relevant sections.
1 Q What is JDBC? A
JDBC technology is an API (included in both J2SE and J2EE releases) that provides cross-DBMS connectivity to a wide range of SQL databases and access to other tabular data sources, such as spreadsheets or flat files. With a JDBC technology-enabled driver, you can connect all corporate data even in a heterogeneous environment
2 Q What are stored procedures? A
A stored procedure is a set of statements/commands which reside in the database. The stored procedure is precompiled. Each Database has it's own stored procedure language,
3 Q What is JDBC Driver ? A The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. This driver is used to connect to the database. 4 Q What are the steps required to execute a query in JDBC? A First we need to create an instance of a JDBC driver or load JDBC drivers, then we need to register this driver with DriverManager class. Then we can open a connection. By using this connection , we can create a statement object and this object will help us to execute the query. 5 Q What is DriverManager ? A DriverManager is a class in java.sql package. It is the basic service for managing a set of JDBC drivers. 6 Q What is a ResultSet ? A A table of data representing a database result set, which is usually generated by executing a statement that queries the database.

A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set. 7 Q What is Connection? A Connection class represents a connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.

A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method. 8 Q What does Class.forName return? A A class as loaded by the classloader. 9 Q What is Connection pooling? A Connection pooling is a technique used for sharing server resources among requesting clients. Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. Connection pool manager maintains a pool of open database connections. 10 Q What are the different JDB drivers available? A There are mainly four type of JDBC drivers available. They are:

Type 1 : JDBC-ODBC Bridge Driver - A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun.

Type 2: Native API Partly Java Driver- A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.

Type 3: Network protocol Driver- A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products.

Type 4: JDBC Net pure Java Driver - A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress. 11 Q What is the fastest type of JDBC driver? A
Type 4 (JDBC Net pure Java Driver) is the fastest JDBC driver. Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at least three translations versus two), and Type 4 drivers are the fastest (only one translation).
12 Q Is the JDBC-ODBC Bridge multi-threaded?
A No. The JDBC-ODBC Bridge does not support multi threading. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won't get the advantages of multi-threading.



13 Q What is cold backup, hot backup, warm backup recovery?
A Cold backup means all these files must be backed up at the same time, before the database is restarted. Hot backup (official name is 'online backup' ) is a backup taken of each tablespace while the database is running and is being accessed by the users


14 Q What is the advantage of denormalization?
A Data denormalization is reverse procedure, carried out purely for reasons of improving performance. It maybe efficient for a high-throughput system to replicate data for certain data.
15 Q How do you handle your own transaction ? A Connection Object has a method called setAutocommit ( boolean flag) . For handling our own transaction we can set the parameter to false and begin your transaction . Finally commit the transaction by calling the commit method.















SWING/AWT interview questions.

1 Q What is JFC?
A JFC stands for Java Foundation Classes. The Java Foundation Classes (JFC) are a set of Java class libraries provided as part of Java 2 Platform, Standard Edition (J2SE) to support building graphics user interface (GUI) and graphics functionality for client applications that will run on popular platforms such as Microsoft Windows, Linux, and Mac OSX.

2 Q What is AWT?
A AWT stands for Abstract Window Toolkit. AWT enables programmers to develop Java applications with GUI components, such as windows, and buttons. The Java Virtual Machine (JVM) is responsible for translating the AWT calls into the appropriate calls to the host operating system.

3 Q What are the differences between Swing and AWT?
A AWT is heavy-weight components, but Swing is light-weight components. AWT is OS dependent because it uses native components, But Swing components are OS independent. We can change the look and feel in Swing which is not possible in AWT. Swing takes less memory compared to AWT. For drawing AWT uses screen rendering where Swing uses double buffering.

4 Q What are heavyweight components ?
A A heavyweight component is one that is associated with its own native screen resource (commonly known as a peer).

5 Q What is lightweight component?
A A lightweight component is one that "borrows" the screen resource of an ancestor (which means it has no native resource of its own -- so it's "lighter").

6 Q What is double buffering ?
A Double buffering is the process of use of two buffers rather than one to temporarily hold data being moved to and from an I/O device. Double buffering increases data transfer speed because one buffer can be filled while the other is being emptied.

7 Q What is an event?
A Changing the state of an object is called an event.

8 Q What is an event handler ?
A An event handler is a part of a computer program created to tell the program how to act in response to a specific event.

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

10 Q What is clipping?
A Clipping is the process of confining paint operations to a limited area or shape.

11 Q Which containers use a border Layout as their default layout?
A The window, Frame and Dialog classes use a border layout as their default layout.

12 Q What is the preferred size of a component?
A The preferred size of a component is the minimum component size that will allow the component to display normally.

13 Q What method is used to specify a container's layout?
A The setLayout() method is used to specify a container's layout.

14 Q Which containers use a FlowLayout as their default layout?
A The Panel and Applet classes use the FlowLayout as their default layout.

15 Q Which method of the Component class is used to set the position and size of a component?
A setBounds
16 Q What is the difference between invokeAndWait() and invokeLater()? A invokeAndWait is synchronous. It blocks until Runnable task is complete. InvokeLater is asynchronous. It posts an action event to the event queue and returns immediately. It will not wait for the task to complete
17 Q Why should any swing call back implementation execute quickly? A Callbacks are invoked by the event dispatch thread. Event dispatch thread blocks processing of other events as long as call back method executes.
18 Q What is an applet?
A Applet is a java program that runs inside a web browser.
19 Q What is the difference between applications and applets? A Application must be run explicitly within Java Virtual Machine whereas applet loads and runs itself automatically in a java-enabled browser. Application starts execution with its main method whereas applet starts execution with its init method. Application can run with or without graphical user interface whereas applet must run within a graphical user interface. In order to run an applet we need a java enabled web browser or an appletviewer.

20 Q Which method is used by the applet to recognize the height and width?
A getParameters().
21 Q When we should go for codebase in applet?
A If the applet class is not in the same directory, codebase is used.
22 Q What is the lifecycle of an applet?
A init( ) method - called when an applet is first loaded
start( ) method - called each time an applet is started
paint( ) method - called when the applet is minimized or maximized
stop( ) method - called when the browser moves off the applet's page
destroy( ) method - called when the browser is finished with the applet
23 Q Which method is used for setting security in applets?
A setSecurityManager
24 Q What is an event and what are the models available for event handling?
A Changing the state of an object is called an event. An event is an event object that describes a state of change. In other words, event occurs when an action is generated, like pressing a key on keyboard, clicking mouse, etc. There different types of models for handling events are event-inheritance model and event-delegation model
25 Q What are the advantages of the event-delegation model over the event-inheritance model?
A Event-delegation model has two advantages over event-inheritance model. a)Event delegation model enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component's design and its use. b)It performs much better in applications where many events are generated. This performance improvement is due to event-delegation model does not have to be repeatedly process unhandled events as is the case of the event-inheritance.
26 Q What is source and listener ?
A A source is an object that generates an event. This occurs when the internal state of that object changes in some way. A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with a source to receive notifications about specific event. Second, it must implement necessary methods to receive and process these notifications.

27 Q What is controls and what are different types of controls in AWT?
A Controls are components that allow a user to interact with your application. AWT supports the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component. 28 Q What is the difference between choice and list?
A A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices and only one item may be selected from a choice. A List may be displayed in such a way that several list items are visible and it supports the selection of one or more list items.
29 Q What is the difference between scrollbar and scrollpane?
A Scrollbar is a Component, but not a Container whereas Scrollpane is a Container and handles its own events and perform its own scrolling.
30 Q What is a layout manager and what are different types of layout managers available?
A A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout , GridBagLayout, Boxlayout and SpringLayout
31 Q How are the elements of different layouts organized?
A The elements of a FlowLayout are organized in a top to bottom, left to right fashion. The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container. The elements of a CardLayout are stacked, on top of the other, like a deck of cards. The elements of a GridLayout are of equal size and are laid out using the square of a grid. The elements of a GridBagLayout are organized according to a grid. However, the elements are of different size and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes. It is the most flexible layout.

32 Q What are types of applets?
A There are two different types of applets. Trusted Applets and Untrusted applets. Trusted Applets are applets with predefined security and Untrusted Applets are applets without any security.

33 Q What are the restrictions imposed by a Security Manager on Applets?
A Applets cannot read or write files on the client machine that's executing it. They cannot load libraries or access native libraries. They cannot make network connections except to the host that it came from. They cannot start any program on the client machine. They cannot read certain system properties. Windows that an applet brings up look different than windows that an application brings up.

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

35 Q What is the relationship between an event-listener interface and an event-adapter class?
A 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.

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

37 Q What is the difference between the paint() and repaint() methods?
A 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.

38 Q What interface is extended by AWT event listeners?
A All AWT event listeners extend the java.util.EventListener interface.

39 Q What is Canvas ?
A Canvas is a Component subclass which is used for drawing and painting. Canvas is a rectangular area where the application can draw or trap input events.

40 Q What is default Look-and-Feel of a Swing Component?
A Java Look-and-Feel.

41 Q What are the features of JFC?
A Pluggable Look-and-Feel, Accessibility API, Java 2D API, Drag and Drop Support.

42 Q What does x mean in javax.swing?
A Extension of java.

43 Q What are invisible components?
A They are light weight components that perform no painting, but can take space in the GUI. This is mainly used for layout management.

44 Q What is the default layout for a ContentPane in JFC?
A BorderLayout.



45 Q What does Realized mean?
A Realized mean that the component has been painted on screen or that is ready to be painted. Realization can take place by invoking any of these methods. setVisible(true), show() or pack().

46 Q What is difference between Swing and JSF?
A The key difference is that JSF runs on server. It needs a server like Tomcat or WebLogic or WebSphere. It displays HTML to the client. But Swing program is a stand alone application.
47 Q Why does JComponent class have add() and remove() methods but Component class does not?
A JComponent is a subclass of Container and can contain other components and JComponents.
48 Q What method is used to specify a container's layout?
A The setLayout() method is used to specify a container's layout.
49 Q What is the difference between AWT and SWT?
A SWT (Standard Widget Toolkit) is a completely independent Graphical User Interface (GUI) toolkit from IBM. They created it for the creation of Eclipse Integrated Development Environment (IDE). AWT is from Sun Microsystems.
50 Q What is the difference between JFC & WFC?
A JFC supports robust and portable user interfaces. The Swing classes are robust, compatible with AWT, and provide you with a great deal of control over a user interface. Since source code is available, it is relatively easy to extend the JFC to do exactly what you need it to do. But the number of third-party controls written for Swing is still relatively small.
WFC runs only on the Windows (32-bit) user interface, and uses Microsoft extensions to Java for event handling and ActiveX integration. Because ActiveX components are available to WFC programs, there are theoretically more controls available for WFC than for JFC. In practice, however, most ActiveX vendors do not actively support WFC, so the number of controls available for WFC is probably smaller than for JFC. The WFC programming model is closely aligned with the Windows platform.

51 Q What is a convertor?
A Converter is an application that converts distance measurements between metric and U.S units.
52 Q What is the difference between a Canvas and a Scroll Pane?
A Canvas is a component. ScrollPane is a container. Canvas is a rectangular area where the application can draw or trap input events. ScrollPane implements horizontal and vertical scrolling.
53 Q What is the purpose of the enableEvents() method?
A The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.
54 Q What is the difference between a MenuItem and a CheckboxMenuItem?
A The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.
55 Q Which is the super class of all event classes?
A The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.
56 Q How the Canvas class and the Graphics class are related?
A A Canvas object provides access to a Graphics object via its paint() method.
57 Q What is the difference between a Window and a Frame?
A The Frame class extends Window to define a main application window that can have a menu bar. A window can be modal.
58 Q What is the relationship between clipping and repainting?
A When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.


59 Q What advantage do Java's layout managers provide over traditional windowing systems?
A Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.
60 Q When should the method invokeLater() be used?
A This method is used to ensure that Swing components are updated through the event-dispatching thread.

















Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035) Practice Questions
Q. No Question 1 public class MyClass{
int x = 10;
static final int y= 5;

public void method (int z){
int a = 10;
final float b = 10;

class LocalClass {
int c = 3;

public void method (int d){
System.out.println (??); // -- 1
}
}

public static void main (String args[]){
new MyClass();
}
}
Which of the following variable names can be replaced ?? at line no marked as 1,without compiler error?
A x
B a
C b
D c






A , C and D




Local classes can access all the variables from the enclosing classes. But it can access only the final variables of the enclosing method or the method parameter. The above constraint is applicable if the Local class is declared inside the non-static context. since, if the Local class is declared inside the static context it can access only the static members of the enclosing class.









2 public class MyClass{
public static void main (String args[]){
String str = "Hello World";
System.out.print(str.indexOf('d'));
System.out.print(str.indexOf('h'));
System.out.print(str.indexOf('a'));
}
}
What will be the output?
A 10 -1 -1
B 9 -1 -1
C 10 0 -1
D 10 1 -1






A




IndexOf() returns the index within this string of the first occurrence of the specified character. IndexOf() method returns -1 if it cannot find the specified character. The search is case sensitive. So. it returns -1 for indexOf('a').










3 What is the range of values that can be stored in a short primitive variable?
A 0 - 656535
B -32768 to 32767
C -32768 to 32768
D -32767 to 32768






B




The short is a 16 bit signed integer. Its value ranges from -216 to 216-1









4 Which of the following lines will compile without warning or error.
A float f=1.3;
B int i=10;
C byte b=257;
D char c="a";






B




Always real values default o double. So when compiler sees a value like 1.3 , it will treat it as double and will complain. Choice C is incorrect because the byte value ranges from -128 to +127. Here also the compiler will show the same error message,' possible loss of precision'. Choice D is incorrect because , we cannot assign a String to a char, even though the length is one. ie, anything comes inside " " is a string.









5
What will happen if you try to compile and run the following code ?
public class MyClass {
public static void main (String arguments[]) {
amethod( arguments) ;
}
public void amethod (String[] arguments) {
System.out.println (arguments) ;
System.out.println (arguments[1]) ;
}
}

A Error Can't make static reference to void amethod.
B Error Incorrect main method.
C amethod must be declared with String
D Compiles and executes fine.






A




We cannot call a non static method from a static context.









6 Which of the following will compile without error ?
A import java.util.*;
package mypack;
class MyClass {}
B package mypack;
import java.uril.*;
class MyClass{}
C /*This is a comment */
package MyPackage;
import java.awt.*;
class MyClass{}
D All of the above






B and C




The order of different statements and blocks in a java program is as follows. package declaration first, then imports, then class declaration. So if a package declaration exist, it =must be the first non comment code in the file.









7 Float f= new Float( 1.0F );
String str = "value is " +f;
System.out.println( str );

What will be the output of executing the above code snippet?
A Compiler error invalid character in constructor

B Runtime exception invalid character in constructor.
C Compiles and prints 'value is 1.0'
D Compiles and prints 'value is 1'






C




Choice A and B is incorrect because we can use 'F' to specify the given number is float.









8 Which of the following are java keywords ?
A null
B const
C volatile
D true






B and C




Choices B and C are java keywords. Choice A and D are not java keywords, but they are treated as reserved words in java.









9 What will be printed out if this code is run with the following command line : java myprog good morning
public class myprog {
public static void main (String argv[]) {
System.out.println(argv[2])
}
}
A myprog
B good
C morning
D Exception raised: java.lang.ArrayIndexOutOfBoundsException: 2






D




Unlike C++ , java command line arguments does not include the java program name in the argument list. So in our program we actually passing only two arguments. But when printing we are printing the third argument (since array index always start at zero) and as a result it will cause a RuntimeException.









10 What is the range of a byte
A 0 - 256
B -128 to 127
C -127 to 128
D -255 to 256






B




The size of a byte is 1 byte. So its range is from -28 to +28-1.



Q. No Question 11 Which of the following are legal identifiers ?
A 1variable
B variable1
C $anothervar
D _anothervar
E %anothervar






B , C and D




A variable name should start with a letter, under score or a dollar sign. A valid variable can contain letters and digits.









12 What will happen when you compile the following code
public class MyClass{
static int i;
public static void main (String argv[]) {
System.out.println(i) ;
}
}
A 0
B 1
C Compiler Error variable 'i' may not have initialized.

D null






A




All the class level variables are automatically initialized to a default value. Since 'i' is of type int, it is initialized to zero.









13 What will be the output on executing the following code.
public class MyClass {
public static void main (String args[] ) {
int abc[] = new int [] {1, 2, 3, 4};
System.out.println(abc[2]);
}
}
A ArrayIndexOutofBoudsException will be thrown.
B 2
C 3
D 4






C




Always array elements starts with index zero. The element at index 2, ie, the e3lement at position 3 is 3 . So the correct answer is C.









14 What will be the output on executing the following code.
public class MyClass {
public static void main (String args[] ) {
int abc[] = new int [5];
System.out.println(abc);
}
}
A Error array not initialized
B 5
C null
D Print some junk characters






D




It will print some junk characters to the output. Here it will not give any compile time or runtime error because we have declared and initialized the array properly. Event if we are not assigning a value to the array, it will always initialized to its defaults.









15
What will be the output on executing the following code.
public class MyClass {
public static void main (String args[] ) {
int abc[] = new int [5];
System.out.println(abc[0]);
}
}

A Error array not initialized
B 5
C 0
D Print some junk characters






C




Here it will not give any compile time or runtime error because we have declared and initialized the array properly. Event if we are not assigning a value to the array, it will always initialized to its defaults. So the array will be initialized with values zero.









16 What will be the result of attempting to compile and run the following code ?
abstract class MineBase {
abstract void amethod() ;
static int i;
}

public class Mine extends MineBase {
public static void main( String argv[]) {
int[] ar=new int[5];
for (i=0;i < ar.length;i++)
System.out.println (ar[i]) ;
}
}
A A sequence of 5 0's will be printed
B Error: variable 'ar' may not have initialized .
C Error Mine must be declared abstract
D Error MineBase cannot be declared abstract.






C




If we are extending an abstract class, we need to provide implementations for every abstract method. If we are not able to provide the implementation, we have to declare our child class as abstract. Otherwise the compiler will flag an error message.









17 What will be printed out if you attempt to compile and run the following code ?
int i=1;
switch (i) {
case 0:
System.out.println ("zero") ;
break;
case 1:
System.out.println("one") ;
break;
case 2:
System.out.println("two") ;
break;
default:
System.out.println("default") ;
}
A one
B zero
C one default
D one two default






A




It is obvious. It printed the value corresponding for the case label 1.









18
What will be printed out if you attempt to compile and run the following code ?
int i=1;
switch (i) {
case 0:
System.out.println ("zero") ;
break;
case 1:
System.out.println("one") ;
case 2:
System.out.println("two") ;
break;
}

A zero
B one
C one two
D Error no default specified.






C




Choice C is the correct because, since the value of i is one, it will start executing the case 1. But it will continue its execution till it finds a break or till it reach the end of switch statement, so the value one followed by two will be printed. Choice D is incorrect because, the use of default in switch expression is optional.









19 What will be printed out if you attempt to compile and run the following code ?
int i=10;
switch (i) {
default:
System.out.println("Default");
case 0:
System.out.println ("zero") ;
break;
case 1:
System.out.println("one") ;
case 2:
System.out.println("two") ;
break;
}
A default
B default zero
C Error , default cannot be the first statement in switch.
D default zero one two






B




Since there is no matching case labels, it will start its execution in default, and continue till the first break statement. The order of case labels in switch statement does not matter.









20 Which of the following data types can appear inside a switch statement as its label ?
A String
B char
C int
D byte






B , C and D




The valid types for the switch statement is byte, char, short and int.



2 comments:

Unknown said...

Good job.

http://pragyarawal.blogspot.com/

suman said...

nice information for beginners.thank you.
learn java