Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

TOP JAVA INTERVIEW QUESTIONS

AND ANSWER YOU MUST PREPARE


java InterviewDaddy October 5, 2018 0
Top Java Interview Questions and Answer You Must Prepare

Welcome to topInterviewsQuestion.us. In this post, We will discuss the mostly asked Java Interview
Questions and Answers which can help freshers and as well as experienced candidates.

There is the list of core java interview questions. If there is any core java interview question that has been
asked to you, kindly post it in the ask question section. We assure that you will get here the 90%
frequently asked interview questions and answers.

The answers to the core java interview questions are short and to the point. The core java interview
questions are categorized in Basics of java interview questions, Oops interview questions, String Handling
interview questions, Multi-threading interview questions, collection interview questions, JDBC interview
questions, etc.

#Note: All Java questions written below are personal experience based so Please try to cover all the
questions & get succeed in the interview.

All the best !!

Java Interview Questions and Answers


Q. What is Java?
Java is the high-level, object-oriented, robust, secure programming language, platform-independent, high
performance, Multi-threaded, and portable programming language. It was developed by James
Gosling in June 1991. It can also be known as the platform as it provides its own JRE and API.
Q. Explain JDK, JRE and JVM?

JDK vs JRE vs JVM


JDK JRE JVM
It stands for
It stands for Java
Java Runtime It stands for Java Virtual Machine.
Development Kit.
Environment.
JRE refers to a
It is the tool
run-time
necessary to It is an abstract machine. It is a
environment in
compile, specification that provides run-time
which
document and environment in which java byte-
java byte-
package Java code can be executed.
code can be
programs.
executed.
It implements
the JVM (Java
Virtual
Machine) and
Along with JRE, it provides all the
includes an class libraries
interpreter/loader, and other
JVM follows three notations:
a support files
Specification(document that
compiler (javac), that JVM uses
describes the implementation of the
an archiver (jar), at run-time. So
Java virtual
a documentation JRE is a
machine), Implementation(program
generator (java- software
that meets the requirements of
doc) and other package that
JVM specification) and Run-
tools needed in contains what
time Instance (instance of JVM is
Java is required to
created whenever you write a
development. In run a Java
java command on the command
short, it contains program.
prompt and run class).
JRE + Basically, it’s
development an
tools. implementation
of the JVM
which
physically
exists.

Q. What are the differences between C++ and Java?


The differences between C++ and Java are given in the following table.

Comparison
C++ Java
Index
Platform- C++ is platform-
Java is platform-independent.
independent dependent.
Mainly used C++ is mainly used Java is mainly used for
for for system application programming. It is
programming. widely used in window, web-
based, enterprise and mobile
applications.
Java was designed and created
C++ was designed
as an interpreter for printing
for systems and
systems but later extended as a
applications
support network computing. It
Design Goal programming. It was
was designed with a goal of
an extension of C
being easy to use and
programming
accessible to a broader
language.
audience.
C++ supports Java doesn’t support the goto
Goto
the goto statement. statement.
Java doesn’t support multiple
Multiple C++ supports inheritance through class. It can
inheritance multiple inheritance. be achieved by interfaces in
java.
C++
Operator Java doesn’t support operator
supports operator
Overloading overloading.
overloading.
C++ Java supports pointer internally.
supports pointers. However, you can’t write the
Pointers You can write pointer program in java. It means
pointer program in java has restricted pointer
C++. support in java.
C++ uses compiler Java uses compiler and
only. C++ is interpreter both. Java source
compiled and run code is converted into bytecode
using the compiler at compilation time. The
Compiler and
which converts interpreter executes this
Interpreter
source code into bytecode at runtime and
machine code so, produces output. Java is
C++ is platform interpreted that is why it is
dependent. platform independent.
Call by Value C++ supports both Java supports call by value only.
and Call by call by value and There is no call by reference in
reference call by reference. java.
C++ supports
Structure and Java doesn’t support structures
structures and
Union and unions.
unions.
C++ doesn’t have
built-in support for
Thread
threads. It relies on Java has built-in thread support.
Support
third-party libraries
for thread support.
Java supports documentation
C++ doesn’t support
Documentation comment (/** … */) to create
documentation
comment documentation for java source
comment.
code.
C++ supports virtual Java has no virtual keyword. We
keyword so that we can override all non-static
Virtual
can decide whether methods by default. In other
Keyword
or not override a words, non-static methods are
function. virtual by default.
unsigned right C++ doesn’t support Java supports unsigned right
shift >>> >>> operator. shift >>> operator that fills zero
at the top for the negative
numbers. For positive numbers,
it works same like >> operator.
Java uses a single inheritance
C++ creates a new tree always because all classes
Inheritance
inheritance tree are the child of Object class in
Tree
always. java. The object class is the root
of the inheritance tree in java.
C++ is nearer to Java is not so interactive with
Hardware
hardware. hardware.
Java is also an object-
C++ is an object-
oriented language. However,
oriented language.
everything (except fundamental
Object- However, in C
types) is an object in Java. It is a
oriented language, single
single root hierarchy as
root hierarchy is not
everything gets derived from
possible.
java.lang.Object.

Q. What are the various access specifiers for Java classes?


Ans: In Java, access specifiers are the keywords used before a class name which defines the access
scope. The types of access specifiers for classes are:

1. Public : Class,Method,Field is accessible from anywhere.

2. Protected:Method,Field can be accessed from the same class to which they belong or from the sub-
classes,and from the class of same package,but not from outside.

3. Default: Method,Field,class can be accessed only from the same package and not from outside of it’s
native package.

4. Private: Method,Field can be accessed from the same class to which they belong.

Q. What is the difference between an Inner Class and a Sub-Class?


Ans: An Inner class is a class which is nested within another class. An Inner class has access rights for
the class which is nesting it and it can access all variables and methods defined in the outer class.

A sub-class is a class which inherits from another class called super class. Sub-class can access all public
and protected methods and fields of its super class.

Q. Why java is not 100% Object-oriented?


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.

Q. List the features of Java Programming language.


There are the following features in Java Programming Language.
Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to
write the program in it.
Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain
our code as the combination of different type of objects that incorporates both data and
behavior.

Portable: Java supports read-once-write-anywhere approach. We can execute the Java


program on every machine. Java program (.java) is converted to bytecode (.class) which
can be easily run on every machine.

Platform Independent: Java is a platform independent programming language. It is


different from other programming languages like C and C++ which needs a platform to be
executed. Java comes with its platform on which its code is executed. Java doesn’t depend
upon the operating system to be executed.

Secured: Java is secured because it doesn’t use explicit pointers. Java also provides the
concept of ByteCode and Exception handling which makes it more secured.

Robust: Java is a strong programming language as it uses strong memory management.


The concepts like Automatic garbage collection, Exception handling, etc. make it more
robust.

Architecture Neutral: Java is architectural neutral as it is not dependent on the


architecture. In C, the size of data types may vary according to the architecture (32 bit or 64
bit) which doesn’t exist in Java.

Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the
program execution.

High Performance: Java is faster than other traditional interpreted programming


languages because Java bytecode is “close” to native code. It is still a little bit slower than a
compiled language (e.g., C++).

Multithreaded: We can write Java programs that deal with many tasks at once by defining
multiple threads. The main advantage of multi-threading is that it doesn’t occupy memory
for each thread. It shares a common memory area. Threads are important for multi-media,
Web applications, etc.

Distributed: Java is distributed because it facilitates users to create distributed applications


in Java. RMI and EJB are used for creating distributed applications. This feature of Java
makes us able to access files by calling the methods from any machine on the internet.

Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means


classes are loaded on demand. It also supports functions from its native languages, i.e., C
and C++.

Q. What are constructors in Java?


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 types of constructors:

1. Default constructor
2. Parameterized constructor

Q. What do you mean by Object?


An object consists of methods and class which depict its state and perform operations. A java program
contains a lot of objects instructing each other their jobs. This concept is a part of core java.

Q. What are Loops in Java? What are three types of loops?

Ans: Looping is used in programming to execute a statement or a block of statement repeatedly. There are
three types of loops in Java:

1) For Loops
For loops are used in java to execute statements repeatedly for a given number of times. For loops are
used when number of times to execute the statements is known to programmer.

2) While Loops
While loop is used when certain statements need to be executed repeatedly until a condition is fulfilled. In
while loops, condition is checked first before execution of statements.

3) Do While Loops
Do While Loop is same as While loop with only difference that condition is checked after execution of
block of statements. Hence in case of do while loop, statements are executed at least once.

Q. What do you understand by Java virtual machine?


Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM acts
like a run-time engine which calls the main method present in the Java code. JVM is the specification
which must be implemented in the computer system. The Java code is compiled by JVM to be a Byte-
code which is machine independent and close to the native code.

Q. What is the difference between Array list and vector?


Array List Vector
Array List is not synchronized. Vector is synchronized.
Array List is fast as it’s non-
Vector is slow as it is thread safe.
synchronized.
If an element is inserted into
Vector defaults to doubling size of its
the Array List, it increases its
array.
Array size by 50%.
Array List does not define the
Vector defines the increment size.
increment size.
Except Hash-table, Vector is the only
Array List can only use Iterator
other class which uses both
for traversing an Array List.
Enumeration and Iterator.

Q. How many types of memory areas are allocated by JVM?

Many types:
1. Class(Method) Area: Class Area stores per-class structures such as the runtime constant pool,
field, method data, and the code for methods.
2. Heap: It is the runtime data area in which the memory is allocated to the objects
3. Stack: Java Stack stores frames. It holds local variables and partial results, and plays a part in
method invocation and return. Each thread has a private JVM stack, created at the same time as the
thread. A new frame is created each time a method is invoked. A frame is destroyed when its
method invocation completes.
4. Program Counter Register: PC (program counter) register contains the address of the Java virtual
machine instruction currently being executed.
5. Native Method Stack: It contains all the native methods used in the application.

Q. What are the differences between Heap and Stack Memory?


The major difference between Heap and Stack memory are:

Features Stack Heap


Heap memory is used
Stack memory is used only by
Memory by all the parts of the
one thread of execution.
application.
Objects stored in the
Stack memory can’t be
Access heap are globally
accessed by other threads.
accessible.
Memory management is
Memory Follows LIFO manner to free based on generation
Management memory. associated to each
object.
Heap memory lives from
Exists until the end of
Lifetime the start till the end of
execution of the thread.
application execution.
Stack memory only contains Whenever an object is
local primitive and reference created, it’s always
Usage
variables to objects in heap stored in the Heap
space. space.

Q. Define Inheritance.
Java includes the feature of inheritance which an object-oriented programming concept. Inheritance lets a
derived class to inherit the methods of a base class.

Q. What do you mean by Object?


Object is a run-time entity and it’s state is stored in fields and behavior is shown via methods. Methods
operate on an object’s internal state and serve as the primary mechanism for object-to-object
communication.

Q. What is the difference between equals() and == ?


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");
}
}}

Q. Explain method overloading.


When a Java program contains more than one methods with the same name but different properties, then
it is called method overloading.

Q. Compare Overloading and Overriding.


Overloading refers to the case of having two methods of same name but different properties, but
overriding occurs when there are two methods of same name and properties, but one is in child class and
one is in parent class.

Q How can you generate random numbers in Java?


Using Math.random() you can generate random numbers in the range greater than or equal to 0.1
and less than 1.0
Using Random class in package java.util
Q. What is ternary operator? Give an example.
Ans: Ternary operator , also called conditional operator is used to decide which value to assign to a
variable based on a Boolean value evaluation. It’s denoted as ?

In the below example, if rank is 1, status is assigned a value of “Done” else “Pending”.

public class conditionTest {


public static void main(String args[]) {
String status;
int rank = 3;
status = (rank == 1) ? "Done" : "Pending";
System.out.println(status);
}
}

Q. Differentiate between Iterator and Enumeration?


Iterator Enumeration
Enumeration is an object that
Iterator is an interface found in generates elements one at a time.
the java.util package. Used for passing through a collection
for unknown size.
Uses 3 methods to interface
such as: Methods used are:

1. i) hasNext() 1. i) hasMoreElements()
2. ii) next() 2. ii) nextElement()
3. iii) remove()

Iterators allow removing


elements from the given It is used for passing through a
collection during the iteration collection, usually of unknown size.
with well-defined semantics.
Iterator method names have The traversing of elements can only
been improved. be done once per creation

Q. Difference between the Inner Class and Sub Class.


Inner Class Sub Class
It’s a class which inherits
It’s a class which is nested within another
from another class called
class.
super class.
Inner class provides the access rights for Sub-class provides access
the class which is nesting it and that can to all public and protected
access all variables and methods defined methods and fields of its
in the outer class. super class.

Q. What is JIT compiler?


Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the bytecode
that have similar functionality at the same time, and hence reduces the amount of time needed for
compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual
machine (JVM) to the instruction set of a specific CPU.

Q. What is the platform?


A platform is the hardware or software environment in which a piece of software is executed. There are
two types of platforms, software-based and hardware-based. Java provides the software-based platform.

Q. What are the main differences between the Java platform and other platforms?
There are the following differences between the Java platform and other platforms.

Java is the software-based platform whereas other platforms may be the hardware platforms or
software-based platforms.
Java is executed on the top of other hardware platforms whereas other platforms can only have the
hardware components.

Q. Java doesn’t support multiple inheritance. Why?


Java doesn’t support multiple inheritance. Because we cannot use different methods in one class it
creates an ambiguity.
Example:

class Intellipaat1
{
void test()
{
system.out.println("test() method");
}
}class Intellipaat2
{
void test()
{
system.out.println("test() method");
}
}Multiple inheritance
class C extends Intellipaat1, Intellipaat2
{
………………………………………….
…………………………………………..
}

Intellipaat1 and Intellipaat2 test() methods are inheriting to class C


So which test() method C class will take. As Intellipaat1 & Intellipaat2 class test () methods are different,
So here we would face ambiguity.

Q. Define JSON?
Expansion of JSON is “JavaScript Object Notation”, It is a much lighter and readable alternative to XML. It
is an independent and easily parse-able in all programming languages. It is primarily used for
Communicating between client – server or server -server communication. It is a much lighter and readable
alternative to XML.

Q. What are the advantages of JSON over XML?


The advantages of JSON over XML are

1. JSON is Lighter and faster than XML


2. Better understandable.
3. Easy to parse and conversion to objects for information consumption.
4. Support multiple data types – JSON support string, number, array, Boolean but XML data are all
strings.

Q. What is class-loader?
Class-loader is a subsystem of JVM which is used to load class files. Whenever we run the java program,
it is loaded first by the class-loader. There are three built-in class-loaders in Java.

1. Bootstrap Class Loader: This is the first class-loader which is the super class of Extension class-
loader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang
package classes, java.net package classes, java.util package classes, java.io package classes,
java.sql package classes, etc.
2. Extension Class Loader: This is the child class loader of Bootstrap and parent class-loader of
System class loader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application Class Loader: This is the child class-loader of Extension class-loader. It loads
the class files from the class-path. By default, the class path is set to the current directory. You can
change the class path using “-cp” or “-class path” switch. It is also known as Application class loader.

Q. What is the output of the following Java program?


1. class Test
2. {
3. public static void main (String args[])
4. {
5. System.out.println(10 + 20 + “Javatpoint”);
6. System.out.println(“Javatpoint” + 10 + 20);
7. }
8. }

The output of the above code will be :

30Javatpoint
Javatpoint1020

Explanation :

In the first case, 10 and 20 are treated as numbers and added to be 30. Now, their sum 30 is treated as
the string and concatenated with the string Javatpoint. Therefore, the output will be 30Javatpoint.

In the second case, the string Javatpoint is concatenated with 10 to be the string Javatpoint10 which will
then be concatenated with 20 to be Javatpoint1020.
Core Java – OOPs Concepts: Initial OOPs Interview Questions
Q. What is Polymorphism?

Polymorphism is briefly described as “one interface, many implementations”. Polymorphism is a


characteristic of being able to assign a different meaning or usage to something in different contexts –
specifically, to allow an entity such as a variable, a function, or an object to have more than one form.
There are two types of polymorphism:

1. Compile time polymorphism


2. Run time polymorphism

Compile time polymorphism is method overloading whereas Runtime time polymorphism is done using
inheritance and interface.

Q. What is object-oriented paradigm?


It is a programming paradigm based on objects having data and methods defined in the class to which it
belongs. Object-oriented paradigm aims to incorporate the advantages of modularity and reusability.
Objects are the instances of classes which interacts with one another to design applications and
programs. There are the following features of the object-oriented paradigm.

Follows the bottom-up approach in program design.


Focus on data with methods to operate upon the object?s data
Includes the concept like Encapsulation and abstraction which hides the complexities from the user
and show only functionality.
Implements the real-time approach like inheritance, abstraction, etc.
The examples of the object-oriented paradigm are C++, Simula, Smalltalk, Python, C#, etc.

Q. What is the difference between an object-oriented programming language and object-


based programming language?
There are the following basic differences between the object-oriented language and object-based
language.

Object-oriented languages follow all the concepts of OOPs whereas, the object-based language
doesn’t follow all the concepts of OOPs like inheritance and polymorphism.
Object-oriented languages do not have the inbuilt objects whereas Object-based languages have the
inbuilt objects, for example, JavaScript has window object.
Examples of object-oriented programming are Java, C#, Smalltalk, etc. whereas the examples of
object-based languages are JavaScript, VBScript, etc
Q. What is multiple inheritance? Is it supported by Java?
If a child class inherits the property from multiple classes is known as multiple
inheritance. Java does not allow to extend multiple classes.

The problem with multiple inheritance is that if multiple parent classes have a
same method name, then at runtime it becomes difficult for the compiler to
decide which method to execute from the child class.

Therefore, Java doesn’t support multiple inheritance. The problem is commonly


referred as Diamond Problem.

Q. What is run-time polymorphism or dynamic method dispatch?


In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden
method is resolved at runtime rather than at compile-time. In this process, an overridden method is called
through the reference variable of a superclass. Let’s take a look at the example below to understand it
better.

class Car {
void run()
{
System.out.println(“car is running”);
}
}
class Audi extends Car {
void run()
{
System.out.prinltn(“Audi is running safely with 100km”);
}
public static void main(String args[])
{
Car b= new Audi(); //upcasting
b.run();
}
}

Q. What is method overloading and method overriding?

Method Overloading :

In Method Overloading, Methods of the same class shares the same name but each method must
have different number of parameters or parameters having different types and order.
Method Overloading is to “add” or “extend” more to method’s behavior.
It is a compile time polymorphism.
The methods must have different signature.
It may or may not need inheritance in Method Overloading.
Let’s take a look at the example below to understand it better.

class Adder {
Static int add(int a, int b)
{
return a+b;
}
Static double add( double a, double b)
{
return a+b;
}
public static void main(String args[])
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

Method Overriding:

In Method Overriding, sub class have the same method with same name and exactly the same
number and type of parameters and same return type as a super class.
Method Overriding is to “Change” existing behavior of method.
It is a run time polymorphism.
The methods must have same signature.
It always requires inheritance in Method Overriding.

Let’s take a look at the example below to understand it better.

class Car {
void run(){
System.out.println(“car is running”);
}
Class Audi extends Car{
void run()
{
System.out.prinltn(“Audi is running safely with 100km”);
}
public static void main( String args[])
{
Car b=new Audi();
b.run();
}
}

Q. What is the difference between abstract classes and interfaces?


Abstract Class Interfaces
An abstract class can provide An interface cannot provide any
complete, default code and/or just code at all,just the signature.
the details that have to be
overridden.
In case of abstract class, a class
A Class may implement several
may extend only one abstract
interfaces.
class.
An abstract class can have non- All methods of an Interface are
abstract methods. abstract.
An abstract class can have An Interface cannot have instance
instance variables. variables
An abstract class can have any An Interface visibility must be
visibility: public, private, protected. public (or) none.
If we add a new method to an If we add a new method to an
abstract class then we have the Interface then we have to track
option of providing default down all the implementations of
implementation and therefore all the interface and define
the existing code might work implementation for the new
properly method
An abstract class can contain An Interface cannot contain
constructors constructors
Interfaces are slow as it requires
extra indirection to find
Abstract classes are fast
corresponding method in the
actual class

Q. Can you override a private or static method in Java?


You cannot override a private or static method in Java. If you create a similar method with same return
type and same method arguments in child class then it will hide the super class method; this is known as
method hiding. Similarly, you cannot override a private method in sub class because it’s not accessible
there. What you can do is create another private method with the same name in the child class. Let’s take
a look at the example below to understand it better.

class Base {
private static void display() {
System.out.println("Static or class method from Base");
}
public void print() {
System.out.println("Non-static or instance method from Base");
}
class Derived extends Base {
private static void display() {
System.out.println("Static or class method from Derived");
}
public void print() {
System.out.println("Non-static or instance method from Derived");
}
public class test {
public static void main(String args[])
{
Base obj= new Derived();
obj1.display();
obj1.print();
}
}

Q. What do you mean by aggregation?


Aggregation is a specialized form of Association where all object have their own life-cycle but there is
ownership and child object can not belongs to another parent object. Let’s take an example of Department
and teacher. A single teacher can not belongs to multiple departments, but if we delete the department
teacher object will not destroy.

Q. What is composition in Java?


Composition is again specialized form of Aggregation and we can call this as a “death” relationship. It is a
strong type of Aggregation. Child object dose not have their life-cycle and if parent object deletes all child
object will also be deleted. Let’s take again an example of relationship between House and rooms. House
can contain multiple rooms there is no independent life of room and any room can not belongs to two
different house if we delete the house room will automatically delete.

You might also like