1) Explain java beans and what are its advantages.

It is a software component which can be used on variety of environment
Advantages of beans are:
• Beans are written only once and can be used many times
• Configuration setting of beans can be saved in persistant storage
• We can control the exposure of properties methods and events of beans
• It can send and receive events from another objects
• We can easily configure beans using auxiliary software and it is not included in run time environment
• It may or may not be visible to another user

2) what are the basic differences between an Interface and an Abstract class?

• Only a interface can extend a interface but any class can extend abstract class
• All the variables in interface are set as final by default
• Interface execution is slow as compared to abstract class
• Abstract scope is only upto the derived class and scope of Interface is upto any level
• Abstract class can implement method but interface cannot because a interface contains only the signature of a method but not the body of a method
• In a class we can implement many interfaces but only one abstract class

3) Explain connection pooling in java

• In connection pooling several context instances have been created for the same database.
• As application server starts a pool of connection object has been created
• These objects are managed by pool manager
• Pool manager provides context instance as the request comes and when the context instance is done with connection, it is retured in the pool for future use
• The class is use to provide connections available to calling program in its getConnection method. This method searches for a connection and if not available then a new connection is created.

4) Explain difference between get and post method.

• Visibility - GET request is sent via the URL string which is visible whereas POST request cant be seen as it is encapsulated in the body of the HTTP request
• Length – there is limitation of length for GET request as it goes through URL and its character length cant be more than 255 but in POST request no such limitation.
• Performance –As no time is spend on encapsulation in GET request so it is comparatively faster and relatively simpler. In addition, the maximum length restriction facilitates better optimization of GET implementation.
• Type of Data - GET request can carry only text data as we know URL only contain text data on the other hand post request can carry both text as well as binary
• Caching/Bookmarking – as we know now that GET request is nothing but a URL hence it can be cached as well as bookmarked. No such options are available with a POST request.
• FORM Default - GET is the default method of the HTML FORM element. To submit a FORM using POST method, we need to specify the method attribute and give it the value "POST".
• Data Set - GET requests are restricted to use ASCII characters only whereas no such restrictions are in POST requests

5) What are the ways in which a thread can enter the waiting state?

A thread can enter the waiting state by:
• By sleep() method invocation
• By blocking its input and output
• By invoking an object’s wait() method.
• It can also enter the waiting state by invoking its suspend() method.

6) Explain daemon thread in Java and which method is used to create the daemon thread?

• Deamon thread runs in the back ground doing the garbage collection operation for the java runtime system.
• It has the low priority
• These threads run without the involvement of the user.
• We can use the accessor method isDaemon() to determine if a thread is a daemon thread.
• Daemon threads exist only to serve user threads.
• The setDaemon() method is used to create a daemon thread

7) Define reflection in java

• It allows you to analyze a software component like java beans
• It helps in describing software component capability dynamically, at run time rather than at compile time
• This is provided by java.lang.reflect package which includes several interfaces

8) Explain mutable object.

Mutable objects have the fields which can be changed even after the object is created.

9) What is an Applet with a example?

• It is a small program which is easily transmitted over internet
• Applet can be downloaded whenever a user demand
• It makes some of the functionality to be move from server to client
• It is installed automatically
• It has limited access of resources
• It run as a part of web document
• Lesser risk of viruses
• Applet intract with the user through AWT(abstract window toolkit) not with I/O

10) Which is better from Extending Thread class and implementing Runnable Interface?

• Implementing runnable interface is more advantageous because when you are going for multiple inheritance, then only interface can help.
• If you are already inheriting a different class, then you have to go for Runnable Interface. Otherwise you can extend Thread class.
• Also, if you are implementing interface, it means you have to implement all methods in the interface.
• If we implement runnable interface it will provide better object oriented design
• Implementing also gives consistency
• By using runnable interface we can run the class several times whereas thread have start() method that can be called only once.

11) What is the use of finally keyword in exception handling?

• In a program where exception is handled using try catch block after this finally keyword is used.
• Finally creates a block that will be executed even after a exception is thrown or not
• If no catch statement matches the exception even then finally block will be executed
• It is executed just before the method return

12) Explain generics use in Java?

• Generic means parametrized type
• It makes operation and paramneter to decide the data type of interfaces,classes and methods
• It also add the type safety
• It also streamline the process
• It helps in reusing the code

13) What are recent changes to collection?

Introduction of Generic in Collections Framework :
• With the addition of generic makes all the Collections Framework has been reengineered for it.
• All the collection now become generic
• one the most important feature that has been added due to genetic is type safety

14) How are Cookies managed in java?

• Cookies are managed by package which includes classes and interfaces.
• It is used to create a stateful HTTP session.
• The classes are CookieHandler,CookieManager, and HttpCookie.
• The interfaces are CookiePolicy and CookieStore.
• All but CookieHandler was added by Java SE 6.

15) Name and explain the types of specifier in java.

Types of specifier are:
Private :

• same class member can access the data
• Same package subclass cannot access it
• Same package non subclass is not able to access the private data
• Different package subclass and different package non class can not access it

• same class member can access the data
• Same package subclass cannot access it
• Same package non subclass not able to access the private data
• Different package subclass can access the data but not different package non class
No modifier

• same class member can access the data
• Same package subclass can access it
• Same package non subclass able to access the private data
• Different package subclass and different package non class can not access it

• same class member can access the data
• same package subclass cannot access it
• same package non subclass is able to access the private data
• different package subclass and different package non class can access it

16) What is the use of Adapter class in event handling?

Use of adapter class are:
• It simplifies the creation of event handling
• Interface holds only abstract methods and requires all of them to be implemented to avoid this adapter is used
• It processes and receives some event which is handled by listener interface
• We can create a new class by extending one of the adapter classes to act as a event listener.
• It provides an empty implementation of all methods
• It is used to create an interface having dummy methods

17) Can we compare String using equality operator (==) operator?

We can compare String using equality operator. But we mostly use equals() method because of following reasons:
• The equality operator is used to compare primitives values only where as equals method() should be used to compare objects.
• The equality operator can invoke subtle issue while comparing primitive to Object. Where as equals() method is used to perform character based comparison.
• equals() return true if two String represent to the same object or when both strings contents are exactly same but equality() perator returns true if two String object represents to same object but return false if two different String object contains same contents

18) What is intern() method in Java?

The intern() method is of String class. The intern() method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string object will be added in String pool and the reference of this String is returned.

19) When is class garbage collected?

Java uses the garbage collector to free memory which is occupied by those objects which is no more reference by any of the program. An object becomes eligible for Garbage Collection when no live thread can access it. There are many ways to make a class reachable and thus prevent it from being eligible for Garbage Collection: • Objects of that class are still reachable.
• Class object representing the class is still reachable.
• ClassLoader that loaded the class is still reachable.
• Other classes loaded by the ClassLoader are still reachable.
When all of the above are false, then the ClassLoader together with all classes it loaded are eligible for Garbage Collection.

20) What is the difference between a Choice and a List?

The between Choice and list are following:
• Choice class presents a pop-up menu of choices whereas List is a collection of different visible item.
• Choice is displayed in a compact form, to see the list of available choices we need to scroll down whereas list displays the entire available items.
• Choice allows selecting only one items but List supports the selection of one or more List items.
• Lists typically allow duplicate elements selection. List allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all.

21) What is JCA in java?

Java Cryptography Architecture term from Sun for implementing security functions for the Java platform. It provides a platform and gives architecture and APIs for encryption and decryption. JCA is used by the developer to combine the application with the security measure. A programmer uses the JCA to meet the security measure. It helps in performing the third partly security rules. It uses the hash table, encryption message digest, etc to implement the security.
The Java Persistence API is enabling us to create the persistence layer for desktop and web applications. Java Persistence deals in following:
• Java Persistence API
• Query language
• Java Persistence Criteria API
• Object mapping metadata

22) What is difference between eager and lazy loading?

The difference between eager and loading are:
• Eager loading means to load the data before the requirement whereas lazy loading mean that load the data only when required.
• Eager loading fetch the data in one query whereas lazy loading fetch the data when needed by triggering the sub query.

23) What is JMS in Java?

Java Message Service (JMS) is used for creating the communication interface between two clients by using the message passing services. This helps the application to interact with other components irrespective of components location whether they rely on same system or connect to the main system through LAN or internet.

24) What is shallow cloning and deep cloning?

Shallow copy: in this object is copied without its contained objects. Shallow clone only copies the top level structure of the object not the lower levels. It is an exact bit copy of all the attributes.
Deep copy: In this object is copied along with the objects it refers to. Deep clone copies all the levels of the object from top to the bottom recursively.

25) What is the difference between applications and applets?

The differences between an Applet and an application are as follows:
• Applets can be embedded in HTML pages and downloaded over the Internet whereas Applications have no special support in HTML for embedding or downloading.
• Application starts execution with its main method whereas applet starts execution with its init method.
• Application must be run on local machine whereas applet needs no explicit installation on local machine.
• Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser.
• Application can run with or without graphical user interface whereas applet must run within a graphical user interface.

26) What are Class loaders?

Class loader enables the program to load the class at run time. This is located in the java.lang package.
Using Class Loader we can also load the customize classes which is required for the application execution. The class loaders in Java are organized in a tree. When JVM is started three class loaders are used:
• Bootstrap class loader: the core java libraries. It is written in native code.
• Extensions class loader: loads the code in the extension directories. It is implemented by ExtClassLoader class.
• System class loader: code found on the java.class.path which map to the system class path variables. It is implemented by AppClassLoader class. All user classes by default are load by the system class loader.

27) What is the Comparable interface?

The Comparable interface is used to sort collections and arrays of objects using the collections.sort() and java.utils. The objects of the class implementing the Comparable interface can be ordered. All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:
int i = object1.compareTo(object2)
• If object1 < object2: The value of i returned will be negative.
• If object1 > object2: The value of i returned will be positive.
• If object1 = object2: The value of i returned will be zero.

28) What is Single Threaded Model in Servlets?

Single Thread Model is a marker interface which contains no methods and variable in it.
• When using Single thread model with Servlet, it make sure that that only one thread can be executed at a time. It avoids running of two or more thead simultaneously.
• If we wants to make single threaded we can implement this interface in the following fashion.
public class SingleThreadedTest implements SingleThreadModel
//some code

29) What are the different Authentication Options available in Servets?

Authentication options available in Servlets: There are four different options for authentication in servlet:
1. Basic Authentication: Username and password provided by the client to authenticate the user.
2. Form-based authentication- In this the login form is made by the programmer by using HTML.
3. Digest Authentication- It is similar to basic authentication but in this the passwords are encrypted using Hash formula. This makes digest more secured.
4. Client certificate Authentication- It requires that each client accessing the resource has a certificate that it send to authenticate itself. This requires SSL protocol.

30) What is the disadvantage of garbage collector?

Garbage Collector runs in its own thread which affects the performance of the system. It increases the workload of JVM because it constantly monitor the object which is not referenced.. The two main disadvantages of garbage collector are:
• TIME: to collect all those no referenced object JVM spends a considerable amount of time by scanning the entire heap.
• Mark and sweep: some time it is difficult to implement mark and sweep in the application.
Does java support global variable?
No, java does not support global variable because of the following reasons:
• Globally accessible: global variables are globally accessible.
• Referential transparency:global variable breaks the referential transparency and also a global variable generate problem in the namespace.
• Object oriented: As JAVA is object oriented language so where each variable is declared inside the class. To use this variable, object should be initialized.

31) Explain different layout manager in Java.

There are following types of layouts are used to organize or to arrange objects:
• Border Layout: Have five areas for holding components: north, east, west, south and center.
• Flow Layout: Default layout manager, lays out the components from left to right
• Card Layout: Different components at different times are laid out, Controlled by a combo box.
• Grid Layout: Group of components are laid out I equal size and displays them in certain rows and columns.
• Grid Bag Layout: Flexible layout for placing components within a grid of cells.

32) What is chained exceptions in java?

When in a program the first exception causes another exception that is termed as Chained Exception. Chained exceptions helps in finding the root cause of the exception that occurs during application’s execution. The constructors that support chained exceptions in Throwable classes are:
• Throwable initCause(Throwable)
• Throwable(Throwable)
• Throwable(String, Throwable)
• Throwable getCause()

33) When is the main thread stop in java?

When we execute the java program, it call the main() method because main() method is the first thread in the program. This main() method or thread invokes the other thread which is required for the complete execution of the program. The main thread should be the last thread in the program to end. so to make main() method to be last we make sure when we called to another function by giving execution control to that must return the control back to the main() method.

34) What are the ways to create child threads?

There are two ways to create java threads:
• Implementing the Runnable interface: this overcomes the limitation of inheriting from only one parent class Thread. Using Runnable interface, lays a path to ground work of a class that utilizes threads
• Extending Thread class: It inherits the methods and data members, fields from the class tread. In this process only one class can be inherited from the parent class Thread.
The advantage is a class can extend Thread class and also implements the Runnable interface, if required. The Runnable interface is set for implementing a thread and the class that implements the interface performs all the work.

35) Why bytecode is important to Java?

The compiled Java source code is known as byte code. We need bytecode due to following reasons:
• Is independent of the input language.
• Plays an important role in the execution speed of the application.
• Can run on any platform irrespective of system architecture.
• Can be used for internet applications where security is important
• Enable us to load classes which are required for the execution of the application.
• allows the web applications to run on various platforms, on various browsers on different infrastructures.

36) What is an Iterator and explain traversing through a collector using Iterator?

We can access each element in the Collection by using Iterators irrespective of how they are organized in the collector. Iterator can be implemented a different way for every Collection. To use an iterator to traverse through the contents of a collection we do:
• Obtain an iterator by calling the collections iterator() method to the start of the collection.
• Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext()returns true.
• Within the loop, obtain each element by calling next().
• remove() method is used to remove the current element in the iteration.

37) What is Race condition?

Race Condition: it is the situation when two threads raise the request for the same resource allocation, but the manner in which resources are allocated are significant, is called race conditions.
• Race condition is created in program in order to run the parallel execution of program by using multiple threads in a same period.
• A race condition occurs when two threads operate on same object without proper synchronization and there operation interleaves on each other.
• The risk of Race condition is higher in Java.

38) What is difference between Java and JavaScript?

The difference between java and java scripts are:
• Java is an Object Oriented Programming Language and capable of running on multiple operating systems with the help of interpreter whereas Java Script is the object oriented scripting language and it is embedded in HTML and runs directly on the browser.
• JVM is used to executed java program on different program whereas Java Script code is not compiled they are directly run on the browser.
• Java language is used to develop the software whereas java script is used providing interactivity to the simple HTML pages.

39) What is the difference between factory and abstract factory pattern?

The differences between factory and abstract factory are following:
• Factory pattern is a single method but abstract factory is an object.
• The Abstract Factory pattern is one level of abstraction higher than the factory pattern.
• Factory pattern generally returns the common parent class or method whereas the abstract factory pattern returns the one of the several factories.

40) What is Singleton?

Singleton in Java is a class with just one instance in whole Java application.
• This make sure that only one instance of a class is created.
• getInstance() method is used to get single instance of the class.
• It creates a global point to access all object.

41) What is the difference between JAR and WAR files?

The differences between JAR and WAR files are:
• JAR files (Java Archive) allows combining many files into one whereas WAR files (Web Application Archive) stores XML, java classes, and JavaServer pages for Web Application purposes.
• JAR is used to hold Java classes in a library whereas in WAR files are stored in lib directory of the application.
• In this EJB module which contains enterprise java beans class files and EJB deployment descriptor are packed as JAR files with .jar extension whereas in WAR web modules which contains Servlet class files, JSP Files, GIF and HTML files are packaged as JAR file with .war extension.

Senior Level Java Interview Questions
Explain the usage of serialization.

Objects are serialized when need to be sent over network.
They are serialized when the state of an object is to be saved.

How are Observer and Observable used?

The observable class represents an observable object.
The object to be observed can be represented by sub-classing observable class.
When there is a change in an observable instance, an application calling the Observable's notifyObservers method causes all of its observers to be notified of the change by a call to their update method.

Difference between Swing and Awt.

AWT are heavy-weight components. Swings are light-weight components. Thus, swing works faster than AWT.

Define inner class in Java

Class that is nested within a class is called as inner class. The inner class can access private members of the outer class. It is mainly used to implement data structure and some time called as a helper class.

Differences between constructors and methods.

A constructor is used to create objects of a class. A method is an ordinary member in a class.
Constructor does not have a return type. A method should have a return type.
Constructor name is the name of the class. A method name should not be the name of the class.
Constructor is invoked at the time of creation of the class. Method needs to be invoked in another method by using the dot operator.
Constructor can not have ‘return’ statement. All methods that return non-void return type should have ‘return’ statement.

Define Method overriding. Explain its uses.

Method overriding is the process of writing functionality for methods with same signature and return type, both in super class and subclass The uses of method overriding: Time to invest method signature is reduced

Different functionality in both super class and sub class by sharing same signature

The functionality can be enhanced
The behavior can be replaced in the sub class

What is the purpose of the File class?

The File class provides access to the files and directories of a local file system.

Can you explain Native methods in Java?

• The Java native method is used to merge the power of C or C++ programming into Java.
• To enhance to high performance language, when efficient native Java compilers are not fully implemented, use of native method boosts the performance to at least the speed of C compiled code.
Java applications can call code written in C, C++, or assembler. This is sometimes done for performance and sometimes to access the underlying host operating system or GUI API using the JNI.

Explain class loaders in Java with an example.

• The class loader describes the behavior of converting a named class into the bits responsible for implementing that class.
• Class loaders eradicate the JREs need to know anything about files and file systems when running Java programs.
• A class loader creates a flat name space of class bodies that are referenced by a string name and are written as:
Class r = loadClass(String className, boolean resolveIt);

What is Reflection API in Java?

• The Reflection API allows Java code to examine classes and objects at run time.
• The new reflection classes allow you to call another class's methods dynamically at run time.
• With the reflection classes, you can also examine an instance's fields and change the fields' contents.
• It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.
• The Reflection API consists of the java.lang.Class class and the java.lang.reflect classes: Field, Method, Constructor, Array, and Modifier.
Static class loading vs. dynamic class loading.
• The static class loading is done through the new operator.
• Dynamic class loading is achieved through Run time type identification. Also called as reflection
This is done with the help of the following methods:
getClass(); getName(); getDeclaredFields();
Instance can also be created using forName() method. It loads the class into the current class memory.

Can you explain shallow cloning and deep cloning?

Cloning of objects can be very useful if you use the prototype pattern or if you want to store an internal copy of an object inside an aggregation class for example.
• Deep cloning - You clone the object and their constituent parts.
• It should be used when it is inappropriate to separate the parts; the object is formed of, from it.
• Shallow cloning - You clone only the object, not their parts. You add references to their parts.
• It should be used when it is adequate to have the references added to the cloned object

Explain the purpose of Comparator Interface.

• Comparators can be used to control the order of certain data structures and collection of objects too.
• The interface can be found in java.util.Comparator
• A Comparator must define a compare function which takes two Objects and returns a -1, 0, or 1
• Sorting can be done implicitly by using data structures of by implementing sort methods explicitly.

What is the impact of private constructor?

• Private Constructors can't be access from any derived classes neither from another class.
• So you have to provide a public function that calls the private constructor if the object has not been initialized, or you have to return an instance to the object, if it was initialized.
This can be useful for objects that can't be instantiated.

Can you explain static Initializers in Java?

A static initializer block resembles a method with no name, no arguments, and no return type. There is no need to refer to it from outside the class definition.
The code in a static initializer block is executed by the virtual machine when the class is loaded.
Because it is executed automatically when the class is loaded, parameters don't make any sense, so a static initializer block doesn't have an argument list.

Define Externalizable Interface and explain its purpose.

• The Externizable interface extends the serializable interface.
• When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject()two methods to control more complex object serailization process.
• When you use Externalizable interface, you have a complete control over your class's serialization process. The two methods to be implemented are : void readExternal(ObjectInput)
• The object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays.
void writeExternal(ObjectOutput) • The object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays.