Java Interview Questions and Answers - Test & Download!

Explain how to force the garbage collection in Java.

- First of all Garbage collection is an automatic process and can't be forced. Although, you can request it by calling System.gc().
- JVM does not guarantee that GC will be started immediately.
- Every class inherits finalize() method from java.lang.Object.
- The finalize() method is called by garbage collector when it determines no more references to the object exists.
- You can sent request to recycle the unused objects by calling System.gc() and Runtime.gc() , but there is no guarantee when all the objects will garbage collected.

Advantages and disadvantages of Java Sockets.

Advantages of Java Sockets :

- Sockets are flexible and easy to implemented for general communications.
- Sockets cause low network traffic unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request.

Disadvantages of Java Sockets :

- Socket based communications allows only to send packets of raw data between applications.
- Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

What do you understand by Synchronization? why is it important?

- Synchronization is a process of controlling the access of shared resources by the multiple threads.

- It allows only one thread can access one resource at a time.

- It ensures one thread not to modify a shared object while another thread is in the process of using or updating the object's value.

- This often leads to significant errors. Synchronization prevents such type of data corruption.

Synchronizing a function :
public synchronized void SyncMet()
{
// Appropriate method-related code.
}

Constructors and normal methods.

- Constructors must have the same name as the class.
- Constructors can not return a value.
- Normal methods are only called once while regular methods can be called many times
- Normal methods can return a value or can be void.

What is an immutable class? How to create an immutable class?

- Immutable class is a class which once created, it’s contents can not be changed.
- Immutable objects are the objects whose state can not be changed once constructed.
- Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe.
- Immutable objects are automatically thread-safe since the state of the immutable objects can not be changed once they are created
- All wrapper classes in java.lang are immutable, i.e. String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger

Difference between ArrayList and vector.

- ArrayList is not thread-safe whereas Vector is thread-safe.
- In Vector class each method is surrounded with a synchronized block and thus making Vector class thread-safe.
- Both the ArrayList and Vector hold onto their contents using an Array.
- When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room.
- A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

What is the difference between Java and C++?

- Java is compatible with C++ but the backward compatibility is not being given in the case of C++.
- Java format is influenced by C++ only and it is strongly typed language but C++ is loosely typed language.
- C++ provides write once and compile anywhere concept, but Java provides write once run anywhere concept.
- C++ allows procedural, functional, object oriented and template programming, whereas java provides only object oriented paradigm.
- C++ calls directly to the system libraries for program, but java has to call through an interface to access the java libraries.
- C++ supports pointer, but there is no concept of pointers in Java language.

What is a java object and java application?

- Java object is an object that is provided by the execution of an application. When an application is compiled an object of that application is being made. Java application on the other hand is a program that is being written in Java and being read by the Java virtual machine.

What is the difference between multitasking and multithreading?

Multitasking includes two ways for representation :

1. Preemptive multitasking: where the system terminates the idle process without asking the user. For example: Unix/Linux, Windows NT
2. Non-preemptive multitasking: where the system ask the process to give the control to other process for execution. For example: Windows 3.1 and Mac OS 9.

Multithreading :

1. Multithreaded programs are the program that extend the functionality of the multitasking by dividing the program in thread and then execute the task as individual threads.
2. Threads run in a different area and each thread utilizes some amount of CPU and memory for execution.

What is the difference between multiple processes and multiple threads?

- Multiple processes are the way to provide multitasking environment to the user to allow him to switch over to different programs quickly. In these processes, it consists of complete set of its own variables and data. Multiple threads share the same variable and same data. Multiple processes are safe to use but multiple threads are riskier in the sense that they share the same data.

- Multiple processes have much more overhead but multiple threads have less overhead and individual threads can be stand alone if other threads are destroyed.

- In multiple processes inter communication is slower and more restrictive, whereas communication between threads are faster.
1 2 3 4 5 6

Difference between Java and JavaScript
Java - difference between Java and JavaScript - Java is an Object Oriented Programming Language which is developed by Sun Microsystems. It is capable of running on multiple operating systems with the help of.....
How to obtain a performance profile of Java program
Java - performance profile in Java - To improve the performance of a program, performance analysis is used. The usual purpose of this analysis is to determine which sections of a program to optimize......
Why doesn't Java run on all platforms?
Java runs mostly on all platforms. For running a Java program we need JVM on all the platforms. If JVM is not installed on any platform than we are not able to run ...
Post your comment
Discussion Board
java programming papers pune university
Nice
kajal jadhav 04-18-2015
java interview Questions
Here's some more java questions:

1) Junior java developer
a) Basic ocjp (former scjp) questions:
– What does static, final mean, purposes;
– How many accesibility modifiers exist? Please describe them.
– Why do you need a main method?
– How many constructors can you have?
– Define overwriting and overloading
– Give java API implementations for overwriting and overloading
– Describe the String class – unique properties
– StringBuilder vs StringBuffer
– Collections : please describe, give some examples and compare them to eachother
– ArrayList vs Vector
– HashMap vs HashTable
– What’s a tree
– What’s a map
– Multithreading: describe the management in java
– What’s a semaphone?
– How many states are there for threads?
– Describe the usage for synchronized word (2)
– Serialization in java – a descrition and usage
– Garbage collection in java – description and usage
– Can you guarantee the garbage collection process?
b) Simple design pattern questions:
– Singleton please describe main features and coding
– Factory please describe main features and coding
– Have you used others? please describe them

2) Intermediate and Senior level – depending on rate of good responses, additional questions to 1):

http://centraladvisor.com/programming-2/java/java-developer-interview
Bogdan 08-1-2012
Java interview questions and answers
Explain the importance of DriverManager.

The basic service to manage set of JDBC drivers.


What are the methods in Object?

clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString

Define a nested class.

If all the methods of a inner class is static then it is a nested class.

What is garbage collection?

Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process


Difference between LinkedList and ArrayList.

LinkedList are meant for sequential accessing.

ArrayList are meant for random accessing.


Define a package.

Packages provides wide namespace ability and allows to group set of classes into a single unit.
Raj 12-5-2011
Java interview questions and answers
Explain the significance of ListIterator.

Using ListIterator you can iterate back and forth.



Can you explain inner class.

If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.

Can you explain the meaning of aggregation and composition

Aggregation - It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its

reference, then it is called aggregation.

Composition - Holding the reference of the other class within some other class is known as composition.

Is it possible to instantiate the Math class?

You can’t instantiate the math class.
Pankaj 12-5-2011
Java interview questions and answers
Define Locale.

A Locale object represents a specific geographical, political, or cultural region.

How will you load a specific locale?

By using ResourceBundle.getBundle(…);

Is JVM a compiler or an interpreter?

Interpreter





Can you explain the usages of Class.forName()?

It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( “class-instance”.newInstance() ).

Inq adds a question: Expain the reason for each keyword of

public static void main(String args[])

Akash 12-5-2011
Java interview questions and answers
Define reflection.

Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes.


Can you tell me range of byte?

128 to 127


How to invoke external process in Java.

Runtime.getRuntime().exec(….)




What is the best way to findout the time/memory consuming process?

By using profiler
Rakesh 12-5-2011
Java interview questions and answers
What is skeleton and stub? Explain their purposes.

Stub is a client side representation of the server, which takes care of communicating with the remote server.



What kind of thread is the Garbage collector thread?

Daemon thread




Explain the purpose of Void class.

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.
Nitin 12-5-2011
Java interview questions and answers
Explain the importance of finalize method.

Finalize method cleans up some resources before it get garbage collected.

Define mutable object and immutable object.

The value of Mutable object is changeable.
Ex., StringBuffer

The value of an immutable object can't be changed

Ex., String, Integer, Float

What are the base class for Error and Exception?

Throwable
Dharam 12-5-2011
Java interview questions and answers
Difference between string and stringbuffer object.

String is an immutable object.

StringBuffer is a mutable object.


Define daemon thread.

Daemon thread are the threads which can run without user intervention.
The JVM can exit when there are daemon thread by killing them abruptly.


Define a DatabaseMetaData.

It represents comprehensive information about the database as a whole.
Jitu 12-5-2011
Java interview
Explain preemptive scheduling and time slicing.

In preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence.


In time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks.


Explain the different scopes for Java variables.

3 scopes of Java variables are defined below:


Instance

Initialized to default values at the time of creation of object, and remain accessible as long as the object accessible.

Local

Defined within a method and remain accessbile only during the course of method excecution and fall out of scope When the method finishes

execution.

Static

Static variables are the class level variables.
Static variables are initialized when the class is loaded in JVM for the first time and remain there as long as the class remains loaded.
Static variables are not tied to any particular object instance.
Akash 11-23-2011
Java interview questions and answers
Explain the purpose of finalization.

It provides an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

Explain the importance of daemon thread.

Daemon thread is a low priority thread.
It runs intermittently in the back ground doing the garbage collection operation for the java runtime system.

A daemon thread is created using setDaemon method.


Synchronized methods and synchronized statements.

Synchronized methods

Methods that are used to control access to an object.
A thread only executes a synchronized method after it has acquired the lock for the method's object or class.

Synchronized statements

They are similar to synchronized methods.
A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
Nitin 11-23-2011
Java interview questions and answers
What are the way of using thread?

Can be implemented by using runnable interface
By inheriting from the Thread class.

Difference between a constructor and a method.

Constructor

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.
It has no return type, and is invoked using the new operator.

Method

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


Explain how to serialize an object to a file.

The class whose instances are to be serialized should implement an interface Serializable, pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
Naveen 11-23-2011
Java questions and answers
Access Specifiers in Java.

Public- public classes, methods, and fields can be accessed from everywhere.

Protected-

Protected methods and fields can only be accessed within the same class, within its subclasses, and within classes of the same package.

Default(no specifier)

Such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.

Private

Private methods and fields can only be accessed within the same class.
Private methods and fields are not visible within subclasses
They are not inherited by subclasses.



Explain static methods.

Static methods are declared with the keyword static as modifier.
They are called Static because they affect a class as a whole, not a particular instance of the class.
They are always invoked without reference to a particular instance of a class.

Restrictions of using static methods:

It can only call other static methods.
It must only access static data.
It cannot reference to the current object using keywords super or this.
Priya 11-23-2011
Java interview questions
Can you tell me the main Implementations of the Set interface?

HashSet
TreeSet
LinkedHashSet
EnumSet


Explain the importance of HashSet.

It is an unsorted, unordered Set.
It uses the hashcode of the object being inserted.
You can use it when you want a collection with no duplicates and you don’t care about order when you iterate through it.

Explain the importance of TreeSet.

It is a set implementation keeping the elements in sorted order.
The elements are sorted according to the natural order of elements or by the comparator provided at creation time.
Tina 11-23-2011
Java interview questions and answers
Define native method.

A native method is implemented in a language other than Java.

Explain explicit casting.

In Explicit casting, the complier are specifically informed about transforming the object.

Example

long a = 890.20;

int b = (int) a; //Explicit casting


Explain implicit casting.

Assigning one entity to another without any transformation guidance to the compiler is implicit casting.
This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.

Example

int a = 6000;

long b = a; //Implicit casting


Explain reflection API

Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time.
This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc.

Example: Using Java Reflection API we can get the class name, by using the getName method.
Rajeev 11-22-2011
Java interview questions and answers
Explain the importance of Java Virtual Machine (JVM).

It converts .java file into .class file by using Compiler and Interpreter reads byte codes.

Explain the different types of access modifiers in Java.

They determine the type of access to the member of a class.

Types:

-Public : accessible to all classes
-Protected : accessible to the classes within the same package and any subclasses.
-Private : accessible only to the class to which they belong
-Default : accessible to the class to which they belong and to subclasses within the same package


Why there are no global variables in Java?

Global variables are globally accessible and hence can create collisions in namespace.


What is the Java API?

It a large collection of software components that provide capabilities, such as graphical user interface (GUI) widgets.
Rajeev 11-22-2011
Java interview questions and answers
Explain StringTokenizer.

It is utility class that are used to break up string.

Example:

StringTokenizer str = new StringTokenizer(“Welcome”);

while (str.hasMoreTokens()) {

System.out.println(st.nextToken());

}
Nadeem 11-22-2011
Java interview questions and answers
Difference between the boolean & operator and the && operator.

When boolean & operator is evaluated, both operands are evaluated
&& operator is a short cut operator.

When && operator is evaluated, the first operand is evaluated.
When first operand returns a value of true then the second operand is evaluated.
When first operand evaluates to false, the evaluation of the second operand is skipped.
Nadeem 11-22-2011
Java interview questions
Does Java support pointers?

Java doesn't support the usage of pointers. Improper handling of pointers leads to memory leaks which is why pointer concept hasn't found place in Java.

Swing and Awt

AWT are heavy-weight componenets.
Swings are light-weight components and this is reason why swing works faster than AWT.


Pass by reference and passby value

Pass By Reference is the passing the address itself rather than passing the value.
Passby Value is passing a copy of the value to be passed.
Rakesh S 11-4-2011
Java interview questions
Abstract class

It must be extended or subclassed.
It acts as a template.
It may contain static data.
A class may be declared abstract even if it has no abstract methodsand this prevents it from being instantiated.
Annie 11-4-2011