A list of top frequently asked JAVA interview questions and answers are given below.
James Gosling initiated Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called ‘Oak’ after an oak tree that stood outside Gosling's office, also went by the name ‘Green’ and ended up later being renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and open-source, aside from a small portion of code to which Sun did not hold the copyright.
Java is a programming language that produces software for multiple platforms. When a programmer writes a Java application, the compiled code (known as bytecode) runs on most operating systems (OS), including Windows, Linux and Mac OS. Java derives much of its syntax from the C and C++ programming languages.
Java produces applets (browser-run programs), which facilitate graphical user interface (GUI) and object interaction by Internet users. Prior to Java applets, Web pages were typically static and non-interactive. Java applets have diminished in popularity with the release of competing products, such as Adobe Flash and Microsoft Silverlight.
Java applets run in a Web browser with Java Virtual Machine (JVM), which translates Java bytecode into native processor instructions and allows indirect OS or platform program execution. JVM provides the majority of components needed to run bytecode, which is usually smaller than executable programs written through other programming languages. Bytecode cannot run if a system lacks required JVM.
There are some java features include Object Oriented
Some features include Object Oriented, Platform Independent, Robust, Interpreted, Multi-threaded
An integrated development environment (IDE) is a software suite that consolidates basic tools required to write and test software.
Developers use numerous tools throughout software code creation, building and testing. Development tools often include text editors, code libraries, compilers and test platforms. Without an IDE, a developer must select, deploy, integrate and manage all of these tools separately. An IDE brings many of those development-related tools together as a single framework, application or service. The integrated toolset is designed to simplify software development and can identify and minimize coding mistakes and typos.
An IDE can improve the productivity of software developers thanks to fast setup and standardization across tools.
ithout an IDE, developers spend time deciding what tools to use for various tasks, configuring the tools and learning how to use them. Many or even all of the necessary dev-test tools are included in one integrated development environment.
IDEs are also designed with all their tools under one user interface. An IDE can standardize the development process by organizing the necessary features for software development in the UI.
Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and it will be destroyed when the method has completed.
Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded.
A class is a blue print from which individual objects are created. A class can contain fields and methods to describe the behavior of an object.
It is part of the analysis of a program and describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance.
It is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. Therefore encapsulation is also referred to as data hiding.
The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this Encapsulation gives maintainability, flexibility and extensibility to our code.
These are variables declared with in a class, outside any method, with the static keyword.
Singleton class control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes.
Java Runtime Environment is an implementation of the Java Virtual Machine which executes Java programs. It provides the minimum requirements for executing a Java application;
Platform independent practically means “write once run anywhere”. Java is called so because of its byte codes which can run on any system irrespective of its underlying operating system.
Java is not 100% Object-oriented because it makes use of eight primitive datatypes such as boolean, byte, char, int, float, double, long, short which are not objects.
Wrapper classes converts the java primitives into the reference types (objects). Every primitive data type has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class. Refer to the below image which displays different primitive type, wrapper class and constructor argument.
Primitive | Wrapper Classes | Constructor Argument |
---|---|---|
Boolean | Boolean | Boolean or String |
byte | Byte | byte or String |
char | Character | char |
int | Integer | int or String |
float | Float | float, double or String |
double | Double | double or string |
long | Long | long or String |
In Java, constructor refers to a block of code which is used to initialize an object. It must have the same name as that of the class. Also, it has no return type and it is automatically called when an object is created.
There are two type of constructor:
String class is designed with the Flyweight design pattern in mind. Flyweight is all about re-usability without having to create too many objects in memory.
A pool of Strings is maintained by the String class. When the intern( ) method is invoked, equals(..) method is invoked to determine if the String already exist in the pool. If it does then the String from the pool is returned instead of creating a new object. If not already in the string pool, a new String object is added to the pool and a reference to this object is returned. For any two given strings s1 & s2, s1.intern( ) == s2.intern( ) only if s1.equals(s2) is true.
Two String objects are created by the code shown below. Hence s1 == s2 returns false.
//Two new objects are created. Not interned and not recommended.String s1 = new String("A");String s2 = new String("A");
s1.intern() == s2.intern() returns true, but you have to remember to make sure that you actually do intern() all of the strings that you’re going to compare. It’s easy to forget to intern() all strings and then you can get confusingly incorrect results. Also, why unnecessarily create more objects?
Instead use string literals as shown below to intern automatically:
String s1 = "A";String s2 = "A";
s1 and s2 point to the same String object in the pool. Hence s1 == s2 returns true.
Since interning is automatic for String literals String s1 = “A”, the intern( ) method is to be used on Strings constructed with new String(“A”).
Java 8 has been released in March 2014, so it’s one of the hot topic in java interview questions. If you answer this question clearly, it will show that you like to keep yourself up-to-date with the latest technologies.
Java 8 has been one of the biggest release after Java 5 annotations and generics. Some of the important features of Java 8 are:
Java 9 was a major release and brought a lot of features. Some of the important features are:
A class loader is an object that is responsible for loading classes. The class ClassLoader is an abstract class.
Java is based on Object Oriented Programming Concepts, following are some of the OOPS concepts implemented in java programming.
Let’s look into these object oriented programming concepts one by one. We will use java programming language for code examples, so that you know how to implement OOPS concepts in java.
Abstraction is the concept of hiding the internal details and describing things in simple terms. For example, a method that adds two integers. The method internal processing is hidden from outer world. There are many ways to achieve abstraction in object oriented programming, such as encapsulation and inheritance.
A java program is also a great example of abstraction. Here java takes care of converting simple statements to machine language and hides the inner implementation details from outer world.
Encapsulation is the technique used to implement abstraction in object oriented programming. Encapsulation is used for access restriction to a class members and methods.
Access modifier keywords are used for encapsulation in object oriented programming. For example, encapsulation in java is achieved using private
, protected
and public
keywords.
Polymorphism is the concept where an object behaves differently in different situations. There are two types of polymorphism – compile time polymorphism and runtime polymorphism.
Compile time polymorphism is achieved by method overloading. For example, we can have a class as below.
public class Circle {{"{"}}
public void draw(){{"{"}}
System.out.println("Drwaing circle with default color Black and diameter 1 cm.");
}
public void draw(int diameter){{"{"}}
System.out.println("Drwaing circle with default color Black and diameter"+diameter+" cm.");
}
public void draw(int diameter, String color){{"{"}}
System.out.println("Drwaing circle with color"+color+" and diameter"+diameter+" cm.");
}
}
Here we have multiple draw methods but they have different behavior. This is a case of method overloading because all the methods name is same and arguments are different. Here compiler will be able to identify the method to invoke at compile time, hence it’s called compile time polymorphism.
Runtime polymorphism is implemented when we have “IS-A” relationship between objects. This is also called as method overriding because subclass has to override the superclass method for runtime polymorphism. If we are working in terms of superclass, the actual implementation class is decided at runtime. Compiler is not able to decide which class method will be invoked. This decision is done at runtime, hence the name as runtime polymorphism or dynamic method dispatch.
package com.journaldev.test;
public interface Shape {{"{"}}
public void draw();
}
package com.journaldev.test;
public class Circle implements Shape{{"{"}}
@Override
public void draw(){{"{"}}
System.out.println("Drwaing circle");
}
}
package com.journaldev.test;
public class Square implements Shape {{"{"}}
@Override
public void draw() {{"{"}}
System.out.println("Drawing Square");
}
}
Shape is the superclass and there are two subclasses Circle and Square. Below is an example of runtime polymorphism.
Shape sh = new Circle();
sh.draw();
Shape sh1 = getShape(); //some third party logic to determine shape
sh1.draw();
In above examples, java compiler don’t know the actual implementation class of Shape that will be used at runtime, hence runtime polymorphism.
Inheritance is the object oriented programming concept where an object is based on another object. Inheritance is the mechanism of code reuse. The object that is getting inherited is called superclass and the object that inherits the superclass is called subclass.
We use extends
keyword in java to implement inheritance. Below is a simple example of inheritance in java.
package com.journaldev.java.examples1;
class SuperClassA {{"{"}}
public void foo(){{"{"}}
System.out.println("SuperClassA");
}
}
class SubClassB extends SuperClassA{{"{"}}
public void bar(){{"{"}}
System.out.println("SubClassB");
}
}
public class Test {{"{"}}
public static void main(String args[]){{"{"}}
SubClassB a = new SubClassB();
a.foo();
a.bar();
}
}
Association is the OOPS concept to define the relationship between objects. Association defines the multiplicity between objects. For example Teacher and Student objects. There is one to many relationship between a teacher and students. Similarly a student can have one to many relationship with teacher objects. However both student and teacher objects are independent of each other.
Aggregation is a special type of association. In aggregation, objects have their own life cycle but there is an ownership. Whenever we have “HAS-A” relationship between objects and ownership then it’s a case of aggregation.
Composition is a special case of aggregation. Composition is a more restrictive form of aggregation. When the contained object in “HAS-A” relationship can’t exist on it’s own, then it’s a case of composition. For example, House has-a Room. Here room can’t exist without house.
Abstract classes are used in java to create a class with some default method implementation for subclasses. An abstract class can have abstract method without body and it can have methods with implementation also.
abstract keyword is used to create a abstract class. Abstract classes can’t be instantiated and mostly used to provide base for sub-classes to extend and implement the abstract methods and override or use the implemented methods in abstract class. Read important points about abstract classes at java abstract class.
JAR files is Java Archive fles and it aggregates many files into one. It holds Java classes in a library. JAR files are built on ZIP file format and have .jar file extension.
This is Web Archive File and used to store XML, java classes, and JavaServer pages. which is used to distribute a collection of JavaServer Pages, Java Servlets, Java classes, XML files, static Web pages etc.
It improves the runtime performance of computer programs based on bytecode.
A NullPointerException is thrown when calling the instance method of a null object, accessing or modifying the field of a null object etc.
abstract class | interface |
---|---|
abstract keyword is used to create abstract class | whereas interface is the keyword for interfaces. |
Abstract classes can have method implementations | whereas interfaces can’t. |
A class can extend only one abstract class | but it can implement multiple interfaces. |
We can run abstract class if it has main() method | whereas we can’t run an interface. |
A marker interface is an empty interface without any method but used to force some functionality in implementing classes by Java. Some of the well known marker interfaces are Serializable and Cloneable.
Array List | Vector |
Array List is not synchronized. | Vector is synchronized. |
Array List is fast as it’s non-synchronized. | Vector is slow as it is thread safe. |
If an element is inserted into the Array List, it increases its Array size by 50%. | Vector defaults to doubling size of its array. |
Array List does not define the increment size. | Vector defines the increment size. |
Array List can only use Iterator for traversing an Array List | Except Hashtable, Vector is the only other class which uses both Enumeration and Iterator. |
Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic.
Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic.
“==” or equality operator in Java is a binary operator provided by Java programming language and used to compare primitives and objects. public boolean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. For example: method can be overridden like String class. equals() method is used to compare the values of two objects.
public
class
Equaltest {{"{"}}
public
static
void
main(String[] args) {{"{"}}
String str1=
new
String(“ABCD”);
String str2=
new
String(“ABCD”);
if
(Str1 == str2)
{{"{"}}
System.out.println(
"String 1 == String 2 is true"
);
}
else
{{"{"}}
System.out.println(
"String 1 == String 2 is false"
);
String Str3 = Str2;
if
( Str2 == Str3)
{{"{"}}
System.out.println(
"String 2 == String 3 is true"
);
}
else
{{"{"}}
System.out.println(
"String 2 == String 3 is false"
);
}
if
(Str1.equals(str2))
{{"{"}}
System.out.println(
"String 1 equals string 2 is true"
);
}
else
{{"{"}}
System.out.prinltn(
"String 1 equals string 2 is false"
);
}
}}
There are major difference between Heap and Stack memory are:
Features | Stack | Heap |
---|---|---|
Memory | Stack memory is used only by one thread of execution. | Heap memory is used by all the parts of the application. |
Access | Stack memory can’t be accessed by other threads. | Objects stored in the heap are globally accessible. |
Memory Management | Follows LIFO manner to free memory. | Memory management is based on generation associated to each object. |
Lifetime | Exists until the end of execution of the thread. | Heap memory lives from the start till the end of application execution. |
Usage | Stack memory only contains local primitive and reference variables to objects in heap space. | Whenever an object is created, it’s always stored in the Heap space. |
For performance & thread-safety.
1. Performance: Immutable objects are ideal for representing values of abstract data (i.e. value objects) types like numbers, enumerated types, etc. If you need a different value, create a different object. In Java, Integer, Long, Float, Character, BigInteger and BigDecimal are all immutable objects. Optimization strategies like caching of hashcode, caching of objects, object pooling, etc can be easily applied to improve performance. If Strings were made mutable, string pooling would not be possible as changing the string with one reference will lead to the wrong value for the other references.
2. Thread safety as immutable objects are inherently thread safe as they cannot be modified once created. They can only be used as read only objects. They can easily be shared among multiple threads for better scalability.
The main distinction between fail-fast and fail-safe iterators is whether or not the collection can be modified while it is being iterated. Fail-safe iterators allow this; fail-fast iterators do not.
Fail-fast iterators operate directly on the collection itself. During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified (i.e., upon realizing that a member has been added, modified, or removed) and will throw a ConcurrentModificationException
. Some examples include ArrayList
, HashSet
, and HashMap
(most JDK1.4 collections are implemented to be fail-fast).
Fail-safe iterates operate on a cloned copy of the collection and therefore do not throw an exception if the collection is modified during iteration. Examples would include iterators returned by ConcurrentHashMap
or CopyOnWriteArrayList
.
A single>ThreadLocal
instance can store different values for each thread
independently. Each thread that accesses the get()
or set()
method of
a ThreadLocal
instance is accessing its own, independently initialized copy
of the variable. ThreadLocal
instances are typically private static fields
in classes that wish to associate state with a thread (e.g., a user ID or transaction ID).
The example below, from the ThreadLocal
Javadoc, generates unique identifiers
local to each thread. A thread’s id is assigned the first time it invokes
ThreadId.get()
and remains unchanged on subsequent calls.
public class ThreadId {{"{"}}
// Next thread ID to be assigned
private static final AtomicInteger nextId = new AtomicInteger(0);
// Thread local variable containing each thread's ID
private static final ThreadLocal<Integer> threadId =
new ThreadLocal<Integer>() {{"{"}}
@Override protected Integer initialValue() {{"{"}}
return nextId.getAndIncrement();
}
};
// Returns the current thread's unique ID, assigning it if necessary
public static int get() {{"{"}}
return threadId.get();
}
}
Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).
In Java, each thread has its own stack, including its own copy of variables it can access.
When the thread is created, it copies the value of all accessible variables into its own stack. The volatile
keyword basically says to the JVM “Warning, this variable may be modified in another Thread”.
In all versions of Java, the volatile
keyword guarantees global ordering on reads and writes to a variable. This implies that every thread accessing a volatile field will read the variable’s current value instead of (potentially) using a cached value.
In Java 5 or later, volatile
reads and writes establish a happens-before relationship, much like acquiring and releasing a mutex.
Using volatile
may be faster than a lock, but it will not work in some situations. The range of situations in which volatile is effective was expanded in Java 5; in particular, double-checked locking now works correctly.
The volatile keyword is also useful for 64-bit types like long and double since they are written in two operations. Without the volatile keyword you risk stale or invalid values.
One common example for using volatile
is for a flag to terminate a thread. If you’ve started a thread, and you want to be able to safely interrupt it from a different thread, you can have the thread periodically check a flag (i.e., to stop it, set the flag to true
). By making the flag volatile, you can ensure that the thread that is checking its value will see that it has been set to true
without even having to use a synchronized block. For example:
public class Foo extends Thread {{"{"}}
private volatile boolean close = false;
public void run() {{"{"}}
while(!close) {{"{"}}
// do work
}
}
public void close() {{"{"}}
close = true;
// interrupt here if needed
}
}
A server is a computer program that provides a service to another computer programs (and its user). In a data center, the physical computer that a server program runs in is also frequently referred to as a server. That machine may be a dedicated server or it may be used for other purposes as well.
In the client/server programming model, a server program awaits and fulfills requests from client programs, which may be running in the same or other computers. A given application in a computer may function as a client with requests for services from other programs and also as a server of requests from other programs.
Interfaces are core part of java programming language and used a lot not only in JDK but also java design patterns, most of the frameworks and tools. Interfaces provide a way to achieve abstraction in java and used to define the contract for the subclasses to implement.
For example, let’s say we want to create a drawing consists of multiple shapes. Here we can create an interface Shape
and define all the methods that different types of Shape objects will implement. For simplicity purpose, we can keep only two methods – draw()
to draw the shape and getArea()
that will return the area of the shape.
package com.journaldev.design;
public interface Shape {{"{"}}
//implicitly public, static and final
public String LABLE="Shape";
//interface methods are implicitly abstract and public
void draw();
double getArea();
}
interface
is the code that is used to create an interface in java.public interface Shape extends Cloneable{{"{"}}}
is an example of an interface extending another interface. Actually java provides multiple inheritance in interfaces, what is means is that an interface can extend multiple interfaces.implements
keyword is used by classes to implement an interface.ShapeAbs.java
package com.journaldev.design;
public abstract class ShapeAbs implements Shape {{"{"}}
@Override
public double getArea() {{"{"}}
// TODO Auto-generated method stub
return 0;
}
}
Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX/Linux like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc.
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism.
To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following −
Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
Netbeans − A Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html.
Eclipse − A Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/.
The following list of reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.
abstract | assert | boolean | break |
byte | case | catch | char |
class | const | continue | default |
do | double | else | enum |
extends | final | finally | float |
for | goto | if | implements |
import | instanceof | int | interface |
long | native | new | package |
private | protected | public | return |
short | static | strictfp | super |
switch | synchronized | this | throw |
throws | transient | try | void |
volatile | while |
Java Reflection API provides the ability to inspect and modify the runtime behavior of java application. We can inspect a java class, interface, enum and get their methods and field details. Reflection API is an advanced topic and we should avoid it in normal programming. Reflection API usage can break the design pattern such as Singleton pattern by invoking the private constructor i.e violating the rules of access modifiers.
Even though we don’t use Reflection API in normal programming, it’s very important to have. We can’t have any frameworks such as Spring, Hibernate or servers such as Tomcat, JBoss without Reflection API. They invoke the appropriate methods and instantiate classes through reflection API and use it a lot for other processing.