37 Java Interview Questions and Answers for Freshers

Dear Readers, Welcome to Java Interview questions with answers and explanation. These 37 solved Java questions will help you prepare for technical interviews and online selection tests conducted during campus placement for freshers.

After reading these tricky Java questions, you can easily attempt the objective type and multiple choice type questions on Java.

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 :

1. Beans are written only once and can be used many times.

2. Configuration setting of beans can be saved in persistant storage.

3. We can control the exposure of properties methods and events of beans.

4. It can send and receive events from another objects.

5. We can easily configure beans using auxiliary software and it is not included in run time environment.

6. It may or may not be visible to another user.

In Java, 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.

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

Explain difference between get and post method.

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

2. Length : There is limitation of length for GET request as it goes through URL and its character length cannot be more than 255 but in POST request no such limitation.

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

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

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

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

7. Data Set : GET requests are restricted to use ASCII characters only whereas no such restrictions are in POST requests.

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

- A thread can enter the waiting state by:

1. By sleep() method invocation
2. By blocking its input and output
3. By invoking an object’s wait() method.
4. It can also enter the waiting state by invoking its suspend() method.

Give a brief description of RMI.

- RMI(Remote Method Innovation) allows a java object to be executed on another machine.

- It helps in building distributed applications
- RMI uses object serialization to marshal and unmarshal objects
- RMI mechanism is basically a object oriented RPC mechanism
- To deal with client communication Code skeleton is used at skeleton end
- Small example of RMI which returns the various information about European (EU)countries.
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface EUStats extends Remote
{
   String getMainLanguages(String CountryName)
   throws RemoteException;
   int getPopulation(String CountryName)
   throws RemoteException;
   String getCapitalName(String CountryName)
   throws RemoteException;
}

What do you understand by JSP actions?

- JSP actions are XML tags that forces the server to directly use the server to the existing components or control the behavior of the JSP engine.

- JSP actions are executed when a JSP page is requested.

- Actions are inserted in the jsp page using XML syntax to control the behavior of the servlet engine.

- By using JSP actions, we can reuse bean components, dynamically insert a file and switch the user to another page.

- Some of the available actions are as follows:

1. <jsp: include> – include a file at the time the page is requested.
2. <jsp: useBean> – find or instantiate a JavaBean.
3. <jsp: setProperty> – set the property of a JavaBean.
4. <jsp: getProperty> – insert the property of a JavaBean into the output.
5. <jsp: forward> – forward the requester to a new page.
6. <jsp: plugin> – generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin.

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.

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.

Various classes in this package and their functions are:

1. AccessibleObject : Allows you to bypass the default access control checks.

2.Array : Allows you to dynamically create and manipulate arrays.

3. Constructor : Provides information about a constructor.

4. Field : Provides information about a field.

5. Method : Provides information about a method.

6. Modifier : Provides information about class and member access modifiers.

7. Proxy : Supports dynamic proxy classes.

8. ReflectPermission : Allows reflection of private or protected members of a class.

Explain mutable and immutable objects with example.

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

- Instance variables are set as public.

- Example :
class Mutable
{
   private int value;
   public Mutable(int value)
   {
       this.value = value;
   }
getter and setter for value
}
- Immutable objects have no fields to be changed. All the instance variables are private.

- Example :
public class ImmutableClass
{
   private final int value;
   public MutableClass(final int aValue)
   {
       //The value is set. Now, and forever.
       value = aValue;
   }
   public final getValue()
   {
       return value;
   }
}

What is an Applet with a example?

- It is a small program which is easily transmitted over the 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

- Small example to draw a string using applet :
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet
{
   public void paint(Graphics g)
   {
       g.drawString("A Simple Applet", 20, 20);
   }
}

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.

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.

- Example :
class FinallyDemo
{
   // Through an exception out of the method.
   static void procA()
   {
   try
   {
       System.out.println("inside procA");
       throw new RuntimeException("demo");
   }
   finally
   {
       System.out.println("procA's finally");
   }
}

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

- Example of generics :
class Gen
{
   T ob; // declare an object of type T
   // Pass the constructor a reference to
   // an object of type T.
   Gen(T o)
   {
       ob = o;
   }
   // Return ob.
   T getob()
   {
       return ob;
   }
   // Show type of T.
   void showType()
   {
       System.out.println("Type of T is " +
       ob.getClass().getName());
   }
}

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 of the most important feature that has been added due to genetic is type safety.

Autoboxing facilitates the use of primitive types :

- It helps in storing of primitive types in collections.

The For-Each Style for Loop :

- Now collection can be cycled through by use of the for-eachstyle for loop.
- Although iterators are still needed for some uses, in many cases, iterator-based loops can be replaced by for loops.

What is the the use of Inet class in networking?

- The InetAddress class binds both the numerical IP address and the domain.

- Name for that address.

- We can interact with Inet class by using the name of an IP host rather than its IP address.

- InetAddress can used in both IPv4 and IPv6 addresses.

- The InetAddress class has no visible constructors.

- Factory methods are used to create an InetAddress object.

- Commonly used InetAddress factory methods are following:

1. static InetAddress getLocalHost( )
2. throws UnknownHostException
3. static InetAddress getByName(String hostName)
4. throws UnknownHostException
5. static InetAddress[ ] getAllByName(String hostName)
6. throws UnknownHostException

How are Cookies managed in java?

- Cookies are managed by java.net 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.

What are different ways for character extraction in String class?

- Number of ways of character extraction in string class are:

1. charAt( ) :

- It is used to extract a single character from a String.

- Its general form is : char charAt(int index)

- Here, index of the character to be extracted should be non negative and should be with the character getChars( ).

- To extract more than one character at a time, getChars( ) method is use.

- It has this general form : void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

- Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd

- Specifies an index that is one past the end of the desired substring.

2. getBytes() :

- It extracts more than one character and stores in array but in byte form by default..

- Here is its simplest form : byte[ ] getBytes( ).

3. toCharArray( ) :

- To convert all the characters in a String object into a character array, the easiest way is to call toCharArray( ).

- It returns an array of characters for the entire string.

- It has this general form : char[ ] toCharArray( )

Name and explain the types of specifier in java.

Types of specifier are :

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

2. Protected :

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

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

4. Public :

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

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.

What is an abstract method?

An abstract method is a method which doesn’t have a body, just declared with modifier abstract.

Explain the use of the finally block.

Finally block is a block which always executes. The block executes even when an exception is occurred. The block won't execute only when the user calls System.exit().

What is the initial state of a thread?

It is in a ready state.

What is time slicing?

In time slicing, the task continues its execution for a predefined period of time and reenters the pool of ready tasks.

What are Wrapper Classes?

Wrapper Classes allow to access primitives as objects.

What is List interface?

List is an ordered collection of objects.

Can you explain transient variables in java?

They are the variables that cannot be serialized.

What is synchronization?

Synchronization ensures only one thread to access a shared resource, thus controls the access of multiple threads to shared resources.

What is serialization?

Serialization helps to convert the state of an object into a byte stream.

What is HashMap and Map?

Map is Interface and Hashmap is class that implements that.

What is StringBuffer class?

StringBuffer class is same as String class with the exception that it is mutable. It allows change and doesn’t create a new instance on change of value.

How can you force garbage collection?

It is not possible to force GC. We can just request it by calling System.gc().

Is it possible an exception to be rethrown?

Yes, an exception can be rethrown.

What is the return type of a program’s main() method?

A program’s main() method has a void return type.

Which package is always imported by default?

The java.lang package is always imported by default.

What is a Class?

A class implements the behavior of member objects by describing all the attributes of objects and the methods.

What is an Object?

An object is the members of a class. It is the basic unit of a system. It has attributes, behavior and identity.

Explain the use of "instanceOf" keyword.

"instanceOf" keyword is used to check the type of object.

How do you refer to a current instance of object?

You can refer the current instance of object using "this" keyword.

What is the use of JAVAP tool?

JAVAP is used to disassemble compiled Java files. This option is useful when original source code is not available.

In which package is the applet class located?

Applet classes are located in "java.applet" package.

Java array vs. ArrayList class.

ArrayList is a dynamic array that can grow depending on demand whereas Java arrays are fixed length.

Explain Enumeration Interface.

It defines the methods using which we can enumerate the elements in a collection of objects.

What are access modifiers?

Access modifiers determine if a method or a data variable can be accessed by another method in another class.

Explain the impact of private constructor.

Private constructor prevents a class from being explicitly instantiated by callers.

What is an exception?

An exception is an abnormal condition that arises in a code sequence at run time.

What are ways to create threads?

There are two ways to create a thread:

1. extend the java.lang.Thread class.
2. implement the java.lang.Runnable interface.

How can we stop a thread programmatically?

thread.stop;

What are daemon threads?

Daemon threads are designed to run in background. An example of such thread is a garbage collector thread.

What are the different types of locks in JDBC?

There are four types of major locks in JDBC:

1. Exclusive locks
2. Shared locks
3. Read locks
4. Update locks

What are Servlets?

Servlets are program that run under web server environments.

What are the different ways to maintain state between requests?

There are four different ways:

1. URL rewriting
2. Cookies
3. Hidden fields
4. Sessions

What are wrapper classes?

In Java we have classes for each primitive data types. These classes are called as wrapper class. For example, Integer, Character, Double etc.

What are checked exceptions?

There are exceptions that are forced to catch by Java compiler, e.g IOException. Those exceptions are called checked exceptions.

What is the Locale class?

Locale class is a class that converts the program output to a particular geographic, political, or cultural region.

Is main a keyword in Java?

No, main is not a keyword in Java.

What is the most important feature of Java?

Platform independency makes Java a premium language.

What is a JVM?

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

Does Java support multiple inheritances?

No, Java doesn't support multiple inheritances.

What is the base class of all classes?

java.lang.Object

Can a class be declared as protected?

A class can't be declared as protected. Only methods can be declared as protected.

Can an abstract class be declared final?

No, since it is obvious that an abstract class without being inherited is of no use.

Can we declare a variable as abstract?

Variables can't be declared as abstract. Only classes and methods can be declared as abstract.

Define Marker Interface.

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

What is an abstract method?

An abstract method is a method whose implementation is deferred to a subclass.

When can an object reference be cast to an interface reference?

An object reference is cast to an interface reference when the object implements the referenced interface.

Which class is extended by all other classes?

The object class is extended by all other classes.

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

void.

What are the eight primitive java types?

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

Difference between a public and a non-public class.

A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package.

Which Java operator is right associative?

The = operator is right associative.

What is a transient variable?

Transient variable is a variable that may not be serialized.
25 Basic Java Interview Questions and Answers
Basic Java interview questions - What is reflection?What is JVM?Explain different layout manager in Java.What is the difference between Stream classes and Reader writer classes?......
34 Advanced Java Interview Questions - Senior Level Java Interview
Advanced java interview questions - Can we compare String using equality operator (==) operator?What is intern() method in Java?When is class garbage collected?What is the difference between a Choice and a List?.......
Interface vs. an abstract class
Interface vs. an abstract class - An abstract class may contain code in method bodies whereas code is not allowed in an interface......
Post your comment
Discussion Board
Saying thanks
Class Thanks{
public static void main(String[] args){
String str=" Lots of thanks boss, Very Helpful to all freshers and so effective answers, Thanq so muchhhhhlh";
System.out.println(str);
}
}
jyothynaveen 02-27-2015
thanks
very helpful to a fresher thank you sir.
ashwiniperishetty 11-23-2014
Thank you sir,
This questions are very helpful to me.
Poornima 11-9-2014
java
Most valuable information for student for interview.
Thank you very much sir.
monika yadav 11-16-2013
advice
nice questions!!! but for tests plz provide ans also so that we can abt to know our level..
abc 09-19-2013
JAVA
NOTABLY GOOD!
manjuanth 08-23-2013
java
Thanks for your valuable information in your blog,,,,,,i hope this data is very helpful to the students who are willing to attend interviews''''''''''''''''''
SIVAKUMAR 12-15-2012
Excellent
It is so useful for me...... I think this is the best web site for Java

Keep if up...
Krishna Mohan 11-29-2012