COREJAVA

COREJAVA Interview Questions And Answers
More interview questions and answers

How would you implement a thread pool?

ThreadPools are useful when you need to limit the number of threads running in your application. Built in thread pools in the java.util.concurrent package.

Thread pools address two different problems :-
They usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. 


Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.

What difference between constructor and method?

A constructor is a member function of a class that is used to create objects of that class. 

It has the same name as the class itself, has no return type, and is invoked using the new operator.


 A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

Example for transient variable?

What is the difference between frame work and api? Why we called collections framework?

instanceof in Java

instanceof operator is used to check whether the object is an instance of the class or subclass or interface.

The instanceof is also known as type comparison operator because it compares the instance with type.
It returns either true or false.
instanceof operator with variable having null value, it returns false

What are legacy classes in java?

what is the return type of delete method in StringBuffer ?

StringBuffer 

Can a main() method of class be invoked in another class?

Yes! We can invoke the main() method of one class in another class. Since main() method is a static method, it can be invoked by using the class name with the method name.

What is the difference between java command line arguments and C command line arguments?

In C command line arguments, values are passed in the main() method having the two parameters.

One is int argc i.e. arguments count and the another is char *argv[] i.e. arguments vector which is an array of pointers to character strings.

 

What is the difference between == & .equals()?

The == and eqauls() method, both are used to check the equality of the two strings, but in the different sense.

The eqauls() method put the two strings in the two different arrays and compare the characters one by one.

 If all the characters are matched then this method will return true otherwise false.

The == operator checks whether the two strings points to the same the object or not. The == operator checks the bit pattern of the two references.

What is the difference between abstract class & Interface?

Abstract class is a class that can not be instantiated and having zero or more abstract method.

It must be subclassed by other class implementing the abstract method. 

The abstract class is modified by keyword \'abstract\'. 

Interface can be think of as fully abstract class.All the method within the interface are abstract must end with a semicolon followed by parantheses.

If a class implement an Interface,it must provide the definition to all the methods of the interface or it must be the abstract class.

What is use of static, final variable?

If you modify a variable or method by a static modifier it means there is only one copy of that variable or method shared by all theinstances of that class. A class can not be modified as static,but an inner class.

 A final variable is just like a constant. It\'s value can not be change once it is initialized. It must be initialized at the time of variable declaration or the constructor completed.

Examples of final class.

If you modify a class with a final keyword, it means, this class can not be subclassed. No class can inherit the features of the final class. If you try to this, an error will result. 

Example: 

 package p1;

 public final class FinalClass{public void show(){System.out.println(\"This is a final class.\"); } }

 class FinalSub extends FinalClass{ //errorpublic static void main(String[] args){FinalClass f=new FinalClass();f.show();}} 

 Output: The above program will result an error in compilation like \'can\'t subclassed a final class\'.

package p1; public final class FinalClass{ public void show(){ System.out.println(\"This is a final class.\"); } } class FinalSub extends FinalClass{ //error public static void main(String[] args){ FinalClass f=new FinalClass(); f.show(); } }

What is a java bean?

JavaBeans is an API reusable, platform indepent component writtenin java programming language. 

A JavaBean is a simple class havingthe setter and getter methods for each property. 

It is good convension to implement the Serializable interface.

 Example: 

  import java.io.*;

public class MyBean implements Serializable {

// Properties private String name = null; private int age = 0; // Getter and Setter Methods

public String getName() { return name; } public void setName(String s) { name = s; } public int getAge() { return age; } 

public void setAge(int i) { age = i; } }

What is use of synchronized keyword?

One of the most powerful feature of Java is its multithreading mechanism. 

The synchronization is used to coordinate the activities between the multiple threads.

Java uses the monitor to synchronize the methods or the block of code. A \'synchronized\' keyword is used with the method signature or before a block of code.

 If all the thread of the class want to access the same method concurrently, monitor helps them to synchronize the accessone thread at a time by locking the resource being accessed on the accessing object.


Multithreading in java.

What is reflect package used for & the methods of it?

The java.lang.reflect package provides the information about the code, i.e. objects and classes.

Reflection provides the programmatic access to variables, methods, constructors to operate on objects.

 It is used to retrieve the member information for any loaded class. 

 Example:Class a=Class.forName(\"java.lang.String\");Method m[]=a.getDeclaredMethods();java.lang.reflect package provides classes such as Method,Modifier,Field,Constructor,Proxy etc. Using these classes we can retrieve the needed information of the loaded class.

What is use of serialization?

Serialization can be obtained in a class by implementing the java.io.Serializable interface. 

All the subclasses of a serializedclass are also themseleves serialize. 

This interface contains no methods and used simply to identify being serialized.

 Its main purpose is to save the object state into a device or filefor the future use.

 This process is calles serialization. When we want to access the state of the object we make it deserialized.The classes that require serialization must implement the following methods for the serialization and deserialization process.

 private void writeObject(java.io.ObjectOutputStream out) throws IOException{//write the object state} private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException{//read the object state} The writeObject() method is responsible for saving the state of the object into a resource, i.e. device or a file. The readObject()method is responsible for the accessing the object state.

Can methods be overloaded based on the return types ?

No! Methods can\'t be overloaded based on the return type.

 For methods overloading you must change the argument list.

 You can change the number of parameter passed or their data types.The return type may be the same, doesn\'t matter.

Why do we need a finalize() method when Garbage Collection is there ?

Before performing the garbage collection the JVM called the finalize() method to cleanup the resources such as closing the file or socket connection etc.


 The finalize() method is declared in the java.lang.Object class.

 When you implement the finalize method, you are actually overriding it from the Object class.Your finalize() method must be declared as follows:

 protected void finalize () throws throwable{//some cleanup code here}

Difference between AWT and Swing components ?

AWT(Abstract Window Toolkit} and Swing are the components of the JFC(Java Foundation Classes), and used for creating the GUI(Graphical User Interface).

 AWT is a portable GUI library for stand-alone applications and/or applets. 

Swing implements a set of GUI components that build on AWT technology and provide a pluggable look and feel. Swing is implemented entirely in the Java programming language.AWT over Swing:*Speed*Applet Portability*Look and FeelSwing over AWT:*Portability*Behavior*Features

Is there any heavy weight component in Swings ?

A heavyweight component is one that is associated with its own native screen resource. 

Using the JMF with the JFC/Swing is a heavy weight component. 

All AWT components are heavyweight and all Swing components are lightweight. Mixing the AWT components with Swing is painful task.

What are the methods in Applet ?

An applet life cycle contains the following methods:*init()*start()*stop()*destroy()Besides these your applet can implement the paint() method.

 Example: 

import java.applet.Applet;import java.awt.Graphics;

import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString(\"Hello world!\", 50, 100); } }

When is init(), start() called ?

The browser starts execution of an applet with the init() method. This method is used for initialization of the component. 

The start() method is called applet is ready to display the content and called after the init() completed and before the paint() called.

What is Exception ?

An Exception is an abnormal condition that may occur during the program execution.

 Exception is a class drived from the Throwable class. 

Two types of exception are there:Checked exception and Unchecked exception. If a checked exception is thrown by a method it must declare it or handle it by providing a try/catch block. 

Java provides the five keywords for handling the exception: try,catch,throw,throws and finally.When an exception is thrown,the class Exception or its subclassmust be instantiated and passed to the catch block as a parameter.

What are the ways you can handle exception ?

When an exception is thrown by a method, it must declare or handle it. 

 A method can declare the exception using the keyword throws with the method signature and a list of exceptions type so that the calling methods can guard themselves. 

 For example: 

public void myMethod() throws IOException, ArithemeticException{//some code here that might cause the exception}If a method does not declare the exception then it must handle the exception by providing the try/catch block.For example:public void myMethod(){try{//some code here that might cause the arithematic exception}catch(ArithematicException e){}}

What is finally method in Exceptions ?

You never know that the exception will be thrown or not. 

 That means you are not sure that the catch will be executed or not. 

 So it is better not to put the code inside the catch block which must be executed such as closing a file or a socket connection. Java provide another keyword \'finally\' for this purpose. 

The finally block must come immediately after the all catch blocks or after the try block if there is no catch associated with the try block. The finallyblock must be executed, doesn\'t matter the exception is thrown or not.

What are the types of access modifiers ?

In java, there are three types of access modifiers:   *public   *protected   *privateBut, there are four access control levels, burn itinto your mind. The fourth access control level isdefault. 

We get default access control if we don\'t use any of the access modifiers.

What are the other modifiers in java ?

Besides access modifiers, the other modifiers in java are:
  *abstract,
  *static,
  *final,
  *strictfp,
  *transient,
  *volatile,
  *native,
  *synchronized, etc.

Is synchronized modifier ?

Yes! synchronized is a modifier in java. It is used 
for synchronized a resource if multiple threads
want to access the resource.

What is meant by polymorphism ?

Polymorphism is a useful mechanism in java. Polymorphism means \'one name with multiple implementaions.\'

Java supports two types of polymorphism: static and dynamic polymorphism.

 Polymorphism can be achieved in java by method overloading (static polymorphism) and method overriding (dyanmic polymorphism). 

 Overloading: Using the same method name with multiple implementation in such a way that the argument list must be changed and return type may change. For overloading, change in the argument list is a must. Overloading resolve at the time of compilation.

 Overriding: Using the same method name with thesame argument list and return type called method overriding. However in Java 5, the ruturn type ofthe overrriding method may be changed with the subtype of the overridden method.

What is inheritance ?

Inheritance is the mechanism of using the features of one class into another class.

 The class which acquire the properties of another class (super class)is called subclass or drived class. 

Java provides the keyword \'extends\' to support the Inheritance.

 Example:

package p1; public class SuperClass{ void show(){ System.out.println(\"Super class\"); } } class SubClass extends SuperClass{ public static void main(String[] args){ SubClass s=new SubClass(); s.show(); } }

What is method Overloading ?

Using the same method name with different arguments list is called method overloading. 

To overload amethod, you must change the arguments list. Thereturn type may or may not be change.

What is method Overriding ?

Using the same method name with the same argument list and 
return type called method overriding. However in Java 5, the
 ruturn type of the overrriding method may be changed with
the subtype of the overridden method.

Does java support multi dimensional arrays ?

No! Java does support array within array.We can achieve multidimensional arrays using it.Example:int[][][] m=new int[3][3][2];

Is multiple inheritance used in Java ?

Java does not support multiple inheritance. But we can achievethis using interface.

 A class can\'t extends more than one classbut an interface can extends more than oneinterface.Example:interface I1{//some abstract methods here}interface I2{//some abstract methods here}interface I3 extends I1,I2{//some abstract methods here}

Is there any tool in java that can create reports ?

Yes! There are many reporting tools in java:
  * JFreeChart
  * Prefuse
  * JasperReports
  * jCharts
  * JFreeReport

What is meant by Java ?

Java is a pure Object oriented programming language originally developed by Sun Microsystems, released in 1995 and has the capability in its platform independency. 

It support multithreading, exception handling and automatic garbage collection facilities.Java supports various applications like:Web applications and web services.

What is meant by a class ?

A Class is a just like a container which containsvariables and methods. The variables make up thestate and the methods describe the behavior of theclass.

What is meant by a method ?

A method is a group of instructions enclosed by the curly braces{}.

 A method has a specific signature having the method name along with the parameter list and a return type. Methods describe the behaviour of the class. Methods are where the real work gets done,date get manipulated and algorithms implemented.

What are the OOPS concepts in Java ?

Java is a pure Object oriented programming language and supports:
  * Class
  * Object
  * Abstraction
  * Encapsulation
  * Polymorphism
  * Inheritance, etc.

What is meant by encapsulation ? Explain with an example.

Binding up the data and methods into a singleunit, i.e. class is called encapsulation.

 Example:

 class Area{ //data variable double dim1; 

 double dim2;

 //methods public double calculateArea(double d1,double d2){ //some calculation code here}}

What is meant by inheritance ? Explain with an example.

Inheritance is the mechanism of using the features of one class into another class.

 The class which acquire the properties of another class (super class)is called subclass or drived class.

 Java provides the keyword \'extends\' to support the Inheritance. 

 Example:


package p1; public class SuperClass{ void show(){ System.out.println(\"Super class\"); } } class SubClass extends SuperClass{ public static void main(String[] args){ SubClass s=new SubClass(); s.show(); } }

What is mean by JVM ?

A Java source code is compiled by java compiler(javac) and converted into the bytecode.

 This bytecode is then executed by the JVM. A Java Virtual Machine (JVM) is a software program and data structures which use a virtual machine model to execute the instructions.

 JVM accepts accepts the byte code and provides output of that bytecode. 

A bytecode is highly optimized set of instructions.The JVM is combines a set of standard class libraries which implement the Java API (Application Programming Interface).

What is meant by identifiers ?

Identifiers are just the name of the variables, methods, classes, interfaces etc.

 Each of the above things is identified by their names in the program. 

They are not the thing themselves, they justpoint to the values in the memory. Identifiers follows some rules to be declared: * Identifiers must be composed of letters, numbers, the underscore _ and the dollar sign $. * Identifiers may only begin with a letter, the underscore or a dollar sign.

What are the different types of modifiers ?

There are two types of modifiers in Java:  * Access Modifiers,  * Non-access modifiers.

 Acess modifiers are public, protected and private.Non-access modifiers are abstract, final, static, transient, volatile, strictfp, and synchronized.

What are the primitive data types in Java ?

Primitives data types in java are:
 * boolean
 * char
 * byte
 * short
 * int 
 * long
 * float
 * double

What is mean by a wrapper class ?

The wrapper classes serve the two purpose:
 * It wraps the primitive to an object so that primitives can
 be used in the activities which are reserved only for the objects.
 * Converting primitives to and from String objects.
Java provides the Wrapper class for each of the primitives
in java. Some of these are: 
 * Boolean
 * Character
 * Byte
 * Short
 * Integer
 * Long
 * Float
 * Double

What is Garbage collection ?

Java provides the automatic garbage collection facility. 

 JVM performs the garbage collection to free up the unnecessary memory which can\'t be reached through the object reference. We can\'t force the JVM to perform the garbage collection, but we can request the JVM by our program to to call the method System.gc(), but it is upto JVM to perform garbage collection or not.

What is mean by final class, methods and variables ?

A final keyword is used to prevent the inheritance if it is used with the methods and classes. 

If we modify a class with the final modifier, it means, that class can\'t be subclassed, i.e. we can not make a subclass of final class.If we declare a method to final, it means, that method will not be inheritin the subclass of that class in which the final method is declared.If we declared a final variable, it means, that the value of the variable can not be modified once it is initialized.

What is mean by interface ?

You can think of interface as a fully abstract class.

 An abstract class can have abstract and non-abstract methods, but an interface can have only abstract methods ends with the semicolon.

 An interface may also contain constant.Example:public interface MyInterface{int i1;static int i2;static final int i3;void showi1();public void showi2();public abstract showi3();}

What is the difference between an array and a vector ?

An array is simply a data structure that stores the similar types of elements with sequence of consecutively numbered. int a[]=new int[3]; 

 This will create an array of int of size 3. The size of the can\'t be increase once it is created.Vector is just like an array, but it is rescalable. That means we can increase or decrease the size of the vector. One most important thing about vector is that unlike array, vector can hold multiple types of element. Vector can be declared as:Vector v=new Vector();Vector provides the methods to manipulate the elements:v.add(\"Hello\");v.add(3);v.add(1,\"world!\");v.set(2,\"How are you!\");v.get(0);Use the vector if you want to store the multiple data types and don\'t know about the size.

What is singleton class ?

The Singleton is a Design Pattern for allowing onlyone instance of your class. 

The Singleton's mainpurpose is to control object creation upto one.

It is good for threading problems, because we are surethat there is only one instance of the class.

What is constructor ?

Constructors are the special member functions which have 
the same name as the class name. The most important 
thing is that they don\'t hava return type. Constructors 
may be overloaded. If you don\'t provide a constructor 
for the class, the compiler will supply the defualt one. 
Constructors can have any of the access modifiers.

Example:

public class MyClass{
int i;
int j;
public MyClass(){}
protected MyClass(int i){}
private MyClass(int i,int j){}
}

What is casting ?

Casting is the process of assigning the value of one type of variable to another type of variable. 

Two types of casting are there in java:

  Implicit casting
  Explicit casting

We can directly assign the value of a variable to other variable if that variable can be easily fit by memory size into the other variable, this is called implicit casting.


 Example:

 int a=5; //a having 4 byte of memorybyte b=6; //b having 1 byte of memorya=b; 

//OK! byte b can be easily fit into an int a.b=a; //NO! int a can't be fit into the byte b.b=(byte)a;

 //OK! Explicit casting.The above statement telling the compiler that, I know there may be some loss of bits.

What is the difference between final, finally and finalize ?

final is a keyword used for the following things:-

final variable use to prevent the value modification.

final methods can't be inherited.

final class can't be sub-classed.


finally is the block of code used with the try/catch block or the try block if there is no catch associated with the try block.

finalize It is useful where you want some code must be executed whether the exception is thrown or not.finalize is a method that is called by JVM just before the performing the garbage collection.

 But is not sure that this method will be called ore not, it depends upon the JVM.It is declared in the Object class. You can override the finalize() method.

What is mean by packages in java?

Packages are the container for the classes.

 A single package may contain several classes and sub packages.

 Java provides the keyword \'package\' to declare the package. Each package has an identifier and can be import in the other package.

 Packages are introduced to resolve the class naming confliction that can arise when two programmers have the same name for their classes.Declaring a package:package p1;class abc{}Importing a package:package p2;import p1.abc;class xyz{}

Name 5 calsses you have used ?

 * String 
 * Thread 
 * ArrayList 
 * Vector 
 * HashMap

Name 2 classes that can store arbitrary number of objects ?

 * ArrayList
 * Vector

What is the difference between java.applet.* and java.applet.Applet ?

When you import java.applet.*, it means you are importing 
all the classes available in the java.applet package.

When you import java.applet.Applet, it means you are importing 
the single class. It is better to import the classes that 
you need instead of importing all the classes in the package.

What is a default package ?

The java.lang is the default package which is automatically 
imported in each of the java source file.

What is anonymous class ?

Anonymous class is one that has no name. Java provides 
the anonymous inner classes with different flavours. 
An anonymous inner class can also be declared even in the 
argument list of the method.

What is the use of an interface ?

An interface tells that what a class can do. It is a good 
object oriented design to use interfaces in your program. 
When a class implements the interface, it is actually 
contracting to implement all the functionality of the interface. 
Interfaces also support multiple inheritance.

What is a serializable interface ?

If a class implements the serializable interface, 
it means that state of objects of that class can be
serialized and deserialized. This interface has no 
methods.

How to prevent field from serialization ?

If you want prevent serialization of the
fields(variables), mark them transient. 
The transient variable can\'t be serialized.

What is the difference between throw and throws ?

The throw keyword is used to throwing the exceptionmanually in the program. 

For Example:

 try{throw new NullPointerException();}catch(NullPointerException e){} 

 The throws keyword is used with the method signature with the list of Exceptions type. This process is called exception declaration. It tells the calling method to guard themselves to declare the exception or handle it.

 For example:void calculate(int a,int b) throws ArithematicException{//some calculation code here}

Can multiple catch statements be used in exceptions ?

Yes! Multiple catch statement can be used in exceptions, but with some general rules.

 A single try block can have multiple catch associated with it but the each catch has an arguments according to the inheritance heirarchy of Exception. 

That means a subtype of Exception heirarchy must not be come in the catch block before the supertype of the Exception heirarchy. 

 Example:

 try{int i=3/0; //divide by zero exception}catch(Exception e){}catch(ArithematicException e){}

 The above code will result a compilation error \'unreachable code\' at the second catch statement because ArithematicException is a subtype of the Exception class. 

The above code should be like this:try{int i=3/0; //divide by zero exception}catch(ArithematicException e){}catch(Exception e){}

Is it possible to write a try within a try statement ?

Yes! The try statement can be nested within another try block.

What is mean by a Thread ?

Thread is a light weight process.

The Java Virtual Machine allows an application to have multiple threads of execution running concurrently

Every thread has a priority from one to ten.

 Threads with higher priority are executed in preference to threads with lower priority. Java provides two ways to create the Thread: * Extending the Thread class * Implementing the Runnable interface.

What is mean by multi-threading ?

Multithreading allows two or more parts of the same program to run concurrently. 

A single program or block of code can be executed by any number of treads. 

Some problems may arises with multi-threading if two or more threads manipulates the shared or global variable.

What is the 2 way of creating a thread ? Which is the best way and why?

Two way of creating the thread in java are: * Extending the Thread class * Implementing the Runnable Interface.Both ways provides the same functionality.

 But itis better to implement the Runnable interface, because if you extends the Thread class you willnot be able to extend any other class. One classcan extends only a single class but can implements many interfaces.

What is the method to find if a thread is active or not ?

The method to find if a thread is active:

boolean isAlive()

What is the difference between sleep and suspend ?

The sleep() method moves the thread to waitingstate for particular time. 

for exampleThread.sleep(7000);butthe suspend() method moves to waiting state untilthe resume() method gets called.

Can thread become a member of another thread ?

No! In multi-threading environment a thread can
start the another thread but it can not be a 
member of another thread.

What are the three types of priority ?

MIN_PRIORITY 
MAX_PRIORITY 
NORM_PRIORITY

Garbage collector thread belongs to which priority ?

Garbage collector thread belongs to low priority.

What is the use of this ?

this keyword is used to point to the currently executing object. 

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

 Example:public class PointExample { public int x = 0; public int y = 0; //constructor public Point(int x, int y) {this.x = x;this.y = y; }}

How can you find the length and capacity of a string buffer ?

The StringBuffer is a class that has a mutable sequence of characters.

 Length and capacity of the StringBuffer object can be find out by the following two methods: * length() * capacity()Capacity of the StringBuffer is always plus 16 to the length. Example:class StringBufferExample { public static void main(String args[]) { StringBuffer sb = new StringBuffer(\"Hello World!\"); 

 System.out.println(\"Buffer value= \"+sb); System.out.println(\"Length = \" +sb.length()); System.out.println(\"Capacity = \" +sb.capacity()); }}

How to compare two strings ?

There are two ways to compare the two strings in java: 

 * using the == operator, * using the equals() method.

 For Example:String s1=new String(\"Hello!\");String s2=new String(\"Hello!\");if(s1==s2) System.out.println(\"Equal using == operator.\");elseif (s1.equals(s2))System.out.println(\"Equal using equals method.\");elseSystem.out.println(\"Not Equal.\");

What is the purpose of run-time class and system class?

The System class provide systemlevel functionality to Java applications.

 Some of the facilities provided by System class: * Reading input from the keyboard.

 * Writing output to console. * Reading and writing system properties and environment variables Runtime class provides support for runtime environment.

What is the method used to clear the buffer ?

flush()

What is mean by Stream Tokenizer ?

The StreamTokenizer is class in Java that takesan input stream and parses it into \"tokens\",allowing the tokens to be read one at a time. Each byte read from the input stream is acharacter in the range from \'u0000\' to \'u00FF\'. 

The character value is used to look up five possible attributes of the character: white space, alphabetic, numeric, string quote, and comment character. Some Methods defined by StreamTokenizer class: * void whitespaceChars(int low, int hi) * void wordChars(int low, int hi) * String toString() * void slashStarComments(boolean flag) * void parseNumbers() * void ordinaryChars(int low, int hi) * int lineno() ,etc.

What is serialization and de-serialisation ?

The values assigned to the variables of an objectmake up the state of the object. 

Saving the stateof the object for the future use into some file or the device is called the Serialization.

 When we want to use that object, we read the values of the variables from the file or device. 

This process is called De-serialization.

What is mean by Applet ?

An applet is a tiny Java program that can run on browser and can be included in an HTML page, much in the same way an image is included in a page. 

 When you use a Java technology-enabled browser to view a page that contains an applet, the applet\'s code is transferred to your system and executed by the browser\'s Java Virtual Machine (JVM).

How to find the host from which the Applet has originated ?

Two methods help here:public java.net.URL getDocumentBase();public java.net.URL getCodeBase(); 

The getDocumentBase() returns the URL to the host that server the HTML document.The getCodeBase() returns the URL to where the original applet class was loaded from.

What is the life cycle of an Applet ?

The life cycle of an Applet:

  * init()
  * start()
  * stop()
  * destroy() 

How do you load an HTML page from an Applet ?

Applets are loaded and executed within a web browser, and hence you can load specific URL.

 * Get a reference to the applet context * Call the showDocument method with a URL object as parameter.

 The following code can help here: import java.applet.*;

 public class MyApplet extends Applet { // Applet code here // load an html page public void showPage (String aPage) //aPage should contained address of the HTML page to be shown { URL url = null; try { url = new URL (aPage); } catch (MalformedURLException e) { //handle exception } if (url != null) { getAppletContext().showDocument (url); } } }

What is mean by getCodeBase and getDocumentBase method ?

The getDocumentBase() method returns \"the URL of the document in which the Applet is embedded.\"

 It actually return the URL of the directory in which the document resides.

 The getCodeBase() method gets the base URL. 

This is the URL of the directory which contains this applet.It Returns:the base URL of the directory which contains this applet.

What is the use of parameter tag ?

In java applets, the parameter tag is used in the 
html used to send parameter to applet. In applet 
you can read the parameters passed by html code.

What is the difference between getAppletInfo and getParameterInfo ?

The getAppletInfo() method returns the string that 
describes the applet. The getParameterInfo() method 
returns an array of string arrays that specify the 
name,type, and description of each of the parameter.

How to communicate between applet and an applet ?

Sometimes you need to allow two or more applets to communicate on the Web page.

 Because the applets all run within the same Java context-that is, they are all in the same virtual machine together-appletscan invoke each other\'s methods.

The AppletContext class has some methods for locating another applet by name, or retrieving all the applets in the currentruntime environment. The AppletContext class in the java.applet package contains the two member functions getApplet and getApplets.

 By using these functions, an applet can find other applets and invoke methods on them.

 Example:Html file: Using the name attribute, you can refer to a applet: Applet anotherApplet = getApplet(\"applet1\"); anotherApplet.someMethod(); //calling any public method

What is mean by event handling ?

Events represent the activity that occurs between the user and the application. 

Java�s Abstract Windowing Toolkit (AWT) communicates these actions to the programs using events. 

When the user interacts with a program, by clicking a command button, the system creates an event representing the action and delegates it to the event-handling code within the program. 

This code determines how to handle the event so the user gets the appropriate response. 

Java provides the Event class and each event is represented by an object that gives information about the event and identifies the event source. Whenever an event occured by an event sourse, 

An appropriate evetnt handler(EventListener) is called. The Event Listener knows that how to handle the handle.

What are all the listeners in java and explain ?

An event listener is an object used to handling a particular kind of event.

 Event Handling Interfaces * ActionListener * AdjustmentListener * ComponentListener * ContainerListener * FocusListener * ItemListener * KeyListener * MouseListener * MouseMotionListener * WindowListener

What is mean by an adapter class ?

The adapter classes allow you to use the Listener Interfaces without having to create a body for every method. Adapter class provides the empty implementation for Listener interface\'s method. 

 You don\'t have to override all the listener\'s method.

What are the types of mouse event listeners ?

 
 * MouserListener
 * MouseMotionListener

What are the types of methods in mouse listeners ?

 * public void mouseClicked(MouseEvent e)
 * public void mouseReleased(MouseEvent e))
 * public void mouseOver(MouseEvent e)
 * public void mouseDoubleClicked(MouseEvent e)
 * public void mousepressed(MouseEvent e)

What is the difference between panel and frame ?

A Panal and the Frame, both are the component of 
the Abstract Window Toolkit(AWT). A panel is a 
component which can be embedded in a frame, and a 
frame is nothing but a window application an can 
embed all the components. Frame-is a top level 
container.

  while the panel is sub-level container..not the top level
  container..

What is the default layout of the panel and frame ?

 The default layout of panel is flowlayout.
 The default layout of frame is border layout.

What is the difference between list and choice ?

A Choice is a compact form that requires you to pull it down to see the list of available choices.

 Only one item may be selected from a Choice.

 A List may be displayed in such away that several List items are visible. A List supports the selection of one or more List items.

What are the different types of Layouts ?

The different types of Layouts are :

  * FlowLayout, 
  * BorderLayOut,
  * GridBagLayout,
  * GridLayout,
  * CardLayout.

What is mean by CardLayout ?

A CardLayout object is a layout manager for a container.It treats each component in the container as a card.

Only one card is visible at a time, and the container acts as a stack ofcards.

The ordering of cards is determined by thecontainer\'s own internal ordering of its component objects. The CardLayout class manages two or more components (usually JPanel instances) that share the same display space. CardLayout defines a set of methods that allow an application to flip through these cards sequentially, or to show a specified card.

 The addLayoutComponent(java.awt.Component, java.lang.Object) method can be used to associate a string identifier with a given card for fast random access.

What is the difference between GridLayout and GridBagLayout?

GridLayout class puts all the components in a rectangular grid and is divided into an equal sized rectangles and each component is placed inside a rectangle. 

 The GridBagLayout class is a flexible layout manager that aligns components vertically and horizontally, without requiring that the components be of the same size.

 Each GridBagLayout object maintains a dynamic, rectangular grid of cells, with each component occupying one or more cells, called its display area.GridLayout has the constructors :GridLayout(int rows, int cols) and GridLayout(int rows, int cols, int hgap, int vgap)The major difference between GridLayout and GridBagLayout is that GrigBagLayout supports components of different sizes, and you can specify layout options for each component. 

 Use the GridBagLayout when you need tabular layouts (or layouts that can be thought of as matrices) and when it is important to specify the resizing behavior of each component.

Which class has no duplicate elements ?

The classes that implements java.util.Set interface 
(such as, HashSet,TreeSet) do not support duplicate 
elements.

What is mean by Swing ?

Swing is a library of GUI controls which improves upon the Abstract Window Toolkit.

The Swing toolkit includes a rich set of components for building GUIs and adding interactivity to Java applications. It includes rich undo support, a highly customizable text package, integrated internationalization and accessibility support. Swing is completely written in Java to truly leverage the cross-platform capabilities of the Java platform. Swing is part of the Java Foundation Classes (JFC). 

The JFC also include other features important to a GUI program.Swing provides significantly enhanced functionality, such as actions, tables, trees, images buttons, tabs, toolbars, and sliders.

What is the difference between an applet and a Japplet?

Applet is component of AWT whereas JApplet is a component of Swing.  JApplet is a Swing version of Applet.

 An applet is a heavy-weight component, and JApplet is a light-weight component. 

The swing components provide better look and feel than awt.

 Swing components are derived from the javax.swing.* package and they are prefixed with a latter \'J\'(like JFrame, JButton, JApplet) Whereas applet is derived from the package java.applet.*

What are all the components used in Swing ?

The javax.swing package has the following classes 
to create the swing the component:

  * Buttons and Labels
  * Checkboxes and Radio Buttons
  * Lists and Combo Boxes
  * Borders
  * Menus
  * The PopupMenu Class
  * The JScrollPane Class
  * The JSplitPane Class
  * The JTabbedPane Class
  * Scrollbars and Sliders
  * Dialogs 

What is mean by tab pans ?

In javax.swing package, Using the JTabbedPane class, you can have several components, such as panels, share the same space. 

The user chooses which component to view by selecting the tab corresponding to the desired component. The add() method of JTabbedPane class is used to add container component to the JTabbedPane component of Java Swing.

 Example:import javax.swing.*;import java.awt.*;public class MyTabbedPane{ public static void main(String[] args){ JFrame f = new JFrame(\"My Tabbed Pane Frame\");f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTabbedPane t = new JTabbedPane(); frame.add(t, BorderLayout.CENTER); JButton b = new JButton(\"1\"); t.add(\"Tab 1\", button); b = new JButton(\"2\"); t.add(\"Tab 2\", button); frame.setSize(300,300); frame.setVisible(true); }}

What is the use of JTree ?

Jtree is a just like a tree which is used to disply the items in the form of the tree.

 A JTree object does not actually contain your data; it simply provides a view of the data. 

Each row displayed by the tree contains exactly one itemof data, which is called a node.

 Every tree has a root node from which all nodes descend.

What is the use of JTable ?

Using the JTable class you can display tables ofdata, optionally allowing the user to edit the data. 

JTable does not contain data; it is simply a view of your data.

 The JTable class is an implementation of the Active Record design pattern.

 It is used for creating, reading, updating, and deleting records in the database table.

What is mean by JFC ?

The JFC(Java Foundation classes) tells you how to create graphical user interfaces (GUIs) for applications and applets, using the Swing components. 

The Java Foundation Classes (JFC) are a graphical framework for building portable Java-based graphical user interfaces (GUIs).

 JFC consists of the Abstract Window Toolkit (AWT), Swing and Java 2D.

What is JAR file ?

JAR file is a file format based on the popular ZIP file format and is used for aggregating many files into one. A  JAR file is essentially a zip file that contains an optional META-INF directory.

 A JAR file can be created by the command-line jar tool, or by using the java.util.jar API in the Java platform. JAR file format enables you to bundle multiple files into a single archive file.

What is mean by manifest files ?

The manifest file is named MANIFEST.MF. In Java ,a manifest file is a specific file contained within a JAR file.

 It is a meta data file that contains name-value pairs organized in different sections.

 If a JAR file is intended to be used as an executable file, the manifest file specifies the main class of the application.

What is two properties in Beans ?

A javaBean property has the two methods:
  * setProperty() 
  * getProperty() 

What is the use of beaninfo ?

BeanInfo classes provides a high degree of control over how a bean appears and behaves at design time.

 BeanInfo classes are design-time-only classes.If a bean implementor wants to provide information regarding methods, properties when they can provide a bean info class by implementing BeanInfo interface and provide information regarding the bean properties,methods etc.

What are the interfaces you used in Beans ?

 The Serializable interace is used in Beans.

What are the classes you used in Beans ?

Classes that are available in java.beans package :

 * BeanDescriptor * Beans * DefaultPersistenceDelegate * Encoder * EventHandler * EventSetDescriptor * Expression * FeatureDescriptor * IndexedPropertyDescriptor * Introspector * MethodDescriptor * ParameterDescriptor * PersistenceDelegate * PropertyChangeEvent * PropertyChangeListenerProxy * PropertyChangeSupport * PropertyDescriptor * PropertyEditorManager * PropertyEditorSupport * XMLDecoder * XMLEncoder

What is the difference between C++ & Java ?

Difference between java and C++ : * C evolved into C++, and C++ transmuted into Java. 

 * Java is the language of the Internet whereas C++ was designed mainly for systems programming, * Java supports object-oriented programming, same way as C++. * Java does not support operator overloading. 

 * Java does not include a preprocessor or support the preprocessor directives.

 * Java does not support multiple inheritance. * Java does not support destructors, but rather, add the finalize() function. * Java does not support templates. * Java does not support pointers.

What is the difference between Process and Threads ?

A process is a program in execution, whereas a single process can contains multiple threads. 

The key difference is that processes are fully isolated from each other whereas threads share (heap) memory with other threads running in the same application. 

Threads share the address space of the process that created it; processes have their own address.

How will you initialize an Applet ?

You can initialize your applet using the init() method.

What is the order of method invocation in an Applet ?

The order of invocation in Applet is : 
  * init()
  * start()
  * paint()
  * stop()
  * destroy()

When is update method called ?

The update() method is defined by the AWT and is called when your applet has requested that a portion of its window be redrawn. The problem is that the default version of update() first fills an applet with the default background colour and then calls paint().

 You can override the update() method. The paint() in this case will simply call update(). public void update(Graphic g) { //Redisplay your window here.}public void paint(Graphics g) { update(g); // call to the update()method.}

What is JNI ?

JNI stands for Java Native Interface. The Java Native Interface (JNI) enables the integration of code written in the Java programming language with code written in other languages such as C and C++.

 It allows programmers to take full advantage of the Java platform without having to abandon their investment in legacy code. JNI lets Java code use code and code libraries written in other languages, such as C and C++, and allows you to call Java code from within native code. 

 The JNI allows writing native methods to handle situations when an application cannot be written entirely in the Java programming language e.g. when the standard Java class library does not support the platform-specific features or program library. 

The JNI framework lets a native method utilize Java objects in the same way that Java code uses these objects.

What is the base class for all swing components ?

All the swing components are derived from abstract javax.swing.JComponent class.

Is there any tag in HTML to upload and download files ?

The following tag is used for this purpose : 
  tag upload file.

What is the Layout for ToolBar ?

The layout for toolbar is Flow Layout. There is no Specific Layout for adding ToolBar.

You can use null layout for use a toolbar at the position where you want. 

You can also use DefaultToolBarLayout.

How will you add panel to a Frame ?

We can add panel to a Frame :
 
Panel p = new Panel();
Frame f =new Frame(\"My frame\");
f.getContentpane().add(p);
 

What is the corresponding Layout for Card in Swing ?

The corresponding Layout for Card in Swing CardLayout.

What is light weight component ?

AWT supports lightweight components. Light weight componenets can be created using Java without mixing any other language code.

 A light weight component is one that subclasses java.awt.Component (or java.awt.Container) directly - implementing the look-and-feel of the component in Java rather than delegating the look-and-feel to a native peer.

What is difference in between Java Class and Bean ?

The Java Bean is simple java class which is contains Getters and Setters methods nothing else. 

These methods can only used to set or get the values of the variables. 

They neither contain any business logic nor do they interact with the database. 

 Whereas a plain old java class contains the business logic, provides some data processing capabilities, database interaction, etc.

Diff between Application and Applet ?

Applets are the tiny java program runs under the control of web browser and dynamically downloaded over the internet. Browser takes care of the life cycle of the Applet, i.e. calling the init(), start(), paint(), stop(), destroy(), etc methods.

 Applets are designed to run dynamically over the web.An application runs stand-alone, with the support of a virtual machine under the control of local user\' operating system.

 An application starts execution with the main() method. The main method here is nothing but the system method used to invoke the application.

What is the use of Interface ?

Java achieve inheritance using two notions : By extending the class and implementing the interface. 

When you \"implement\" an interface, you are stipulating that your class adheres to the \"contract\" of the interface that you specified. Use interfaces to say \"What objects can do\" or \"What can be done to an object. 

\"Interfaces are intended to define the what without defining the how. Interfaces provide a form of multiple inheritance. A class can extend only one other class. Interfaces are limited to public methods and constants with no implementation.


Interface

Why Java is not fully objective oriented ?

Java is not fully object oriented language, because not all values in Java are Objects.�

The basic numeric types such as int, long, double, etc., are not objects and need to be \"boxed\" into objects in order to pass them as Object parameters or call methods on them. Java does not support Multiple inheritance and operator overloading. Java uses static keyword.

We can perform a function declared as static without an object this violates real world reflection and object orientation.

Core Java Basics

What it the root class for all Java classes ?

The Object class is the root class of all the Java classes.

What is the exact difference in between Unicast and Multicast object ? Where we will use ?

Unicast object means there is one receiver. Use multicast to allow one-to-many connections.

 The example for multicast is the java eventhandling model.

Why there are some null interface in java ? What does it mean ?

Interface which does not contain any variables and methods.

 Examples: * java.io.Serializable, * java.lang.Cloneable, etcBoth of these interfaces declare no methods, by implementing them, a class signals some fact to the JVM (either it\'s OK to serialize it, or it\'s ok to clone it.) 

 The null interface is also called as Marker Interface or tagged interface.

What is latest versions in JAVA related areas ?

As of December 2008, the latest version of Java is 1.6.0_11

What is mean by class loader ? How many types are there? When will we use them ?

Class loaders determine when and how classes can be added to a running Java environment.

 In Java, code is loaded (either from the disk or over the network) by a Class Loader. 

Class loaders perform two functions : First, the JVM needs to load the byte code for a particular class, it asks a class loader to find the byte code.

 Each class loader can use its own method for finding requested byte code files. Second, class loaders define the namespaces seen by different classes and how those namespaces relate to each other. 

Class Loaders provide Java\'s dynamic loading capability, which allows classes to arrive and depart from the runtime environment.In a JVM, each and every class is loaded by some instance of a java.lang.

ClassLoader. The ClassLoader class is located in the java.lang package and developers are free to subclass it to add their own functionality to class loading.Some of the class loaders in the JDK: * java.net.URLClassLoader * java.security.SecureClassLoader * java.rmi.server.RMIClassLoader * sun.applet.AppletClassLoader

public static void main - Explain?

Public is an access modifiers tells that this method can be accessed anywhere inside or outside the package by any class\' object reference. 

Static means there is only one copy of that method is available to all the instances of the class. void is simply a return type of the method telling that this method will return nothing.main is an identifier to identify the method. The main() method is the entry point to the program.

What is difference between String & StringBuffer?

String class provides the immutable character sequence whereas StringBuffer class objects are mutable characters sequence.

 The StringBuffer is faster than String when performing simple concatenations.

 Example:String s=new String(\"Hello\");s.toUpperCase();The String object s is still pointing to \"Hello\" instead of \"HELLO\". Here a new string \"HELLO\" is created but did not assigned to any reference variable.But:StringBuffer sb=new StringBuffer(\"Hello\");sb.toUpperCase();The StringBuffer object sb is now pointing to the \"HELLO\".This is the main difference that string object are immutable and string buffer objects are mutable.

What is Wrapper class. Is String a Wrapper Class?

Wrapper classes are used to \"wrap\" the primitives data types into objects so that they can be included in the activities which are reseved for the objects. 

 Yes! String class is a wrapper class, it wraps the string literals to an object.

What is Default modifier in Interface?

Default modifier in Interface is public access modifier.

Can abstract be declared as Final?

No! An abstract method or abstract class can\'t be marked as a final. 

They both have the opposite meaning. An abstract class must be subclassed, whereas a final class must not be. An abstract method must be overridden whereas a final method can\'t be inherited, hence can\'t be overridden.

Can we declare variables inside a method as Final Variables?

Yes! we can declare variables inside a method as final variables.

How can a dead thread be started?

A Thread is considered to be dead when it completes its run() method. 

We can\'t call a start() method on a given Thread object for the second time. Hence a dead thread can\'t be restarted.

Can Applet have constructors?

Yes we can have constructors in an applet. But applets don\'t usually have constructors because an applet isn\'t guaranteed to have a full environment until its init() method is called. 

Applet constructor is just like any other constructor, they cannot be overridden.

What is Checked & Unchecked exception?

Both types of exceptions are drived from the class Exception.

 But Unchecked exception are RunTimeException, which do not to be handled or declared. Whereas Checked Exceptions must be handled by try/catch block or must be declared in the method signature.

Explain. Two types of multi-tasking.

Two types of multi-tasking : 
  * Process based multi-tasking.
  * Thread based multi-tasking.

In Process based multitaskin, more than one processes run concurrently. Whereas In Thread based multitasking  multiple threads executes concurrently. A single process may contain several executing threads sharing the same address space.

Explain I/O Filter.

The filter driver determines the total bandwidth of the disk. I/O filters generally used for reading  from one stream and writing another stream.

Can applet in different page communicate with each other?

Yes, An applet can communicate with another applet on different. Since an AppletContext will be created for a single page. If it is in multiple pages, different applet context will be there for different applets.
But even if the applets are on different pages, they run under the same JVM, so we can create an class similar to AppletContext say this class  AppletRegistry, which holds references to all the applets running in the JVM, and this class can be use to hand over the reference to whoever needs it for communication.
This registry should maintain a static hashtable that should keep the map of all the applet objects.

What is the difference between == & .equals().

==  compare reference objects .
equals() compare values .

What is the difference between abstract class & Interface.

Both Abstract class and interface can\'t be instantiated. 

Abstract class may have abstract and non-abstract methods. 

Interface may contain only abstract methods.

 Abstract class doesn\'t support multiple inheritance.Interface supports multiple inheritance.

Abstract class can have final, non-final, static and non-static variables.Interface has only static and final variables.Interface can\'t have static methods, main method or constructor.

Abstract class can provide the implementation of interface.Interface can\'t provide the implementation of abstract class.The abstract keyword is used to declare abstract class.The interface keyword is used to declare interface.Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.

What is singleton class & how you can implementation it?.

singleton :-

What is use of static, final variable?

static variable:- also called class level variable .
Static variables are initialized when class is loaded.
Static variables are initialized before any object of that class is created.
Static variables are initialized before any static method of the class executes

final variable:-
final variable needs initialization always, if you don’t initialize it would throw a compilation error.


The static final variables are constants

Examples of final class.

final class :- A final class is a class that can't be extended.


A final class is a class that can't be extended.

public final class ClasaName{
  //  . . . Class contents
}

What is difference between Event propagation & Event delegation?

What is difference between Unicast & Multicast model?

What is a java bean?

What is use of synchronized keyword?

What are the restrictions of an applet & how to make the applet access the local machines resources?

What is reflect package used for & the methods of it?

What is use of serialization?

Serialization is the process of producing Stream of bytes from the object and writing it into the output source such as file. 

The serialization also keeps information to restore the fields during deserialization.To produce stream of bytes, the class should be inherited either from java.io.Serializable interface.which is marker interface.

Can methods be overloaded based on the return types ?

A method cannot be overloaded on the bases of return types because the compiler will check only the method signature( name of the method and the arguments).

So a method cannot be overloaded on the bases of return types.

What should you do get your browser compatible with swing components?

What are the methods in Applet ?

When is init(),start() called ?

When you navigate from one applet to another what are the methods called?

What is the difference between Trusted and Untrusted Applet ?

What is Exception ?

What are the ways you can handle exception ?

When is try, catch block used ?

Exception handling using try-catch-finally for normal termination. 

Try block : It contains the statements which likely to throw an exception.

 If an exception raised, the remaining statements in the try block are skipped.Catch Block : Executed only if try block throws an exception.Finally Block : To maintain cleanup code

What is finally method in Exceptions ?

To maintain cleanup code while exception handling in try catch block.

What are the types of access modifiers ?

What are the other modifiers ?

Is synchronized modifier ?

Yes, Synchronized means thread safe i.e. only one thread will be executed at a time.

What is inheritance ?

What is method Overloading ? What is this in OOPS ?

What is method Overriding ? What is it in OOPS ?

Does java support multi dimensional arrays ?

Is multiple inheritance used in Java ?

No, Java doesn\'t support multiple inheritance with 
class, but it supports with iterface.

How do you send a message to the browser in JavaScript ?

Does JavaScript support multidimensional arrays ?

Yes! Multi-dimensional arrays can be represented by arrays of arrays. 

var v = new array(3,4,5);

Does JavaScript support multidimensional arrays ?

Is there any tool in java that can create reports ?

What is meant by Java ?

What is meant by a class ?

What is meant by a method ?

Methods are similar to functions or procedures that are available in other programming languages.

Method signature contains method name and parameter list. 

A method contains a set of statements that are combined to do a particular task. And, methods are of two types like predefined library methods and user defined methods.method declared inside class.

What are the OOPS concepts in Java ?

What is meant by inheritance ? Explain with an example.

What is meant by polymorphism ? Explain with an example.

Is multiple inheritance allowed in Java ? Why ?

What is meant by Java interpreter ?

Interpretation happens at runtime(which means while running the Java program) ,turns it into native code.

Compilation of java file will generate class file by calling javac.

Java interpreter is a program which implements the JVM specification and actually executes the bytecodes by running the program.

What is meant by JVM ?

JVM is a Java virtual machine,  JVM is a process that executes a computer program compiled into Java bytecode. Through bytecode java achieves interoperability (platform independent).

What is a compilation unit ?

Source code for a Java class is called a compilation unit. Forms the input for the Java compiler (javac).

What is meant by identifiers ?

What are the different types of modifiers ?

What are the access modifiers in Java ?

What are the primitive data types in Java ?

What is meant by static variable and static method ?

Static variable is also known as class variable, global variable.

The static variable is used to refer the common property of all objects,variables that are common to all objects.Static is a modifier used with class, methods and blocks.

 Static member never associated with object but with class.Static members are loaded when class is loaded into jvm, hence static members are accessed without()before) creating an object itself.

 A static method cannot access instance variable, instance methods and cannot use this or super from static context.

What is meant by Garbage collection ?

GC is automatic memory management, which is a collector attempts to reclaim garbage or memory occupied by objects that are no longer in use by the program(unreferenced objects). Advantage of GC is memory efficient, automatically done.Can be done  By nulling the reference, assigning a reference to another, annonymous object etc.

What is meant by abstract class

What is meant by final class, methods and variables ?

What is meant by a resource leak ?

A resource leak is where memory is being steadily consumed by resources that are no longer being used. In java this situation arises when references to objects that are no longer required.  To avoid this you should remember to set all variables to null as soon as you are finished with the reference. This will allow the gc to free up the memory that the objects were consuming. 

What is meant by a resource leak ?

What is the difference between interface and abstract class ?

What is the difference between public private, protected and static?

1) The scope of the private members is anywhere within the class.
 
2) The scope of the protected members is anywhere with in the same package and only subclass of the different package.
3) The scope of the public members is anywhere!.

static members are Common across all objects
Also called class variable.A static variable cannot access instance method. 
 

What is meant by method overriding ?

A subclass can re-implement superclass method to provide subclass specific implementation. 
Accesibility modifiers of superclass and subclass and return type, method signature must be same.

What is singleton class ?

A class having only one instance.

What is the difference between an array and a vector ?

Array have limitations:
Size fixed, Homogeneous.
While Vector is growable array, allows duplicate elements,ordered, not sorted, Accepts any number of null values. Synchronized,Heterogeneous. 
It is class of Collection interface.

What is meant by constructor ?

What is meant by casting ?

What is the difference between final, finally and finalize ?

What is meant by packages ?

Package is group classes interfaces. Two types built-in package and user defined package.
The package statement should be the first line.
Provides access protection.
Removes naming collision.

What are all the packages ?

Name 2 calsses you have used ?

Name 2 classes that can store arbitrary number of objects ?

What is the difference between java.applet.* and java.applet.Applet ?

What is a default package ?

java.lang package by default,imported implicitly. 

What is anonymous class ?

Anonymous classes make our code compact. They can be declare and instantiate a class at a time. They do not have a name. They are local class only .

This section covers the following topics:

Name interfaces without a method ?

Marker Interface

What is the use of an interface ?

 interface contains abstract class.

What is a serializable interface ?

Converting the state of an object into a byte stream. Serializability of a class is enabled by the class implementing the java.io.Serializable interface.

How to prevent field from serialization ?

Through transient keyword.

What is meant by exception ?

How can you avoid the runtime exception ?

Runtime exceptions are unchecked exceptions, we can handle them through try catch block.
try { 
 ... do stuff ... 
 } catch (SomeException e) { 
 e.printStackTrace(); 
 throw e; 
 } 

What is the difference between throw and throws ?

Throw is used to propagate an exception to its caller inorder to let the calling method to handle an exception rather than implementation method.Throw keyword is always used at block level but not at method signature level.
All built-in exceptions are automatically thrown by the JVM. But, built-in exceptions can be programmatically thrown by the developer using throw keyword.
All user defined exceptions must be programmatically thrown using �throw� keyword.
Syntax:
throw ;
Example:
throw new ArithmeticException(�/ by zero�);
Throws keyword is used at method signature level to specify the type of exception a method throws.
Syntax:
  method_name()
  � <,ExceptionTypeⁿ>{

}

Can multiple catch statements be used in exceptions ?

yes multiple catch statements can be used but it depends upon number of try block which throws an exception.

Is it possible to write a try within a try statement ?

Yes, 
try {
  try {
    throw new Error(\"oops\");
  }
  finally {
    console.log(\"finally\");
  }
}
catch (ex) {
  console.error(\"outer\", ex.message);
}

What is the method to find if the object exited or not ?

What is meant by a Thread ?

A thread is a smallest unit of dispatchable code.
Defining, Instantiating, and Starting threads by
 Extending Thread class
 Implementing Runnable interface
Methds to Prevent Thread execution
 Sleep()
 Join()

What is meant by multi-threading ?

A large program is split into multiple tasks, assign a thread for each task and execute them concurrently is called as multithreading.

What is the 2 way of creating a thread ? Which is the best way and why?

Defining, Instantiating, and Starting new Threads
The code which we want to run as a thread of execution is written inside a run() method.
We can define a thread either by:
1. Extending a java.lang.Thread class
2. Implementing a java.lang.Runnable Interface.
 Runable is better than extending Thread.
it shares the same object to multiple threads.
 if you extends Thread, you can\'t extend another class

What is the method to find if a thread is active or not ?

thread.isAlive() method.

What are the thread-to-thread communication ?

Threads communication is possible in java. A first thread registers with a gateway for receiving communication. Registration includes identifying a location for receiving messages. The gateway maps message payloads received from second threads to the location of the first thread. The first thread detects a payload in the location and consumes it for processing.

What are the thread-to-thread communication ?

What is the difference between sleep and suspend ?

If the thread is not allowed to perform any operations for a particular period of time, then use sleep() method. The sleep() method suspends currently executing thread for the specified time.
Join()
The currently running thread is suspended until the invoking thread completes its execution (and entered into dead state). The currently executing thread joins at the end of the invoking thread. This is used when the currently executing thread cannot continue until the invoking thread completes its execution.

Can thread become a member of another thread ?

What is meant by deadlock ?

There may be situations when two or more process  are put into waiting state simultaneously to get the resources holding by each other.In this position each would be waiting for the other process to release the resource. So both processes gets locked, waits for the each other\'s resource to released. This situation is called deadlock.

What is meant by deadlock ?

How can you avoid a deadlock ?

What are the three types of priority ?

Every thread in java has some priority. The valid priority range is 1 to 10, where 1 is the least and 10 is the max priority.
The Thread class defines the following constants to set some standard priorities:
1) Public static final int MIN_PRIORITY (1)
2) Public static final int NORM_PRIORITY (5)
3) Public static final int MAX_PRIORITY (10)
The thread with highest priority may get (cannot guarenteed) the chance of first execution.
Two threads have the equal priority, we cannot determine which thread will be executed first.
Thread class defines following methods to get and set the thread priorities:
1) Public final int getPriority()
2) Public final void setPriority(int priority)
Default Priority
By default, every thread is set with default priority which is 5.
The default priority of the main thread is also 5.

What is the use of synchronizations ?

Garbage collector thread belongs to which priority ?

low(MIN priority)

What is the use of ‘this’ ?

How can you find the length and capacity of a string buffer ?

public int capacity()
Returns the current capacity. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.
Returns:
the current capacity.
public int length()
Returns the length (character count).
Specified by:
length in interface CharSequence
Returns:
the length of the sequence of characters currently represented by this object.

How to compare two strings ?

CompareTo(), Compare() method

What are the interfaces defined by Java.lang ?

The package java.lang contains classes and interfaces that are essential to the Java language. These are:

Object, superclass of all classes in Java.
Thread, the class that controls each thread in a multithreaded program.
Throwable, the superclass of all error and exception classes in Java.
Classes that encapsulate the primitive data types in Java.
Classes for accessing system resources and other low-level entities.
Math, a class that provides standard mathematical methods.
String, the class that represents strings.
Because the classes in the java.lang package are so essential, the java.lang package is implicitly imported by every Java source file. In other words, you can refer to all of the classes and interfaces in java.lang using their simple names.

What is the purpose of run-time class and system class?

What is meant by Stream and Types ?

What is the method used to clear the buffer ?

What is meant by Stream Tokenizer ?

java.lang.Object
java.io.StreamTokenizer
class takes an input stream and parses it into \"tokens\", allowing the tokens to be read one at a time. The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles.

What is serialization and de-serialisation ?

What is meant by Applet ?

How to find the host from which the Applet has originated ?

What is the life cycle of an Applet ?

How do you load an HTML page from an Applet ?

What is meant by Applet Stub Interface ?

What is meant by getCodeBase and getDocumentBase method ?

How can you call an applet from a HTML file?

What is meant by Applet Flickering ?

How to communicate between applet and an applet ?

What is meant by event handling ?

What are all the listeners in java and explain ?

What is meant by an adapter class ?

What are the types of mouse event listeners ?

What are the types of methods in mouse listeners ?

What is the difference between panel and frame ?

What is the default layout of the panel and frame ?

What is meant by controls and types ?

What is the difference between a scroll bar and a scroll panel?

What is the difference between list and choice ?

How to place a component on Windows ?

What are the different types of Layouts ?

What is meant by CardLayout ?

What is the difference between GridLayout and GridBagLayout

What is the difference between menuitem and checkboxmenu item.

What is meant by vector class, dictionary class , hash table class,and property class ?

Vector is a array whose size can be grown or shrink. Allows duplicate elements.
It is an ordered collection based on index.
Vector is a class of List Interface which is from collection framework.
Allows any number of null values.
By default, vector elements are not sorted.
It is a synchronized collection (thread-safe), since it is a legacy class.
Stack is sub class of Vector.
Dictionary is an abstract class.
Hash table and property are inherited from Map interface which is not derived from collection interface. Based on hashing mechanism.
Keys cannot be duplicated but values can be duplicated.
Both keys and values are unordered i.e., the entries in Hashtable are unordered.
Neither key nor value is null.
By default, hashtable entries are not sorted.
By default, Hashtable is a synchronized Map.
Properties are usually configured in property file with .properties extension.
The entries in property file are key, values and separated with equal (=) symbol.
Though the Properties class is inherited from Hashtable, but both keys and values must be string objects only.
The advantages of using properties file is, the changes can be made in one place, which are reflected across all other placess in our code.

Which class has no duplicate elements ?

Set Interface has no duplicate elements.
HashSet, Linked Hashset, TreeSet class not allows duplicate elements.

What is resource bundle ?

What is meant by Swing ?

What is the difference between AWT and Swing ?

What is the difference between an applet and a Japplet

What are all the components used in Swing ?

What is meant by tab pans ?

What is the use of JTree ?

How can you add and remove nodes in Jtree?

What is the method to expand and collapse nodes in a Jtree?

What is the use of JTable ?

What is meant by JFC ?

What is the class in Swing to change the appearance of the Frame in Runtime?

How to reduce flicking in animation ?

What is meant by Javabeans ?

We can reuse the code by javabeans.Developers can use software components written by others without having to understand their inner workings.

What is JAR file ?

JAR stands for Java ARchive. It\'s a file format based on the popular ZIP file format and is used for aggregating many files into one.
The JAR format also supports compression, which reduces the size of the file and improves download time.

What is meant by manifest files ?

What is Introspection ?

public class Introspector
extends Object.
he Introspector class provides a standard way for tools to learn about the properties, events, and methods supported by a target Java Bean.
For each of those three kinds of information, the Introspector will separately analyze the bean\'s class and superclasses looking for either explicit or implicit information and use that information to build a BeanInfo object that comprehensively describes the target bean.

What are the steps involved to create a bean ?

Say any two properties in Beans ?

What is persistence ?

What is the use of beaninfo ?

What are the interfaces you used in Beans ?

What are the classes you used in Beans ?

What is the diffrence between an Abstract class and Interface?

What is user defined exception ?

Yes! We can also defined our own exceptions according to our requirment. We can do this by extending the Exception class, in this class we override the toString() method.

What is user defined exception ?

What do you know about the garbate collector ?

Garbage collector removes the unreferenced objects from heap memory.
By nulling the reference
By assigning a reference to another
By annonymous object etc.
The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:
protected void finalize()

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.

public static void gc()  

What is the difference between C++ & Java ?

Two main drawbacks with C++ language are : Platform dependent and won�t support Internet and WWW.
To solve these problems, James Gosling developed a new language called JAVA at sun Microsystems in 1991, which is platform independent and supports WWW & Internet.
C++ supports operator overloading multiple inheritance but java does not. Everything (except fundamental types) is an object in Java (Single root hierarchy as everything gets derived from java.lang.Object).
Java does not support pointers, templates, unions, operator overloading, structures etc. 
C++ supports structures, unions, templates, operator overloading, pointers and pointer arithmetic.
Java support automatic garbage collection.
Java, there is a Thread class that you inherit to create a new thread and override the run() method.
C++ has no built in support for threads. 
Java doesn\'t provide multiple inheritance
C++ does support multiple inheritance. 

How do you communicate in between Applets & Servlets ?

What is the use of Servlets ?

In an HTML form I have a Button which makes us to open another page in 15 seconds. How will do you that ?

In an HTML form I have a Button which makes us to open another page in 15 seconds. How will do you that ?

What is the difference between Process and Threads ?

How will you initialize an Applet ?

What is the order of method invocation in an Applet ?

When is update method called ?

How will you communicate between two Applets ?

Have you ever used HashTable and Dictionary ?

What are statements in JAVA ?

A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;).

Assignment expressions
Any use of ++ or --
Method invocations
Object creation expressions

What is JNI ?

 Java Native Interface (JNI) is a programming framework that enables Java code running in a Java Virtual Machine (JVM) to call and be called by[1] native applications (programs specific to a hardware and operating system platform) and libraries written in other languages such as C, C++ and assembly.

What is the base class for all swing components ?

What is JFC ?

The Java Foundation Classes (JFC) are a graphical framework for building portable Java-based graphical user interfaces (GUIs). JFC consists of the Abstract Window Toolkit (AWT), Swing and Java 2D. Together, they provide a consistent user interface for Java programs.
Encompass a group of features for building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java applications

What is Difference between AWT and Swing ?

Considering notepad/IE or any other thing as process, What will Happen if you start notepad or IE 3 times? Where 3 processes are started or 3 threads are started ?

How does thread synchronization occurs inside a monitor?

How will you call an Applet using a Java Script function ?

Is there any tag in HTML to upload and download files ?

Why do you Canvas ?

How can you push data from an Applet to Servlet ?

What are the benefits of Swing over AWT ?

Where the CardLayout is used ?

What is the Layout for ToolBar ?

What is the difference between Grid and GridbagLayout ?

How will you add panel to a Frame ?

What is the corresponding Layout for Card in Swing ?

What is light weight component ?

What is bean ? Where it can be used ?

What is difference in between Java Class and Bean ?

A Bean is a Java class, but a Java class does not have to be a bean. Bean reusable software.
A Java class is meant to carry out the different database
operations like retrtieveing data, inserting data and
updating data.

What is the mapping mechanism used by Java to identify IDL language ?

The idlj compiler uses the IDL-to-Java language mapping to convert IDL interface definitions to corresponding Java interfaces, classes, and methods, which can be use to implement client and server code.

Diff between Application and Applet ?

What is fertilizable Interface ?

What is the difference between CGI and Servlets?

CGI (Common Gateway Interface) is an attempt at providing users with dynamic content. It allows users to execute a program that resides in the server to process data and access database to produce the relevant data. They are written in the native operating system and then stored in a specific directory. 
A servlet is an implementation of Java that aims to provide the same service as CGI does, but instead of programs compiled in the native operating system, it compiles into the Java bytecode which is then run in the Java virtual machine. Though Java programs can be compiled into the native code, they still prefer to compile in the Java bytecode.

What is the use of Interface ?

Interface provides service details not the implementation details to the user.
�It is used to achieve full abstraction.
�By interface, we can achieve multiple inheritance.
 

Why Java is not fully objective oriented ?

Because of primitive data types.Multiple Inheritance, Operator Overloading not possible in java.

Why does not support multiple Inheritance ?

java doesn\'t support multiple inheritance directly because it leads to overiding of methods when both extended class have a same method name. this will leads to ambiguity in executing.

What it the root class for all Java classes ?

Object is the root class for all java classes.

What is polymorphism ?

Suppose If we have variable " I " in run method, If I can create one or More thread each thread will occupy a separate copy or same variable will be shared ?

If we have a local variable declared in the run method then all the existing thread will hava a separate copy for that variable. If we are using the instance variable in the run method then this will be shared by all the existing variable.

Suppose If we have variable ‘ I ‘ in run method, If I can create one or More thread each thread will occupy a separate copy or same variable will be shared ?

What is Constructor and Virtual function? Can we call virtual?

What is function in a constructor ?

The main function of constructor to do initialisation followed by instantiation.
It is calle to create an object.
A constructor resembles an instance method, but it differs from a method in that it has no explicit return type.  Constructors often have the same name as the declaring class.
Default constructor(no parameter).
Parameterised Constructor (with parameter)

What is function in a constructor ?

Why we use OOPS concepts? What is its advantage ?

What is the difference in between C++ and Java ? can u explain in detail?

Java supports classes, but does not support structures or unions.
Write once, run anywhere, Platform independent (Interoperability).
Due to byte code and run by JVM.
C++ supports multiple inheritance but java doesn\'t.
Pointers are not in java, All classes in Java ultimately inherit from the Object class.
Java does not support operator overloading.

What is the exact difference in between Unicast and Multicast object ? Where we will use ?

Unicast is a one-to one connection between the client and the server.
A multicast packet is from one machine to one or more. The difference between a multicast packet and a broadcast packet is that hosts receiving multicast packets can be on different lans

In a Container there are 5 components. I want to display the all the components names, how will you do that one ?

In a Container there are 5 components. I want to display the all the components names, how will you do that one ?

Why there are some null interface in java ? What does it mean ?

Null Interfaces know as Marker Interfaces having no method.There is a method clone() in Object class.Examples  Serializable, Cloneable.

Give me some null interfaces in JAVA ?

 Serializable, Cloneable.

Tell me the latest versions in JAVA related areas ?

What is meant by class loader ? How many types are there? When will we use them ?

The Class.forName() loads the class into the JVM.
It loads the class into the JVM for further use.
We use this when we want to load JDBC-ODBC drivers.
Class Loader is a part of JVM used to load the classes dynamically. It will load the classes based on demand. Diffrent types of class loaders are extension class loader, system class loader and bootstrap class loader. Bootstrap class loader loads the classes in rt.jar and i18n.jar, extension class loader loads the class in ext dir, system class loader loads all other classes in the class path.
 two type. 
1) Static Loading. 
2) Dynamic Loading. Dynamic way is done by the help of class.forName();
Extensions Class Loader,System Class Loader.

What is meant by flickering ?

What is meant by cookies ? Explain ?

A message given to a Web browser by a Web server. The browser stores the message in a text file. The message is then sent back to the server each time the browser requests a page from the server.
 Every time the user loads the website, the browser sends the cookie back to the server to notify the website of the user\'s previous activity.
Each cookie is effectively a small lookup table containing pairs of (key, data) values
session cookie and persistent cookie.

Which problem you had faced in your earlier project?

How OOPS concept is achieved in Java?

What is features for using Java?

How does Java 2.0 differ from Java 1.0?

Public static void main - Explain?

public is a access modifier, static means dosent belongs to an object, void means main does not return any value, main( ) is the method called when a Java application begins.

What are command line arguments?

Passed at the time of running the java program. Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.
Java application can accept any number of arguments from the command line.
when you invoke an application, the runtime system passes the command line arguments to the application\'s main method via an array of Strings. Each String in the array contains one of the command line arguments

Explain about the three-tier model?

What is difference between String & StringBuffer?

String is immutable and stringbufffer is mutable

What is Wrapper class. Is String a Wrapper Class?

What are the restriction for static method Purpose of the file class?

What is Default modifier in Interface?

Difference between Interface & Abstract class?

Can abstract be declared as Final?

Can we declare variables inside a method as Final Variables?

What is the package concept and use of package?

A package is a namespace that organizes a set of related classes and interfaces. Java platform provides an enormous class library (a set of packages) suitable for use in your own applications.It is a group of classes, interfaces 
Advantage is reusability. Packages are of two types. User defined package, built in package.

How can a dead thread be started?

Difference between Applet & Application?

What is Life cycle of the Applet?

Can Applet have constructors?\

Differeence between canvas class & graphics class?

A Canvas object provides access to a Graphics object via its paint() method. 

Differeence between canvas class & graphics class?

Explain about Superclass & subclass.

What is AppletStub?

Explain Stream Tokenizer?

What is the difference between two types of threads?

What is Checked & Unchecked exception?

What is use of throws exception?s

What is finally in exception handling Vector class?

What will happen to the Exception object after exception handling?

Explain. Two types of multi-tasking.

Explain Two ways to create the thread.

Explain Synchronization.

Explain I/O Filter.

Can applet in different page communicate with each other?

Why Java is not 100 % pure OOPS ? ( EcomServer )?

When we will use an Interface and Abstract class ?

How to communicate 2 threads each other ?

inter thread communication can be done by 3 methods wait(), notify(),notifyall().

Describe difference between method overriding and overloading?

Both are type of polymorphism, method overloading having same method name but different parameter list (number, order, type), it is resolved at compile time so it is known as Early binding.
Method overriding having same method name, parameter list and return type is also same.It is resolved at runtime therefore called Late binding.

What is the restriction on an Overridden methods’ accessibility ?

If we are overriding the method in the same package\'s class then it must not be the private member. If we are overiding the method is the other package\'s class, then it must not be the private and default. 

What is the restriction on an Overridden methods’ accessibility ?

Can a method be overloaded by different return type but same argument type?

No! For method overloading, the parameter list must be changed. Method overloading does not depend the on return type.

Can a method be overloaded by different return type but same argument type?

What is a "stateless" protocol?

What is constructor chaining and how to do this in Java?

Super class constructors are always executed before subclass constructors is called as constructor chaining.
�this()� is used to call matching constructor from the same class.
�super()� is used to call matching constructor from immediate superclass.

What is constructor chaining and how to do this in Java?

Contructor can be overloaded,i.e. a single class can hava more than one contructor. A construct may call to another constructor. The first statement in the constructor must be a call to either this() or  super() but not both. The super() will call the matching superclass constructor according to the number of arguments passed in the super(). A this() will call the overloaded constuctor in the same class according to the parameter list. The called constructor may also make a call to the other constructor using this(). This type of contructor calling in the same class is called constructor chaining.

What is passed by ref and by value?

When we make a call to the method, we may pass some values in the parameter list. When we pass the actual value of the variable, it simply pass the copy of the variable not actual value. Hence change in the copy of that variable will not affect the actual value of that variable.

When we passed the object reference into the parameter list in to a method call, we are actually passing the copy of bits that refer to the object somewhere into the memory not actual value of the object. If we modify the object using the reference of that object will also affect the actual value of that passed object.

What is passed by ref and by value?

How to ensure size of a primitive data type?

Means that all variables must first be declared before they can be used.the operating system allocates memory and decides what can be stored in the reserved memory

Elaborate the Garbage Collection process in Java ?

What is a difference between An interface and an abstract class?

In DB access where to write the query. In JSP or servlet?

We can write query in both JSP page and servlet. It depends upon you. But it is better to separate classes to make a database connection, pass the reference to the JSP page and write query using JSTL 2.0(Java Standard Tag Library).

In DB access where to write the query. In JSP or servlet?

Explain difference between Constructer and a method

Constructors are the special member, they do not have a return type. We can call the methods explicitly but constructors are called automatically when we create the object using the new operator. The purpose of constructor is to allocate the memory to the object and initialize the class\' variables. If you don\'t provide the constructor in your class, the compiler will insert the default constructor.

Explain difference between Constructer and a method

What is serialization in Java?

Object can be represented as a sequence of bytes that includes the object\'s data as well as information about the object\'s type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.

Describe difference between an error and an exception?

What are differences between procedural and object oriented language?

Object Orientated Programming and Procedure Oriented Programming are basically two different paradigms for writing code. In procedural programming the main emphasis is on procedure while in object oriented the data is important part. on the same hand data is more secured in object oriented program. Procedural programming separates the data of the program from the operations that manipulate the data. The fundamental advantage of OO programming is that the data and the operations that manipulate the data (the code) are both encapsulated in the object. Object Oriented programming deals with the elemental basic parts or building blocks of the problem, whereas Procedural programming focuses on the steps required to produce the desired outcome. In OOP, decomposing the problem into smaller discrete pieces called \"Objects\". 

What are differences between procedural and object oriented language?

What is the difference between a Class and an Object ?

A class is a construct that defines a collection of properties and methods. It can be viewed as a template.
Object is an instance of a class.

Why threads block or enters to waiting state on I/O?

Threads block or enters to waiting state on I/O, so that other threads may execute while the i/o
Operation is performed. 

What are transient variables in java?

A transient variable is a variable that may not be serialized. It is not stored as part of its objects persistent state. The value of the variable can\'t be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

How Observer and Observable are used?

The JDK provides a reusable embodiment of the pattern in the form of the java.util.Observer interface and the java.util.Observable class. Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.  
In Observer Pattern, object maintains a list of its dependents and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.

What is List interface ?

List is an ordered collection of elements. The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index. Unlike sets, lists typically allow duplicate elements. The List interface includes operations for the following:

    * Positional access 
    * Search
    * Iteration 
    * Range-view 

Useful methods of the List Interface:

  * add()
  * clear()
  * contains()
  * get()
  * isEmpty()
  * listIterator()
  * remove()
  * size()

What is the difference between yield() and sleep()?

Thread.sleep(1000) method hands over the control to other thread for a particular time period. Whereas Thread.yield() method causes the currently executing thread object to temporarily pause and allow other threads to execute according to the scheduling algorithm the CPU is running on.

Can we call finalize() method ?

 No! The finalize method is invoked by the JVM/GarbageCollector on Objects which are no longer referenced.

What is the initial state of a thread when it is created and started?

The thread is in ready state. 

Can we declare an anonymous class as both extending a class and implementing an interface?

No. An anonymous class can extend a class or implement an interface, but it cannot be declared to do both 

What is the differences between boolean & operator and && operator?

When we use boolean & operator between the two operands then both the operands are evaluated. If we are using the && operator between the two operands then second operand is evaluated if the first operand is true. 

What is an abstract method ?

An abstract method does not have a body. It contains only method signature terminated by a semicolon instead of curly braces. Abstract method can be declared only within the abstract class or within the interfaces. The definition to the abstract method will be provided by the class which extends the abstract class or implements the interface.

what is a the difference between System.err and System.out

The System.out writes to  the \"standard output\". The System.err writes to \"standard error\". These two streams are setup by the operating system when the Java program is executed, and can be redirected with the uses of \"|\", \">\", etc. on the command line. You can redirect the output of the System.out to any other file. The following example can help to understand the concept :

public class Test{
public static void main(String args[]){
System.out.println(\"Output of System.out\");
System.err.println(\"Output of System.err\");
}
}

First Execution -
C:>java Test
Output of System.out
Output of System.err

Second Execution -
C:>java Test > abc.txt
Output of System.err

In the second execution we diverted only the std output stream and std err stream remained unchanged. i.e., by this way, we can handle error stream separately.

What is the difference between synchronized block and synchronized method ?

Both the synchronized method and block are used to acquires the lock for an object. When you mark a method synchronized, then you are forcing every thread which calls that method to lock the monitor. If you expect a synchronized() {} block in the calling code, it is possible that some code which calls your method might neglect to
use synchronized() and end up with a threading problem in your program. synchronized code always use objects as locks to prevent other threads from entering the synchronized block. For instance methods, they are synchronized on the \'this\' reference, and for static methods they are synchronized on the instance of the Class object method belongs to. Best practice is to minimize the code inside synchronized blocks because they prevent concurrent threads from executing - losing any advantage of multi-threaded applications. Synchronized blocks help let those portions of a method that do not access shared resources to be run simultaneously while still keeping those parts that need to be shared thread-safe.

How can you force garbage collection in java?

You can not force the JVM for the garbage collection. However you can call the System.gc() method in your program to tell the JVM that it may the time to perform garbage collection. But it is upto the JVM that if will call the  System.gc() method or not. There is no way to force the JVM, it works fine without programmer\'s intervention.

How can you call a constructor from another constructor ?

Yes, we can call the constructor but within the another constructor of the same class using the this(). 

How can you call the constructor of super class ?

We can call the superclass constructor by making a call to super() in the subclass constructor.

What must be the order of catch blocks when catching more than one exception?

When you use multiple catch blocks, it is important to remember that exception subclasses must come before any of their superclasses. This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus a subclass would never be reached if it came after its superclass. Further, in Java, unreachable code is an error.

How can we call a method or variable of the super class from child class ?

We can use super.methodNme() or super.variableName.

If you are overriding equals() method of a class, what other methods you might need to override ?

If you are overriding equals() method of a class, then the other methods you might need to override is hashCode(). 

What is externalizable ?

Externalizable is an Interface that extends Serializable Interface. Java provides Externalizable interface that gives you more control over what is being serialized. This interface defines 2 methods: readExternal() and writeExternal() and you have to implement these methods in the class that will be serialized. In these methods you\'ll have to write 
code that reads/writes only the values of the attributes you are interested in.

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 ispossible for programs to use up memory resources faster than they are garbage collected. As garbage collection is JVM dependent then It is possible for programs to use memory resources faster than they are garbage collected.Moreover garbage collection cannot be enforced,it is just suggested.

What is a native method?

A native method is the Java interface to non-Java code. It is Java\'s link to the \"outside world\". A native method is a Java method whose implementation is provided by non-java code. A native method is one for which the body of the method is defined elsewhere, entirely outside the Java Virtual Machine, in a library. Only methods can be declared as native. A native code is written in a non-Java language, typically C or C++, and compiled for a single target machine type.

Syntax :
native public void Native1( ) ; 

What is the difference between a continue statement and a break statement?

break completely exits the loop. Continue skips the statements after the continue statement and keeps looping.

What must a class do to implement an interface?

If a class implements the interface, it must provides the definition to all the methods declared in the interface or it must be the abstract class. If it is an abstract class then the first concrete subclass must provides the definition to the interface\'s mathods and abstract methods of the abstract class.

What is the difference between notifyand notifyAll method ?

THe notify() method wakes up a single thread waiting on the object and passes the control of the monitor to it. The notifyAll() method will wake up all the threads waiting on the object and will select a thread to pass control to it. The unselected thread will again go back to sleep
in the JVM scheduler list and they will need yet another call to notifty (or notifyAll) in order to wake them up. The notifyAll() method is the same as the notify() method. The only difference is that in this case all the threads from the non-empty wait set of the object are removed and are re-enabled for thread scheduling in stead of only one thread from the wait set being picked arbitrarily, removed, and re-enabled for thread scheduling as is the case in notify() method.

What does wait method do ?

The wait() method is defined in the Object class. The method 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. 

Threads - wait() method do :

    * the wait() method causes a thread to release the lock it is holding on an object; allowing another thread to run.
    * the wait() method is defined in the Object class.
    * wait() can only be invoked from within synchronized code.
    * it should always be wrapped in a try block as it throws IOExceptions.

There are actually three wait() methods

   1. wait()
   2. wait(long timeout)
   3. wait(long timeout, int nanos) 

 The timeout is measured in milliseconds. when wait() is called, the thread becomes disabled for scheduling and lies dormant until one of four things occur:

   1. another thread invokes the notify() method for this object and the scheduler arbitrarily chooses to run the thread
   2. another thread invokes the notifyAll() method for this object
   3. another thread interrupts this thread
   4. the specified wait() time elapses 

What are the different states of a thread ?

The different stated of a thread :
  * NEW : A Fresh thread that has not yet started to execute. 
  * RUNNABLE : A thread that is executing in the Java virtual machine. 
  * BLOCKED : A thread that is blocked waiting for a monitor lock. 
  * WAITING : A thread that is wating to be notified by another thread. 
  * TERMINATED : A thread whos run method has ended. 

What is the difference between static and non static inner class ?

A non-static inner class may have object instances that are associated with instances of the class\'s outer class. A static inner class does not have any object instances.

What is the difference between readers and streams?

The Reader/Writer classes is character-oriented and the InputStream/OutputStream classes is byte oriented.

Why we cannot override static methods?

Static methods are class bound rather than runtime object type bound. That means they cannot be overridden since polymorphism doesn\'t hold. We can\'t override the static methods. We know overriding depends upon the inheritance. Since the static methods are not inherited, hence we can not override static methods. If u try to that, you are actually redefining the superclass version of the static method, this is not an override.

When does a compiler supplies a default constructor for a class?

If a class has no constructors, then the compiler provides a default constructor for that class.

What will happen if an exception is not caught ?

An uncaught exception results in the uncaughtException() method of the thread\'s ThreadGroup being invoked, which eventually results in the termination of the programin.

What are the different ways in which a thread can enter into waiting state?

A thread can enter into waiting state in 3 ways:
  * sleep() method.
  * wait() method.
  * suspend() method.

What is a ResourceBundle class?

Resource bundle used to contain locale-specific objects. When your program needs a locale-specific resource, a String for example, your program can load it from the resource bundle that is appropriate for the current user\'s locale. This allows you to write programs that can:

    * be easily localized, or translated, into different languages.
    * handle multiple locales at once.
    * be easily modified later to support even more locales.

The Java ResourceBundle class eases the process of separating localized resources from an application\'s source code, but you may want to extend the ResourceBundle class to better fit your needs.

What is numeric promotion?

Numeric promotion contexts allow the use of an identity conversion or a widening primitive conversion. Numeric promotion is the conversion of a smaller numeric type to a larger numeric type,so that integer and floating-point operations may take place. In numerical promotion,byte, char, and short values are converted to int values. The int values are also convertedto long values, if necessary. The long and float values are converted to double values. Numeric promotions are used to convert the operands of a numeric operator to a common type so that an operation can be performed. In java, if u are arithematic operator on the operands then :
    *  If either operand is of type  double, the other is converted to  double.

    * Otherwise, if either operand is of type float, the other is converted to float.

    * Otherwise, if either operand is of type long, the other is converted to long.

    * Otherwise, both operands are converted to type int.

 

What is the difference between the prefix and postfix forms of the ++ operator?

Prefix ++ operator first increments the value of operand by 1 and then return the value. Postfix ++ operator first reutrn the value and then increments the value of operands by 1.

What is the difference between a switch statement and an if statement?

Both the statements provides the condition checking of the expressin but Switch statement reduces the complexity of using the multiple if-else clause.

What is hashCode?

The hashCode() is id number allocated to an object by JVM. Objects in Java have hash codes associated with them. An object\'s hash code is a signed number that identifies the object (for example, an instance of the parent class). An object\'s hash code may be obtained by using the object\'s hashCode() method as follows:
 
int hashCode = SomeObject.hashCode();

The method hashCode() is defined in the Object class and is inherited by all Java objects. In order for the Java Collections to work properly (and everything else in Java), the equals() and hashCode() methods must be compatible. Here, compatible means that if equals() reports that two instances are the same, then the hashCode() of both instances must be the same value. 

What is the difference between RandomAccessFile and File?

The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

What is the difference among JVM Spec, JVM Implementation, JVM Runtime ?

A Java virtual machine or JVM is a virtual machine that runs Java byte code. This code is most often generated by Java compilers, although the JVM has also been targeted by compilers of other languages. The JVM has a stackA stack is a data structure that works on the principle of Last In First Out (LIFO). This means that the last item put on the stack is the first item that can be taken off, like a physical stack of plates. A stack-based computer system is one that is base based architecture. The JVM has instructions for the following groups of tasks

    * Load and store
    * Arithmetic
    * Operand stack management (push / pop)
    * Type conversion
    * Control transfer (branching)
    * Object Creation and Manipulation
    * Method invocation and return
    * Throwing exceptions 

What is the difference between Hashtable and HashMap ?

The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. A hashmap is not synchronized and faster than hashtable. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. HashMap does not guarantee that the order of the map will 
remain constant over time. 

Why java is said to be pass-by-value ?

Java is strictly pass-by-value. A common misconception exists that parameters in Java are passed by reference. They are not. Parameters are passed by value. Java doesn\'t pass method arguments by reference, it passes them by value i.e. it simply copies the bit pattern holding by the references.

What do you mean by immutable ? How to create an immutable object ?

Immutable objects means the value of that object can not be modify by applying operations on them. Java Provides the String class to create the mutable string objects.

String s = new String(\"Immutable string.\");  

What is a weak reference ?

A weak reference is a reference that does not protect the referenced object from the garbage collector. 

What is object cloning?

Object cloning means creating the identical object of any object. If you say :

obj1=obj2;

In the above statement obj1 is not actually making another copy of object, it simply makes the copy of reference bits. For this purpose java provides the clone() method for object cloning. This method is defined by the Object class. 

What is object pooling?

An object pool is a set of initialised objects that are kept ready to use. Object pooling is a way to manage access to a finite set of objects among competing clients. in other words,
object pooling is nothing but sharing of objects between different clients. Pooling basically means utilizing the resources efficiently, by limiting access of the objects to only the period the client requires it. Object pooling can offer a significant performance boost; it is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low.

What is the disadvantage of garbage collection?

We know that an object is ready to garbage collected if it is not reachable by any reference. JVM has the facility for the reference counting. Suppose a parent object that has a reference to its child object, which has a reference back to its parent. These objects will never have a reference count of zero even though they may be unreachable by the roots of the executing program. Another disadvantage is the overhead of incrementing and decrementing the reference count each time. Because of these disadvantages, reference counting currently is out of favor.
Garbage collection have some disadvantages:

    * The application�s working set may be larger.
    * Performance may not be as good as if you hand-optimize memory management (for more details, see �Performance�).
    * A common design pattern whereby resources are tied to the lifetime of objects does not work effectively under GC.
    * You must ensure that for any object you want to be long-lived you maintain a chain of strong references to it from a root object, or resort to reference counting for that object.

What are tag interfaces?

The Tag interface defines the basic protocol between a Tag handler and JSP page implementation class. It defines the life cycle and the methods to be invoked at start and end tag. 

What are the restrictions placed on static method ?

 Static method hava some of the following restrictions : 
    * Static methods can not be overridden.
    * Static methods can only be invoked directly without object reference within the same class and with the class name in another class.
    * There is only one copy of static method for the entire class.
    * They are available before creating the instance of the class.
    * Static method can\'t be declared as final or abstract.

What is JIT?

The JIT (just-in-time compiler), also known as dynamic translation, is a technique for improving the runtime performance of a computer program. Java program is compiled into an intermediate language called bytecodes, and it can be downloaded through the network and executed on any computers that have Java execution environment. JIT compiler is a program that turns Java bytecode into instructions that can be sent directly to the processor. The JIT  is a code generator that converts Java bytecode into machine language instructions. Some Java Virtual Machines (VMs), including the VM in the Netscape Navigator browser, include a JIT in addition to a Java interpreter. Java programs compiled by a JIT generally run much faster than when the bytecode is executed by an interpreter. 

What is the Locale class?

A Locale class represents a specific geographical, political, or cultural region. The Locale class allows you to control how multilanguage text is displayed in a Flash application at runtime. 

We and create a Locale object using the constructors in this class:

    * Locale(String language)
    * Locale(String language, String country)
    * Locale(String language, String country, String variant)
     

What is the difference between URL and URLConnection?

The URL has a number of component parts. The URL locates a the resource over the internet. The URL class encapsulates Internet URLs. In a way, it does for the Internet resources what the File class does for local files. URL instance represents the location of a resource, and a URLConnection instance represents a link for accessing or communicating with the resource at the location.

What are the two important TCP Socket classes?

The two important TCP Socket classes : 

    * Socket 
    * ServerSocket 

Socket class allows us to read and write through the sockets. It provides two methods : getInputStream() and getOutputStream().
ServerSocket is used for normal two-way socket communication. 

Strings are immutable. But String s=\"Hello\"; String s1=s+\"World\" returns HelloWorld how ?

  String s=\"Hello\"; 
  String s1=s+\"World\";
In the second line above, We are trying to concatenating the \"Hello\" and a new strign object \"World\". Here a new object is created \"HelloWorld\" and returned to the reference s1. Since string objects are immutable, the reference s is still pointing to \"Hello\".

What is classpath?

The classpath is the connection between the Java runtime and the filesystem. It defines where the compiler and interpreter look for .class files to load or the CLASSPATH is an environment variable that tells the Java compiler javac.exe where to look for class files to import or java.exe where to find class files to interpret. The class path can be set using either the -classpath option when calling an SDK tool (the preferred method) or by setting the CLASSPATH environment variable.

What is path?

A path tells the java compiler and java interpreter where ot find the classes they need to execute or import. Multiple entries in the class path are separated by a semicolon on Windows (;) and by a colon on UNIX (:). 

What is java collections?

The Java collections framework is a set of classes and interfaces that implement commonly reusable collection data structures. A collection framework includes :
  * Collection Interface     
  * Iterator Interface     
  * Set Interface   
  * List Interface   
  * ListIterator Interface   
  * Map Interface   
  * SortedSet Interface   
  * SortedMap Interface 
  * HashSet & TreeSet Classes     
  * ArrayList & LinkedList Classes
  * HashMap & Treemap Classes Vector & Stack Classes

Can we compile a java program without main?

Yes! We can compile our java program without main() method.

What is static initializer block? What is its use?

After method and constructor, Initialization blocks are the third place where the operations can be performed. Initialization block do not have identifier and they are of two types :

  * Instance initialization block.
  * static initializaton block. 
 
Static initialization block starts with the keyword static with opening and ending curly braces. Static initialization block is used to initialize the static variable of the class because they are available before any instance created of the class i.e. before executing the constructor. Hence static initialization block are the right place to initialize the static variable. 

How does a try statement determine which catch clause should be used to handle an exception?

When an exception is thrown within the try block the JVM start searching from the first catch block associated with the try block, the first matching catch block is executed and rest are ignored.

If a class doesn\'t have any constructors, what will happen?

If a class doesn\'t have any constructors, the compiler will supply the default constructor.

What will happen if a thread cannot acquire a lock on an object?

If a thread cannot acquire a lock on an object, it will enter to the waiting state until it acquire the lock on that object.

What will happen if you are invoking a thread's interrupt method while the thread is waiting or sleeping?

What is coupling?

Coupling is the degree of dependence between the two modules. Coupling is broken down into loose coupling, tight coupling, and decoupled. Coupling is also used to describe software as well as systems. It is good to have low coupling between the modules for better object oreinted design.

How will you define an interface?

The following syntax is used to define the interface :
 accessModifier interface InterfaceName{
   dataType var1;
   dataType var2;
   ..............
   ..............
   void method1();
   void method2();
   ..............
   ..............
   }

Here accessModifier may be default or public.
Interface may contain constant variables. These variables are implicitly public static final, you don\'t have to type it explicitly.
Interface can have only public abstract methods, you dont have to type public abstract modifiers explicitly.

How will you define an abstract class?

An abstract class have abstract modifier in its declaration. An abstract class can contain  instance variable, methods that can be concrete methods and abstract methods. An abstract class may not have any abstract method, that does not mean that it is not an abstract class.

Example :

public abstarct AbstractClass{
// instance variable
int a;
int b;
//instance methods
public int getValue(){}
public void setValue(int){}
//abstract method
public int getMaxValue();
}

What is a JVM heap?

The JVM heap is where the objects of a Java program live. The JVM\'s heap stores all objects created by an executing Java program. Objects are created by Java\'s \"new\" operator, and memory for new objects is allocated on the heap at run time. The JVM heap size determines how often and how long the VM spends collecting garbage. A Java Virtual Machine on 32-bit operating systems typically has a maximum heap size of 64Mb. You can modify the JVM heap size .

What is daemon thread?

Threads that work in the background to support the runtime environment are called daemon threads. Daemon threads are typically used to perform services for your application/applet. The virtual machine exits whenever all non-daemon threads have completed. Two methods are used in this context: 

  public final void setDaemon(boolean isDaemon)
  public final boolean isDaemon()

By default a thread you create is not a daemon thread. However you can use the setDaemon(true) method to turn it into one. Daemon thread is a low priority thread which runs in the back ground doing the garbage collection operation for the java runtime system.

What is a green thread?

What is volatile variable?

Volatile means the storage is likely to change at anytime and be changed but something outside the control of the user program. This means that if you reference the variable, the program should always check the physical address (ie a mapped input fifo), and not use it in a cashed way. Variables declared to be volatile will not be optimized by the compiler because the compiler must assume that their values can change at any time. We use volatile keyword to declare the volatile variable.

What is diamond problem?

Suppose You are having the four classes named A, B, C, and D. Assume that class A is the superclass of class B and class C. Now in a programming language, that support multiple inheritance, class D can inherit from the two classes B and C. Suppose class A has a variable v and this variable is inherited in the classes B and C. Again v is inherited by the class D from B and C. Now class D has indirectly inherited variable v form the class A but class D contain two version of the variable b inherited from classes B and C. This is the reason that Java does not support Multiple inheritance. This problem is called diamong problem, because if we desing it graphically, it looks like a diamond shape.

How many JVM's we can run in a system?

Why ArrayList is faster than Vector?

Arraylist is faster than the Vector because ArrayList doesn\'t have synchronisation overhead, i.e. ArrayList has synchronized methods.

What is the security mechnaism used in java?

Java is considered more secure than any other language because of its bytecode facility. Java applet\'s bytecode is dynamically downloaded over the network instead of the .exe file and executed by the JVM in the browser. So there is no overhead of virus or currepted file, because the JVM also checks the length of the bytecode.

Security Implementation Mechanisms : 

  * Java Authentication and Authorization Service (JAAS).
  * Java Generic Security Services (Java GSS-API).
  * Java Cryptography Extension (JCE).
  * Java Secure Sockets Extension (JSSE).
  * Simple Authentication and Security Layer (SASL).

Java security services are separate from the security mechanisms of the operating system.
Java provides security at various layers:

  * Application-Layer Security : At the application layer, application firewalls can be employed to enhance application protection by protecting the communication stream and all associated application resources from attacks.

  * Transport-Layer Security : Transport-layer security relies on secure HTTP transport (HTTPS) using Secure Sockets Layer (SSL). Transport security is a point-to-point security mechanism that can be used for authentication, message integrity, and confidentiality. 

 * Message-Layer Security : In message-layer security, security information is contained within the SOAP message and/or SOAP message attachment, which allows security information to travel along with the message or attachment. 

What is phantom memory?

The Phantom memory is a false memory. Memory that does not exist in reality. Phantom references point to objects that are already dead and have been finalised.
 

What is reflection?

Reflection is an API in java that allows an executing Java program to examine or \"introspect\" upon itself, and manipulate internal properties of the program. For example, it\'s possible for a Java class to obtain the names of all its members and display them. A reflection is what you see when you look in the mirror. Reflection is for dealing with class files you know very little about ahead of time. It is a powerful approach to analyze the class at runtime. If new classes are added into your application dynamically then Reflection is used to get the structure of the class. 

Example : 

import java.lang.reflect.*;
 
   public class ShowMethods {
      public static void main(String args[])
      {
         try {
            Class c = Class.forName(args[0]);
            Method methods[] = c.getDeclaredMethods();
            for (int i = 0; i < methods.length; i++)
            System.out.println(methods[i].toString());
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

What are the differences between JIT and HotSpot?

HotSpot is a JIT compiler. JIT is a part of the JVM that compiles Java bytecode to native machine code at runtime, to make your Java program run faster. HotSpot is the name of Sun\'s JIT compiler which is included in Sun\'s JVM. HotSpot generate native machine code for the CPU that they execute on.

How would you implement a thread pool?

Creating too many threads in one JVM can cause the system to run out of memory or thrash due to excessive memory consumption. To prevent resource thrashing, server applications need some means of limiting how many requests are being processed at any given time. A thread pool offers a solution to both the problem of thread life-cycle overhead and the problem of resource thrashing.

Methods in org.apache.avalon.cornerstone.blocks.threads that return ThreadPool
 ThreadPool AbstractThreadManager.getThreadPool(java.lang.String name) :  Retrieve a thread pool by name.
 ThreadPool AbstractThreadManager.getDefaultThreadPool() :   Retrieve the default thread pool.
  

What is the difference between throw and throws clause?

What is the difference between Comparable and Comparator ?

The comparable interface should be used when the current object is to be compared to objects of its type only.
The comparator should be used when some external class is taking your class as a parameter for some comparison operation and it doesn\'t know how to compare the objects and expects you to give it. You have a set of objects where you want to sort it in both ascending and decending order. Just Comparable will not help you in this. Here you can implement your own comparator and pass it to the sorting algorithm to use. 

What is the difference between List, Set and Map?

List is an ordered collection of elements by index. Key methods of List are : get(int index), indexOf(Object o), add(int index, Object o), etc.

A Set cares about Uniqueness, it doesn\'t allow duplicates elements. The equals() method helps you to find out whether two objects are identical.

A map stores the elements in the form of Key/Value pairs. Here key and value both are objects. A map cares about unique key (unique ID) to a specific value. You can search value in a Map by giving its key.

What is the difference between Exception and Error ?

Exceptions are the abnormal condition that you can handle by your program, but Error is an unrecoverable condition that can be handled by the program at runtime. Both Exceptiona and Error classes are drived from the class Trowable. Java running out of memory is an Error and can not be handled by the program.

What is meant by Open Source ?

Java is an open source language that means you are free to download the java compiler and JVM. You don\'t have to buy these software. 

How do you send data from an applet to Servlet ? What are the steps involved in it ?

The applet can send a GET/POST request to the servlet by opening a servlet URL with a query string. For example : 

// servlet URL 
URL url = new URL(getCodeBase(), \"/MyServlet?name=ABC\");

// open a connection to the servlet
URLConnection servletCon = url.openConnection();
servletCon.setDoInput(true); // true, if we get data back

// get the input stream from the servlet
InputStream in = servletCon.getInputStream();

// read the response from the servlet
..................
..................
}

What are the different inner classes types?

Different types of inner classes :

  * Regular inner classes.
  * Method local inner classes.
  * Anonymous inner classes.
  * Static nested classes.

What is Nested top-level classes?

Nested top-level classes are declared within an enclosing class. Nested top-level classes are always defined with a static keyword. A nested top-level class/interface is defined as a static member of its enclosing class/interface, i.e. static inner classes are called nested top level classes.

What is Member classes?

A member class is one that is declared within the class as like member varaibles and member functions.
These classes are called inner classes, and can be instantiate with only if the enclosing class has been intantiated.

Can a top level class be private or protected?

No! A top level class can\'t be private or protected, it can only be either public or default. 

How will you invoke any external process in Java?

 When invoked, the process starts but does not complete. Sometimes this may appear to be caused by the input that is being fed to the process which adds to the confusion over why the problem occurs.When you invoke any process from Java, you must use separate threads to pump data to/from

What is composition?

Composition is a design technique that establishing relationships between classes. There are two fundamental ways to relate classes : inheritance and composition. Composition is an alternative way of inheritance to ralate classes. 
Example :

class Fruit {

    //...
}

class Mango {

Fruit fruit = new Fruit();
    //...
}

What is aggregation?

Aggregation is a collection of several things grouped together or aggregation is a special kind of association that specifies a whole or a part of relationship. For example : A \'Car\', is consisted of an engine,a steering wheel, four tires, seats, gear box, fuel tank, engine oil tank, air filters etc. So all constituents of car are parts of it. 
Aggregation is transitive, i.e., if A is a part of B, and B is a part of C, then A is also a part of C.

Aggregation is antisymmetric, i.e., if A is a part of B, then B is not a part of A.

What are the methods in Object?

The methods of Object class are : 
  * protected Object clone() : Creates and returns a copy of this object.
  * boolean equals(Object obj) : Indicates whether some other object is \"equal to\" this one.
  * protected void finalize() : Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
  * Class getClass() : Returns the runtime class of an object.
  * int hashCode() : Returns a hash code value for the object.
  * void notify() : Wakes up a single thread that is waiting on this object\'s monitor.
  * void notifyAll() : Wakes up all threads that are waiting on this object\'s monitor.
  * String toString() : Returns a string representation of the object.
  * void wait() : Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
  * void wait(long timeout) : Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
  * void wait(long timeout, int nanos) : Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.
  

What is the relationship between synchronized and volatile keyword?

When two or more threads access the shared variable and perform read/write operations, this variable should be declared within the synchronized method. The Java language allows threads that access shared variables to keep private working copies of the variables; this allows a more efficient implementation of multiple threads. The volatile modifier requests the Java VM to always access the shared copy of the variable so the its most current value is always read. 
Either put the variables in a synchronized method or block, or declare them volatile.

What factors are used to decide using synchronized or volatile?

What are the drawbacks of inheritance?

Drawbacks of inheritance :
    * Difficulty of understanding complex hierarchy.
    * Makes writing a compiler harder, e.g. requires more dynamic type checking since type of an object can change during runtime.
    * Adversely affects execution speed, program size, program complexity, and incurs method passing overhead.
    * Inheritance forces a set of methods and fields on a class. You may not want some of these, and it is not necessary that all of these are required. There is no concept of partial inheritance. 
    * Interface stability of base classes sometimes require even more complexity.

What are the restrictions placed on the values of each case of a switch statement?

The restrictions placed on the values of each case of a switch statement are :

    * The values of each case of a switch statement must be a compile time constant.
    * Only use the values that can be promoted to an int value, i.e. use byte, short, char, int only.


If aaaa is an array then why aaaa.length why not aaaa.length()?

In Java API, we have an Array class which has a variable named \"length\" to count the length of the array, hence we say, aaaa.length to count the length of the array.

In the String class, we have a method named length(), which returns the length of the string. 

What is dynamic typing?

In most of the programming languages, variables can be assigned value in two ways : First, at the time of variable declaration. Second, later in the program. If you assigned value to variable later in the program, then the varaible will not hava a value at the time of compilation, it will be assigned a value at runtime. This runtime assignment of value to variable is called Dynamic typing.

What is static typig?

Assignment of value to the variable at the time of variable declaration is called static typing.

What is HashMap and Map?

Map is an Interface and HashMap is a class that implements the Map interface. HashMap is not serialized.

What is an Object and how do you allocate memory to it?

An object is a runtime entity. It is an instance of the class and have its own state, made up of values assigned to all variables of its class collectively. An object will hava access to all the behaviours(methods) of its class.

The object can be allocated memory using the \"new\" keyword. For Example : 
//class declaration
class CrateObject{
}
//Object creation
CreateObject o = new CreateObject();

What is UNICODE?

Java uses the unicode character set for all the characters and symbols of the world. The Unicode provides the Standard character set to support all language, platform, program. Before the invention of Unicode, many different character sets and encodings had to be used for different languages. It was not possible to store plain text files containing text from languages using different character sets in the same document. Unicode provides a unique number for every character. The  Unicode Consortium is a non-profit organization founded to develop, extend and promote use of the Unicode Standard, which specifies the representation of text in modern software products and standards. 

What is a stream and what are the types of Streams and classes of the Streams?

A stream is sequence of flowing data. Stream is an abstract class in Java, that is used to either read the data or write the data to/from a disk file, device, a network socket, other programs, a memory array etc.

There are two types of streams that Java support :
    * Byte oriented streams.
    * Characters oriented streams.

Classes of the Streams :
    * BufferedInputStream
    * BufferedOutputStream
    * BufferedReader
    * BufferedWriter
    * ByteArrayInputStream
    * ByteArrayOutputStream
    * CharArrayReader
    * CharArrayWriter
    * DataInputStream
    * DataOutputStream
    * FileInputStream
    * FileOutputStream
    * FileReader
    * FileWriter
    * FilterInputStream
    * FilterOutputStream
    * FilterReader
    * FilterWriter
    * InputStream
    * InputStreamReader

	

    * LineNumberReader
    * ObjectInputStream
    * ObjectOutputStream
    * OutputStream
    * OutputStreamWriter
    * PipedInputStream
    * PipedOutputStream
    * PipedReader
    * PipedWriter
    * PrintStream
    * PrintWriter
    * PushbackInputStream
    * PushbackReader
    * RandomAccessFile
    * Reader
    * SequenceInputStream
    * StreamTokenizer
    * StringReader
    * StringWriter
    * Writer
 

What is the difference between TCP/IP and UDP?

TCP/IP is a reliable connection oreinted network protocol. It ensure that a file sent from one network node to another node is a complete file.

UDP is a connectionless, unreliable network protocol. 

UDP is faster than TCP/IP. UDP is used where the speed of data transmission is more important than reliability.

What is Inter-Thread communication?.

In multithreading environment multiple threads run concurrently, sometimes you need two thread to communicate to each other by forwarding the data. The multithread data access and communication classes are: Mutex, Condition, and Lock

What is a thread group?

A thread group represents a set of threads. Every Java thread is a member of a thread group. In addition, a thread group can also include other thread groups. Threads can only access the ThreadGroup to which they belong. Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually. A tree structure can be formed from ThreadsGroups containing other ThreadGroups. 
Java provides the ThreadGroup class for creating and managing the thread groups. The ThreadGroup class provides two constructors :

ThreadGroup(String name)
ThreadGroup(ThreadGroup parent, String name)

Why is UTFDataFormatException thrown by DataOutputStream.writeUTF() when serializing a String?

Why is OutOfMemoryError thrown after writing a large number of objects into an ObjectOutputStream?

When you write a large number of objects into an Object output stream, these objects might be unreachable by the reference that the reference table is hoding. If they are not garbage collected by the JVM, resulting the running out of memory error. A call to the ObjectOutputStream.reset() method resets the object/handle table to its initial state, allowing all previously written objects to be eligible for garbage collection. 

How can I get the serialVersionUID of a class?

The following code can help u to obtain serialVersionUID of a class

import java.io.*;

public class jk 
{
	public static void main(String args[]) 
	{
		String s = new String(\"test\");
		Class cl = s.getClass();
		long uid = ObjectStreamClass.lookup(cl).getSerialVersionUID();
		System.out.println(uid);
	}
}


What is output of following code package r4r.co.in.core.java; public class HelloWorld { static int i = 0; public static void main(String args[]) { new HelloWorld(); } static { i = 10; System.out.println(i); } }

This output of the above program :
    10  

What is output of following code package r4r.co.in.core.java; public class HelloWorld { int i = 0; public static void main(String args[]) { System.out.println(i); new HelloWorld(); } static { int i; i = 10; System.out.println(i); } }

The above program give an error in compilation, like a non-static field can be referenced from a static context. The problem lies in the variable i in print statement inside the main()  method. The variable i can only be accessed through the object reference.

What is output of following code package r4r.co.in.core.java; public class HelloWorld { int i = 0; public static void main(String args[]) { System.out.println(i); new HelloWorld(); } static { static int i; i = 10; System.out.println(i); } }

The above program give an error in compilation, illigal start of expression at static int i in the static initialization block.

What is output of following code package r4r.co.in.core.java; public class HelloWorld { int i = 0; public static void main(String args[]) { System.out.println(i); new HelloWorld(); } static { final static int i=0; i = 10; System.out.println(i); } }

The above program give 3 errors in compilation : 
  1. a non-static variable i can be referenced from a static context in the main method. 
  2. modifier static is not allowed in the static initialization block.
  3. can\'t assign a value to final variable.

What is output of following code package r4r.co.in.core.java; public class HelloWorld { static int i = 0; public static void main(String args[]) { System.out.println(i); new HelloWorld(); } static { final int i=0; i = 10; System.out.println(i); } }

The above program will give an error : can not assign a value to a final variable at i=10 in the static initialization block.

What is output of following code package r4r.co.in.core.java; public class HelloWorld { static int i = 0; public static void main(String args[]) { System.out.println(i); new HelloWorld(); } static { static final int i=0; i = 10; System.out.println(i); } }

Program will give error : illigal start of expression at \"static final int i=0;\"

What is output of following code package r4r.co.in.core.java; public class HelloWorld { static int i = 0; public static void main(String args[]) { System.out.println(i); new HelloWorld(); } static { static int i=0; i = 10; System.out.println(i); } }

Program will give error : illigal start of expression at \"static int i=0;\"

What is output of following code package r4r.co.in.core.java; public class HelloWorld { static int i = 0; public static void main(String args[]) { System.out.println(i); display(); } void display(){ i=90; System.out.println(i); } }

The program will give error : a non-static method display() can be referenced from a static context.

What is output of following code package r4r.co.in.core.java; public class HelloWorld { static int i = 0; public static void main(String args[]) { System.out.println(i); display(); } static void display(){ i=90; System.out.println(i); } }

Output of the program :

  0
  90

What is output of following code package r4r.co.in.core.java; public class HelloWorld { static int i = 0; public static void main(String args[]) { System.out.println(i); display(); } static void display(){ int i=0; i=90; System.out.println(i); } }

Output of the program :

  0
  90

What is output of following code package r4r.co.in.core.java; public class HelloWorld { static int i = 0; public static void main(String args[]) { System.out.println(i); display(); HelloWorld h=new HelloWorld(); h.display(); } static void display(){ int i=0; i=90; System.out.println(i); } }

Output of the program :

  0
  90
  90

What is output of following code package r4r.co.in.core.java; public class HelloWorld { static int i = 0; public static void main(String args[]) { System.out.println(i); HelloWorld h=new HelloWorld(); h.display(); } void display(){ int i=0; i=90; System.out.println(i); } }

Output of the program :

  0
  90

What is output of following code package r4r.co.in.core.java; public class HelloWorld { static int i = 0; public static void main(String args[]) { System.out.println(i); display(); HelloWorld h=new HelloWorld(); h.display(); } void display(){ int i=0; i=90; System.out.println(i); } }

The program will give an error : a non-static method display() can not be referenced from a static context.

What is \'this\' ?

This keyword is basically a Java keyword ,\'this\' can be used to access class variables and methods.

What is thread ?

thread is the basically as basic unit of program execution. A process can have several threads running concurrently, each performing a different job, such as waiting for events or performing a time consuming job that the program doesn\'t need to complete before going on. When a thread has finished its job, the thread is suspended or destroyed. See also process.

What is throw ?

Throw is the bassically as a Java keyword that allows the user to throw an exception or any class that implements the \"throwable\" interface.

What is throws ?

Throws is the basically a Java keyword , It is used in method declarations that specify which exceptions are not handled within the method but rather passed to the next higher level of the program.

What is transaction ?

Transaction is basscially an atomic unit of work that modifies data. A transaction encloses one or more program statements, all of which either complete or roll back. Transactions enable multiple users to access the same data concurrently.

What is transient ?

transient is the basically a keyword in the Java programming language that indicates that a field is not part of the serialized form of an object. When an object is serialized, the values of its transient fields are not included in the serial representation, while the values of its non-transient fields are included.

What is try ?

try is the basically as a Java keyword that defines a block of statements that may throw a Java language exception. If an exception is thrown, an optional catch block can handle specific exceptions thrown within the try block. Also, an optional finally block will be executed regardless of whether an exception is thrown or not.

What is type ?

It is basically a class or interface.

What is variable ?

Variable is the basically identifier, which item of data named by an identifier. Each variable has a type, such as int or Object, and a scope. 

For example :


  1. Class variable,
  2. Instance variable,
  3. local variable.

What is void ?

Void is basically a type of Java keyword , It is used in method declarations to specify that the method does not return any value. void can also be used as a nonfunctional statement.

What is volatile ?

Volatile is basically a Java keyword used in variable declarations that specifies that the variable is modified asynchronously by concurrently running threads.

What is while ?

While is the basically a type of Java keyword, It is used to declare a loop that iterates a block of statements. The loop\'s exit condition is specified as part of the while statement.

What is wrapper ?

Wrapper is the type of object, its encapsulates and delegates to another object to alter its interface or behavior in some way.

What is class method ?

Class method is the bassically a that type method which is invoked without reference to a particular object. Class methods affect the class as a whole, not a particular instance of the class. Also called a static method. See also instance method.

What is class variable ?

Clas variablw is the basscially a type of data item which is associated with a particular class as a whole not with particular instances of the class. Class variables are defined in class definitions. Also called a static field. See also instance variable.

What is constructor ?

A pseudo-method that creates an object. In the Java programming language, constructors are instance methods with the same name as their class. Constructors are invoked using the new keyword.

What is this?

That is the bassically a java keyword which is used for the represent an instance of the class in which it appears.

What is WAR file ?

Web application archive file. A JAR archive that contains a Web module.

What is the mean of Utility Classes?

A Utility class is bassicaly a class that contains grouped static  functionality

Can a java source file hava more than one public classes?

yes

What invokes a thread�s run() method?

After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread\'s run() method when the thread is initially executed.


What are the advantages of Spring framework?

The advantages of Spring framework are:

  1. Spring is a layered architecture
  2. Spring Enables POJO (Plain Old Java Object) Programming. POJO programming enables continuous integration and testability.
  3. Dependency Injection and Inversion of Control Simplifies JDBC
  4. Spring is an open source framework available to all for commercial purpose.

What are features of Spring ?

Features of Spring :

Lightweight :- Spring is lightweight in terms of size and overhead. The entire spring network can be distributed in a single JAR file that weights in at just over 1 MB.

Inverse of Control :- The basic concept of the Inversion of Control pattern is that you do not create your objects but describe how they should be created. You don\'t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A IOC container) is then responsible for looking it all.

Aspect-Oriented :- Spring supports the features of aspect oriented programming approach that enables cohesive development.

Container :- Spring is a container because it manages the life cycle and configuration of application objects.

Framework :- Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI.

What are the various steps involved in a Spring beans life cycle?

The bean factory performs several steps before a bean is ready is use:
  1.   Instantiate.
  2.   Populate properties.
  3.   The factory calls BeanNameAware\'s setBeanName() method.
  4.   The factory calls BeanFactoryAware\'s setBeanFactory() method.
  5.   PostProcessBeforeInitialization() method is called if BeanPostProcessor associated with the bean.
  6.   An init-method is called, if specified.
  7.   Finally, PostProcessAfterInitialization() is called if BeanPostProcessor associated with it.

What do you mean by bean wiring in Spring container?

Piecing together beans within the Spring container is known as wiring. Wiring the beans means you are telling the Spring container what beans are needed and how the container should use dependency injection to tie them together. You should have some basic idea of XML for basic wiring of beans.

How do add a bean in spring application?

A bean can be added in spring application using :

<beans>
   <bean id=\"foo\" class=\"com.Foo\"/>
   <bean id=\"bar\" class=\"com.Bar\"/>
</beans>


in the Spring configuration file. In the bean tag the id attribute specifies the bean name and the class attribute specifies the fully qualified class name. 

What is XMLBeanFactory in Spring framework?

The org.springframework.beans.factory.xml.XmlBeanFactory is a class that implements the BeanFactory interface. To create an XmlBeanFactory, pass a java.io.InputStream to the constructor. The InputStream will provide the XML to the factory. For example, the following code snippet uses a java.io.FileInputStream to provide a bean definition XML file to XmlBeanFactory.

    BeanFactory factory = new XmlBeanFactory(new FileInputStream(\"beans.xml\"));

To retrieve the bean from a BeanFactory, call the getBean() method by passing the name of the bean you want to retrieve.

    MyBean myBean = (MyBean) factory.getBean(\"myBean\");

What are singleton beans and how can you create prototype beans?

The singleton property of <bean> tells the context whether or not a bean is to be defined as a singleton. 
This attribute in bean tag named \"singleton\" if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true.

So, all the beans in spring framework are by default singleton beans.
    <beans>
       <bean id=\"bar\" class=\"com.act.Foo\" singleton=\"false\"/>
   </beans> 

Prototyped beans are useful when you want the container to give a unique instance of a bean each time it is asked for, but you still want to configure one or more properties  of that bean through Spring.
  <bean id=\"student\"  class=\"com.StudentImpl\"
    singleton=\"false\">

A new instance of a prototype bean will be created each time getBean() is invoked with the bean\'s name.

How can you reference a bean from another bean in Spring?

We use the <property> element to set the properties that reference other beans. 

The <ref> sub-element of <property> lets us do this:

  <bean id=\"foo\"
     class=\"com.Foo\">
    <property name=\"bar\">
      <ref bean=\"bar\"/>
    </property>
  </bean>

What is inner bean in Spring fremawork?

You can embed a <bean> element directly in the <property> element.

For Example:

<bean id=\"student\"
    class=\"com.StudentImpl\">
    <property name=\"course\">
      <bean class=\"com.CourseImpl\"/>
    </property>
  </bean>

The drawback of wiring a bean reference in this manner is that you can\'t reuse the instance of StudentImpl anywhere else.
            

How will you handle the ambiguities of autowiring in Spring?

When autowiring using byType or constructor, it\'s possible that the container may find two or more beans whose type matches the property\'s type or the types of the constructor arguments. What will happen if there are  ambiguous beans suitable for autowiring?

Spring can\'t sort out ambiguities and chooses to throw an exception rather than guess which bean you meant to wire in. If you encounter such ambiguities when autowiring, the best solution is not to autowire the bean.

How will you wire a string value to a property whose type is a non-string?

Yes. You can wire a string value to a property whose type is a non-string. The java.beans.PropertyEditor interface provides a means to customize how String values are mapped to non-String types. 7

This interface is implemented by java.beans.PropertyEditorSupport that has two methods:

getAsText() : returns the String representation of a property\'s value.
setAsText(String value) : sets a bean property value from the String value passed in.

If you want to map the non-string property to a String value, the setAsText() method is called to perform the conversion.

What is throws advice in Spring?

The ThrowsAdvice lets you definebehaviour should an exception occur. ThrowsAdvice is a marker interface and contains no method but need to be implemented. A class that implements this interface must have at least one method with either of the following two signatures:
  * void afterThrowing(Throwable t)
  * void afterThrowing(Method m, Object[] o, Object target, Throwable t)

Explain about PreparedStatementCreator?

The PreparedStatementCreator interface is a callback interfaces used by the JdbcTemplate class. This interface creates a PreparedStatement given a connection, provided by the JdbcTemplate class. Implementations are responsible for providing SQL and any necessary parameters. A PreparedStatementCreator should also implement the SqlProvider interface if it is able to provide the SQL it uses for PreparedStatement creation. This allows for better contextual information in case of exceptions. 
It has one method:
PreparedStatement createPreparedStatement(Connection con) throws SQLException

Create a statement in this connection. Allows implementations to use PreparedStatements. The JdbcTemplate will close the created statement. 

What are the benefits of the Spring Framework transaction management ?

Spring Framework supports:

  1. Programmatic transaction management.
  2. Declarative transaction management.

Spring provides a unique transaction management abstraction, which enables a consistent programming model over a variety of underlying transaction technologies, such as JTA or JDBC. Supports declarative transaction management. Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA. Integrates very well with Spring\'s various data access abstractions.

public class Test { static boolean XYZ(char a) { System.out.print(a); return true; } public static void main(String args[]) { int i=0; for(XYZ(\'P\'); XYZ(\'Q\')&&(i<2); XYZ(\'R\')) { i++; XYZ(\'S\'); } } }

PQSRQSRQ

What is right to way to declare array of primitives?

type var-name[];
OR
type[] var-name;

// both are valid declarations
int intArray[];
or int[] intArray;

byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];

int[] intArray = new int[30];
int[] intArray = new int[]{ 1,2,3,4,5,6,7};

Variable Declarations

We know about the variable access, Which is signifies to the ability of code in one class to access a variable in another class, in this case we\'ll looking at the other keywords that apply to variable declarations,but first we\'ll do a quick review of the difference between instance and local variables.

Instance Variables

Instance variable is basically a signifies inside the class but in the outside of any method and its initialized when class is initialized. its mainly a field which is belongs to the unique object.This is following in the code.:

class Employee {
// define fields (instance variables) for employee instances
private String name;
private String title,
private String manager;
// other code goes here including access methods for private fields
}

Local (Automatic/Stack/Method) Variables

Local variable is basically use for the declared within a method, Its means mainly variable is not just initialized within the method, but also declared within the method, Local variable is basically in always n the stack but its not happening in the case of heap.if the variable is an object reference the object itself will still be created on the heap.

There is no such thing as a stack object, only a stack variable.

class TestServer {
public void logIn() {
int count = 10;
}
}

The compiler will reject any code that tries to use a local variable that hasn\'t been assigned a value, because unlike instance variables local variables don\'t get default values.

class TestServer {
public void logIn() {
int count = 10;
}
public void doSomething(int i) {
count = i; // Won\'t compile! Can\'t access count outside method login()
}

It is possible to declare a local variable with the same name as an instance variable.

class TestServer {
int count = 9; // Declare an instance variable named count
public void logIn() {
int count = 10; // Declare a local variable named count
System.out.println(\"local variable count is \" + count);
}
public void count() {
System.out.println(\"instance variable count is \" + count);
}
public static void main(String[] args) {
new TestServer().logIn();
new TestServer().count();
}
}

OUTPUT is :
local variable count is 10
instance variable count is 9

Final Variables

final variable is basically declared by the final keyword , It makes impossible to reinitialize that variable once it has been initialized with an explicit value.

object reference variable is basically a reference variable marked final can\'t ever be reassigned to refer to a
different object.When the data is in the object form and we would like to modified but the reference variable can not be changed , we can also say like we can use final reference to modify the object it refers to, but we can\'t modify the reference variable to make it refer to a different object.there are no final objects, only final references.

 A reference variable\'s value in other words, the bit pattern the variable holds is not an object,A reference variable holds bits that represent, in a platform-dependent format, a way to get to an object.

We can see in this code :
class FinalTest{
final int x; // Will not work unless x is assigned in the constructor
public void showFinal() {
System.out.println(\"Final x = \" + x);
}
}

Attempting to compile the preceding code gives us the following:
%javac FinalTest.java

FinalTest.java:2: Blank final variable \'x\' may not have been
initialized. It must be assigned a value in an initializer, or in
every constructor.
final int x;
1 error

 If we would like to declare an instance variable as final, but don\'t give it an explicit value at the time we declare it, the variable is considered a blank final. The final instance variable can stay blank only until the constructor completes.

class FinalTest{
final int x; // Will work because it\'s initialized in the constructor
public FinalTest() {
x = 28; // Whew! The compiler is relieved that we took care of it
System.out.println(\"Final x = \" + x);
}
}

declaring an object reference variable as final:
import java.util.Date;
class TestClass {
final Date d = new Date();
public void showSample() {
d.setYear(2001); //Altering Date object, not d variable, so it\'s OK
}
}

Transient Variables

If we mark to the instance variable as a transient variables , When we enter to the serialize the object declaring it then the java to ignore this variable. 

Serialization is the very good and important feature of the java , When we would like We can save it and also called the flatten an object by writing its state we can also say the value of its instance variables to a special type of IO stream.

Volatile Variables

A Volatile modifier explains the JVM that a thread accessing the variable must always reconcile which is own private copy of the variable with the master copy of the memory .

The volatile modifier may also be applied to project managers

Static Variables and Methods

Static modifiers has a many special type of methods and variables which is treating as a concepts entirely separate from the other modifiers.the count will just be initialized back to a default value with each new instance. The answer to both the utility method always runs the same scenario and the keep a running total of instances scenario is to use the static modifier. Variables and methods are marked static which is belong to the class, That\'s why we can use static method or variable without having any instances of that class at all. We need only have a class available to be able to invoke a static method or access a static variable.

Static variables : It can be accessed without having an instance of a class. But in this case instance a static variable of a class will be shared by all instances of that class; there is only one copy, That are following in this code.

class Frog {
static int frogCount = 0; // Declare and initialize static variable
public Frog() {
frogCount += 1; // Modify the value in the constructor
}
public static void main (String [] args) {
new Frog();
new Frog();
new Frog();
System.out.println(\"Frog count is now \" + frogCount);
}
}

Accessing Static Methods and Variables

Accessing Static method is very impotent for the any code .When instance of the classes in the code is absence then how to code is appropriate that  we can use the accessing static method for make a appropriate code. 
So in this way we access a static method (or static variable) is to use the dot operator on the class name, as opposed to on a reference to an instance, as follows :
class Frog {
static int frogCount = 0; // Declare and initialize static variable
public Frog() {
frogCount += 1; // Modify the value in the constructor
}
}

class TestFrog {
public static void main (String [] args) {
new Frog();
new Frog();
new Frog();
System.out.print(\"frogCount:\"+Frog.frogCount); //Access static variable
}
}    


Another point to remember is that static methods can\'t be overridden! This doesn\'t mean they can\'t be redefined in a subclass, as we\'ll see a little later when we look at overriding in more detail, but redefining and overriding aren\'t the same thing.

Things you can mark as static:
Methods
Variables
Top-level nested classes
                  Things we can\'t mark as static :
Constructors
Classes
Interfaces
Inner classes
Inner class methods and instance variables
Local variables

Declaration Rules

Declaration rules is basically a identifying correctly constructed source files, package declarations, import statements, class declarations, interface declarations, method declarations, variable declarations, and identifiers.

Source File Structure

We just focusing about Source File Structure which is the kind of import and package issues .The following legal code declares a class Foo, in package com.geeksanonymous : 

package com.geeksanonymous; // Notice the semicolon
class Foo { }

Here in this code its singing a only one package statement per source cod file , that\'s are following as :

package com.geeksanonymous;
package com.wickedlysmart; // Illegal! Only one package declaration allowed
class Foo { }

If class Foo adds any import statement then the code is :
 package com.geeksanonymous;
import java.util.*; // Wildcard package import
import com.wickedlysmart.Foo; // Explicit class import
class Foo { }
 
If the Class Foo dont have a package then the import statements must be above the:

class declarationof the above code .as folows :
import java.util.*; // Wildcard package import
import com.wickedlysmart.Foo; // Explicit class import
class Foo { }

Using Import Statements

We can use import function in the two ways :
  1. wildcard import
  2. explicit class import

Import statements are little more than a way for us to save keystrokes when we\'re typing our code. We essentially give the class a longer name, which we call the fully qualified name.

The compiler would never know what you meant if you typed the following:

class Bar {
void doStuff() {
Foo f = new Foo(); // Here you want the WickedlySmart version
} // But how will the compiler know?
}

To eliminate the confusion, you\'re required to do one of two things to help the
compiler:

1. Use an import statement,

import com.wickedlysmart.Foo;
class Bar {
void doStuff() {
Foo f = new Foo(); // Now the compiler knows which one to use
}
}

or
2. Use the fully qualified name throughout your code:

class Bar {
void doStuff() {
com.wickedlysmart.Foo f = new com.wickedlysmart.Foo() // No doubts
}
}

Formatting the main() Method

When we want our code to actually run, We have to get the ball rolling with a main() method. The following rules apply to the main() method :
  1. It must be marked static.
  2. It must have a void return type.
  3. It must have a single String array argument.
  4. We can name the argument anything we want.
It should be declared public (for the purposes of the exam, assume it must be public).
                 other methods is that it has the signature the JVM is looking for when you invoke Java as follows :
java MyClass
           method the one with a signature matching what the JVM is searching for. If it finds the matching method, We are good to go. If it doesn\'t, We get a runtime error like this :

Exception in thread \"main\" java.lang.NoSuchMethodError: main
              The tricky thing about this error is that we can get it even when there is a main()
method. The following code compiles fine, but still produces the previous NoSuchMethodError when we try to invoke this class from the command line:

class MyClass {
public void main (String [] args) { }
}

Interface Implementation

Interface implementation is a identifying class that correctly implement N an interface which is from java.lang

Declaring an Interface

When we create an interface We can define the functioning of the class i mean to say we can define whats the exactly the call can do .without saying anything about how the class will do it. Interface is basically a contract.

Declaring Interface Constants

In this interface we are allowed to put a constants in an interface,it would be much easier for programmers to remember names like HIGH_GRAVITY, LOW_BOUNCE, and HIGH_BOUNCE as opposed to knowing the exact int values corresponding to each of those. we have a following code :

public final static int LOW_BOUNCE = 4;
public final static int HIGH_GRAVITY = 3;
//
That way, if a method takes the int values,
public void animateIt(int gravity, int bounceFactor) { }
then the code that calls animateIt() can substitute the constants wherever the
int values are expected, as follows:
animator.animateIt(LOW_GRAVITY, HIGH_BOUNCE);
  changes we\'ve made
to the Bounceable interface:
public interface Bounceable {
int LOW_GRAVITY = 1;
int MEDIUM_GRAVITY = 2;
int HIGH_GRAVITY = 3;
int LOW_BOUNCE = 4;
int MEDIUM_BOUNCE = 8;
int HIGH_BOUNCE = 12;
void bounce();
Interface Implementation (Exam Objective 4.2) 59
void setBounceFactor(int bounceFactor);
void setGravity(int gravity);
}

By placing the constants right in the interface, any class that implements the interface
has direct access to the constants, just as if the class had inherited them. For example,
the following would be legal for a Bounceable implementation class:

class Ball implements Bounceable {
// Lots of exciting code goes here
public void bounce() {
animator.animateIt(LOW_GRAVITY, HIGH_BOUNCE); // MUCH easier this way
}
// Still more action-packed code goes here
}

We have a some Rules for the interface constraints :
  1. public
  2. static
  3. final

Implementing an Interface

When we would like to implement an interface , we\'re agreeing to adhere to the contract defined
in the interface. its mean we are authorized person for the provide legal implementations for
every method defined in the interface,and that anyone who knows what the interface methods look like (not how they\'re implemented, but how they can be called and what they return) can rest assured that they can invoke those methods on an instance of our implementing class.


We looked earlier at several examples of implementation classes, including the Ball class that implements Bounceable, but the following class would also compile legally:

public class Ball implements Bounceable { // Keyword \'implements\'
public void bounce() { }
public void setBounceFactor(int bf) { }
}

Implementation classes must adhere to the same rules for method implementation as a class extending an abstract class. In order to be a legal implementation class, a nonabstract implementation class must do the following:

  1. Provide concrete (nonabstract) implementations for all methods from the declared interface.
  2. Follow all the rules for legal overrides
  3. Declare no checked exceptions on implementation methods other than those declared by the interface method, or subclasses of those declared by the interface method.
  4. Maintain the signature of the interface method, and maintain the same return type (but does not have to declare the exceptions declared in the interface method declaration).

How does the UNIX system identify user?

The system identifies you by the user id and group id assigned to you by system administrator. You don\'t need to remember your user id and group id, the system translate username as user id and group name as group id. You need to know your username only.

what are responsibilities of a struts action class?which responsibility is view related aspect of boundary component?Does it provide any facilities for separating these view related aspects for the controller related action classes?

An Action class in the struts application extends Struts \'org.apache.struts.action.Action\" Class. Action class acts as wrapper around the business logic and provides an interface to the application\'s Model layer. It acts as glue between the View and Model layer. It also transfers the data from the view layer to the specific business process layer and finally returns the processed data from business layer to the view layer.

An Action works as an adapter between the contents of an incoming HTTP request and the business logic that corresponds to it. Then the struts controller (ActionServlet) slects an appropriate Action and creates an instance if necessary, and finally calls execute method.

To use the Action, we need to  Subclass and overwrite the execute() method. In the Action Class don\'t add the business process logic, instead move the database and business process logic to the process or dao layer.

The ActionServlet (command) passes the parametrized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

) The new operator creates a single instance named class and returns a reference to that object. what does this mean

The new operator instantiates a class by allocating memory for new object and returning a reference to that memory. The new operator also invokes the object constructor.
The new operator dynamically allocates memory for an object. It has this general form:
class-var = new classname( );
The reference returned by the new operator does not have to be assigned to a variable.
The answer is that Java\'s simple types are not implemented as objects. Rather, they are implemented as \"normal\" variables

What is difference between jdk1.4 and jdk1.5?

Following is added into jdk1.5 .which was not into jdk1.5:
Java Language Features
    Generics 
    Enhanced for Loop 
    Autoboxing/Unboxing 
    Typesafe Enums 
    Varargs 
    Static Import 
    Metadata (Annotations) 
Virtual Machine
    Class Data Sharing 
    Garbage Collector Ergonomics 
    Server-Class Machine Detection 
    Thread Priority Changes 
    Fatal Error Handling 
    High-Precision Timing Support

So many other new features has been added.

Is actionform belongs to the model or view or controller in struts?

ActionForm class is used to capture user-input data from an HTML form and transfer it to the Action Class. ActionForm plays the role of Transport Vehicle between the presentation Tire & Business Tier.

Life Cycle :
1. Request received by Controller
2. Create or recycle ActionForm
3. Call reset()
4. store ActionForm in proper scope
5. populate ActionForm from Request
6. Validate the ActionForm
7. If errors found then forward back to input attribute page(configured in Action mapping in struts-config.xml) with

ActionForm in scope. If no errors found then call execute() with the ActionForm.

The steps would be like this (in terms of the diagram)

A. Client will point to the controller
B. Controller would point to action form
C. Actionform would point to action class
D. Action class would point to JSP?
E. JSP would point to client

Why do we need multiple catch block with single try

It contains the statements which likely to throw an exception.
If an exception is raised, the remaining statements in the try block are skipped.
Try block must be followed by either catch or finally or both.
The catch block is executed only if try block throws an exception.
Catch block cannot be written without try block. For each try block there can be zero or more catch blocks.

How do we config struts config file in spring configuration file?

To use the Struts Spring plugin, add the ContextLoaderPlugIn to your Struts config file (usually struts-config.xml):

    <plug-in className=\"org.springframework.web.struts.ContextLoaderPlugIn\">
        <set-property property=\"contextConfigLocation\"
            value=\"/WEB-INF/applicationContext.xml\"/>
    </plug-in>


The \"contextConfigLocation\" property is the location of the Spring beans configuration file.

For each action that uses Spring, you need to define the action mapping to use org.springframework.web.struts.DelegatingActionProxy and declare a matching (action \"path\" == bean \"name\") Spring bean for the actual Struts action. This is an example of an action that requires an instance of UserDatabase:

<action path=\"/logon\"
               type=\"org.springframework.web.struts.DelegatingActionProxy\">
      <forward name=\"success\"              path=\"/logon.jsp\"/>
    </action>

The corresponding Spring bean configuration:

    <bean id=\"userDatabase\" class=\"org.apache.struts.webapp.example.memory.MemoryUserDatabase\" destroy-method=\"close\" />
    
    <bean name=\"/logon\" class=\"org.apache.struts.webapp.example.LogonAction\">
      <property name=\"userDatabase\"><ref bean=\"userDatabase\" /></property>
    </bean>

For more information on the Spring configuration file format, see the Spring beans DTD.

The Struts action org.apache.struts.webapp.example.LogonAction will automatically receive a reference to UserDatabase without any work on its part or references to Spring by adding a standard JavaBean setter:

    private UserDatabase database = null;    

    public void setUserDatabase(UserDatabase database) {
        this.database = database;
    }

What is the Struts 2.0 flow?

Struts and webwork has joined together to develop the Struts 2 Framework. Struts 2 Framework is very extensible and elegant for the development of enterprise web application of any size. In this section we are going to explain you the architecture of Struts 2 Framework.

Request Lifecycle in Struts 2 applications

User Sends request: User sends a request to the server for some resource.
 
FilterDispatcher determines the appropriate action: The FilterDispatcher looks at the request and then determines the appropriate Action.
 
Interceptors are applied: Interceptors configured for applying the common functionalists such as workflow, validation, file upload etc. are automatically applied to the request.
 
Execution of Action: Then the action method is executed to perform the database related operations like storing or retrieving data from the database.
 
Output rendering: Then the Result renders the output.
 
Return of Request: Then the request returns through the interceptors in the reverse order. The returning request allows us to perform the clean-up or additional processing.
 
Display the result to user: Finally the control is returned to the servlet container, which sends the output to the user browser.

 The Flow of a Struts 2.0 Application
The following are the sequence of steps that will happen when a Html Client makes a request to a Web Application built on top of Struts 2.0

The Client (which is usually a Html Browser) makes a Request to the Web Application.
The Web Server will search for the Configuration Information that is very specific to the Web Application (taken from the web.xml file), and will identity which Boot-strap Component has to be loaded to serve the Client\'s Request.
In Struts 2.0, this Component is going to be a Servlet Filter (whereas in Struts 1.0, the component is an Action Servlet).
The Filter Servlet then finds out the Action Class for this Request that is mapped in the Configuration File. File.
Before passing the Request to the Action class, the Controller passes the Request to a series of Interceptor Stack (explained later).
Then the Request Object is passed on to the corresponding Action Class.
The Action Class then executes the Appropriate Business Logic based on the Request and the Request Parameters.
After the execution of the Business Logic, a Result (\"success\" or \"error\") is returned either in the form of String or in the form of Result Object back to the Controller.
The Controller uses the Return Result to choose which View to be rendered back to the Client Application.

what is the difference b/w JRE & JVM ?

The JRE is the environment within which the virtual machine runs.JRE  JAVA Runtime Environment
JVM  JAVA Virtual Machine
JRE is the container, JVM is the content.
JRE=JVM+ rt.jar
The JRE includes the JVM, which is what actually interprets the byte code and runs the program. To do this the JVM uses libraries and other files provided by the JRE.

What\'re the types of controllers?

There are two types of Controllers in Struts.
   1.Main Controller/FrontController
       Ex: ActionServlet
   2.Application Controller
       Ex:Action Class

What is ASP.Net?

ASP Stands for Active server Pages.ASP used to create interacting web pages.


What is Collections?

Collections is a class, contains methods such as sort(), binarySearch(), copy(), etc.ADD, Remove, Search, retrieve operations can be performed.

What is EJB?

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.

How to described the method Setsheetname?

This method is used to detect the automatically unicode and sets its encoding appropriately. Simply we can use the setSheetName(int sheet, String encoding) method. this has  the facility to set the unicode for setting encoding appropriately.


How to find the record using poi?

In this page of the tutorials we are trying to find records of an excel sheet using POI2.5 API Event. The class RowRecordextends Record implements Comparable. in this program it class is store the row information for the sheet. 


Described the method getFirstCol?

This methods get the first column number for the sheet.


Described the method getLastCol?

This methods get the last col number for the sheet.

How to find the value of the column?

The org.apache.poi.hssf.record.NumberRecord class extends Record and implements CellValueRecord interface,  java.lang.Comparable interface.


How to change the background of the slide?

We creates an object of the shape. In this object of the shape we are assigning rectangle shape and set the size and position. Initial values for x and y axis are 0.The height and width are 400 and 400 respectively. Then create an object of Shape and set values, fill type, background color and  foreground color of the slide. Then finally add into slide. We are using setFillType(Fill.FILL_SHADE) method to set fill type, setBackgroundColor(Color.blue) method to set background color and setForegroundColor(Color.green) method to set the text color.

Described the method addPicture(byte[] pictureData,int format)?

This methods add a picture to the workbook and the return type is int of this method. In This method two parameters are passed into this method. The first parameter is pictureData and second parameter is format .The pictureData is byte form of the picture. In this example we are using Picture.PNG as format.

How to change power point slide size?

setPageSize(java.awt.Dimension pgsize):-

This methods provide the feature of for change the size current page. The page size range passed as parameter in this method. The return type is void. This method is defined as public in SlideShow class.

 

What are the three OOPs principles and define them?

Encapsulation, Inheritance and Polymorphism are the three OOPs Principles.
Encapsulation: Is the Mechanism that binds together code and the 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 a feature that allows one interface to be used for a general class of actions. 

What is the difference between prefix and postfix of -- and operators?

The prefix form returns the increment or decrement operation and returns the value of the increment or decrement operation.The postfix form returns the current value of all of the expression and thenperforms the increment or decrement operation on that value.

What is the �finally� block?

Finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also execute.

What is the difference between String and StringBuffer?

String objects are constants, whereas StringBuffer objects are not.
String class supports constant strings, whereas StringBuffer class supports growable, modifiable strings.

What is the output of the following program? public class AA { public static void main(String args[]) { String s1 = \"abc\"; String s2 = \"def\"; String s3 = s1.concat(s2.toUpperCase( ) ); System.out.println(s1+s2+s3); } }

abcdefabcDEF

What is the purpose of the File class?

The File class is used to create objects that provide access to the files and directories of a local file system.

What is the difference between the File and RandomAccessFile classes?

The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

How many bits are used to represent Unicode, ASCII, UTF-16 and UTF-8 characters?

Unicode requires 16-bits and ASCII requires 8-bits. Although the ASCII character set uses only 1-bits, it is usually represented as 8-bits. UTF-8 represents characters using 8, 16 and 18-bit patterns. UTF-16 uses 16-bit and larger bit patterns

What is the relationship between an event-listener interface and an event-adapter class?

An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface.

What is the difference between a Choice and a List?

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

What is a BeanFactory?

The BeanFactory is provide an advanced configuration mechanism capable of managing beans of any kind of storage facility. 

The ApplicationContext builds on top of the BeanFactory and adds other functionality like integration with Springs AOP features, message resource handling for use in internationalization, event propagation, declarative mechanisms to create the ApplicationContext and optional parent contexts, and application-layer specific contexts such as the WebApplicationContext, among other enhancements.

what is the base class of all classes?

java.lang.Object

what do you think is the logic behind having a single base class for all classes?

1. casting

2. Hierarchical and object oriented structure.

why most of the Thread functionality is specified in Object Class?

Basically for inter tribal communication.


what is the importance of == and equals () method with respect to String object?

== is used to check whether the references are of the same object.

.equals () is used to check whether the contents of the objects are the same.

But with respect to strings, object reference with same content

will refer to the same object.


String str1=Hello;

String str2=Hello;


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


If you take the same example with String-buffer, the results would be different.

String-buffer str1=Hello;

String-buffer str2=Hello;

str1.equals(str2) will be true.

str1==str2 will be false.

Is String a Wrapper Class or not?

No. String is not a Wrapper class

How will you find length of a String object?

Using length () method of String class.

How many objects are in the memory after the exeception of following code segment?

String str1 = \"ABC\";String str2 = \"XYZ\";String str1 = str1 + str2;There are 3 Objects.

what will trim () method of String class do?

The trim () eliminate spaces from both the ends of a string.

what is the possible runtime exception thrown by substring () method?

ArrayIndexOutOfBoundsException

Java 11 Features

1. Running Java File with single command,directly run the file with java command and it implicitly compiles.
2. Added new String Methods 
   e.g. isBlank() ,lines(),strip(), stripLeading(), stripTrailing(),repeat(int)
3.JEP 323, Local-Variable Syntax for Lambda Parameters .

JDK 11 new features-- Local-Variable Syntax for Lambda Parameters

var list = new ArrayList< String >()

 (var s1, var s2) -> s1 + s2

It was in Java 8 but got removed in Java 10. 
Now it’s back in Java 11


The JDK 11 also allow annotations to be added to lambda’s parameters without having to write full variable type name

Function< String, String > append = (@NonNull var string) -> string + " World";

JDK 12 New Features

Oracle will soon roll out Java 12 in March 2019 and new releases