0% found this document useful (0 votes)
15 views

Java Basics

This document contains hints and answers for 45 Java interview questions. The questions cover topics like Java fundamentals, OOP concepts, collections, concurrency, exceptions and more. Sample questions include how Java achieves platform independence, difference between ArrayList and LinkedList, when to use volatile variable and difference between Comparator and Comparable.

Uploaded by

lxystylist
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Java Basics

This document contains hints and answers for 45 Java interview questions. The questions cover topics like Java fundamentals, OOP concepts, collections, concurrency, exceptions and more. Sample questions include how Java achieves platform independence, difference between ArrayList and LinkedList, when to use volatile variable and difference between Comparator and Comparable.

Uploaded by

lxystylist
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 131

1

1) How does Java achieve platform independence? (answer)

hint: bytecode and Java Virtual Machine

2) What is ClassLoader in Java? (answer)

hint: part of JVM that loads bytecodes for classes. You can write your own.

3) Write a Java program to check if a number is Even or Odd? (answer)

hint: you can use bitwise operator, like bitwise AND, remember, even the number has
zero at the end in binary format and an odd number has 1 in the end.

4) Difference between ArrayList and HashSet in Java? (answer)

hint: all differences between List and Set are applicable here, e.g. ordering, duplicates,
random search, etc. See Java Fundamentals: Collections by Richard Warburton to learn
more about ArrayList, HashSet and other important Collections in Java.
2

5) What is double-checked locking in Singleton? (answer)

hint: two-time check whether instances are initialized or not, first without locking and
second with locking.

6) How do you create thread-safe Singleton in Java? (answer)

hint: many ways, like using Enum or by using double-checked locking pattern or using a
nested static class.

7) When to use the volatile variable in Java? (answer)


3

hint: when you need to instruct the JVM that a variable can be modified by multiple
threads and give hint to JVM that does not cache its value.

8) When to use a transient variable in Java? (answer)

hint: when you want to make a variable non-serializable in a class, which implements the
Serializable interface. In other words, you can use it for a variable whose value you don’t
want to save. See The Complete Java MasterClass to learn about transient variables in
Java.

9) Difference between the transient and volatile variable in Java? (answer)

hint: totally different, one used in the context of serialization while the other is used in
concurrency.

10) Difference between Serializable and Externalizable in Java? (answer)

hint: Externalizable gives you more control over the Serialization process.

11) Can we override the private method in Java? (answer)

hint: No, because it’s not visible in the subclass, a primary requirement for overriding a
method in Java.

12) Difference between Hashtable and HashMap in Java? (answer)

hint: several but most important is Hashtable, which is synchronized, while HashMap is
not. It's also legacy and slow as compared to HashMap.
4

13) Difference between Listand Set in Java? (answer)

hint: List is ordered and allows duplicate. Set is unordered and doesn't allow duplicate
elements.

14) Difference between ArrayList and Vector in Java (answer)

hint: Many, but most important is that ArrayList is non-synchronized and fast while
Vector is synchronized and slow. It's also legacy class like Hashtable.

15) Difference between Hashtable and ConcurrentHashMap in Java? (answer)

hint: more scalable. See Java Fundamentals: Collections by Richard Warburton to learn
more.

16) How does ConcurrentHashMap achieve scalability? (answer)

hint: by dividing the map into segments and only locking during the write operation.

17) Which two methods you will override for an Object to be used as Key in HashMap?
(answer)

hint: equals and hashcode

18) Difference between wait and sleep in Java? (answer)

hint: The wait() method releases the lock or monitor, while sleep doesn't.
5

19) Difference between notify and notifyAll in Java? (answer)

hint: notify notifies one random thread is waiting for that lock while notifyAll inform to
all threads waiting for a monitor. If you are certain that only one thread is waiting then
use notify, or else notifyAll is better. See Threading Essentials Mini-Course by Java
Champion Heinz Kabutz to learn more about threading basics.

20) Why do you override hashcode, along with equals() in Java? (answer)

hint: to be compliant with equals and hashcode contract, which is required if you are
planning to store your object into collection classes, e.g. HashMap or ArrayList.

21) What is the load factor of HashMap means? (answer)

hint: The threshold that triggers the re-sizing of HashMap is generally 0.75, which means
HashMap resize itself if it's 75 percent full.

22) Difference between ArrayList and LinkedList in Java? (answer)

hint: same as an array and linked list, one allows random search while the other doesn't.
Insertion and deletion are easy on the linked list but a search is easy on an array. See
Java Fundamentals: Collections, Richard Warburton’s course on Pluralsight, to learn
more about essential Collection data structure in Java.
6

23) Difference between CountDownLatch and CyclicBarrier in Java? (answer)

hint: You can reuse CyclicBarrier after the barrier is broken but you cannot reuse
CountDownLatch after the count reaches to zero.

24) When do you use Runnable vs Thread in Java? (answer)

hint: always

25) What is the meaning of Enum being type-safe in Java? (answer)

hint: It means you cannot assign an instance of different Enum type to an Enum variable.
e.g. if you have a variable like DayOfWeek day then you cannot assign it value from
DayOfMonth enum.

26) How does Autoboxing of Integer work in Java? (answer)

hint: By using the valueOf() method in Java.

27) Difference between PATH and Classpath in Java? (answer)

hint: PATH is used by the operating system while Classpath is used by JVM to locate Java
binary, e.g. JAR files or Class files. See Java Fundamentals: The Core Platform to learn
more about PATH, Classpath, and other Java environment variable.

28) Difference between method overloading and overriding in Java? (answer)


7

hint: Overriding happens at subclass while overloading happens in the same class. Also,
overriding is a runtime activity while overloading is resolved at compile time.

29) How do you prevent a class from being sub-classed in Java? (answer)

hint: just make its constructor private

30) How do you restrict your class from being used by your client? (answer)

hint: make the constructor private or throw an exception from the constructor

31) Difference between StringBuilder and StringBuffer in Java? (answer)

hint: StringBuilder is not synchronized while StringBuffer is synchronized.

32) Difference between Polymorphism and Inheritance in Java? (answer)

hint: Inheritance allows code reuse and builds the relationship between classes, which is
required by Polymorphism, which provides dynamic behavior. See Grokking the
Object-Oriented Design Interview courses on Educative to learn more about OOP
features and designing classes using OOP techniques.

33) Can we override the static method in Java? (answer)

hint: No, because overriding resolves at runtime while static method call is resolved at
compile time.

34) Can we access the private method in Java? (answer)


8

hint: yes, in the same class but not outside the class

35) Difference between interface and abstract class in Java? (answer)

hint: from Java 8, the difference is blurred. However, a Java class can still implement
multiple interfaces but can only extend one class.

36) Difference between DOM and SAX parser in Java? (answer)

hint: DOM loads the whole XML File in memory while SAX doesn’t. It is an event-based
parser and can be used to parse a large file, but DOM is fast and should be preferred for
small files.

37) Difference between the throw and throws keyword in Java? (answer)

hint: throws declare what exception a method can throw in case of error but throw
keyword actually throws an exception. See Java Fundamentals: Exception Handling to
learn more about Exception handling in Java.
9

38) Difference between fail-safe and fail-fast iterators in Java? (answer)

hint: fail-safe doesn’t throw ConcurrentModificationException while fail-fastdoes


whenever they detect an outside change on the underlying collection while iterating
over it.

39) Difference between Iterator and Enumeration in Java? (answer)

hint: Iterator also gives you the ability to remove an element while iterating while
Enumeration doesn’t allow that.

40) What is IdentityHashMap in Java? (answer)

hint: A Map, which uses the == equality operator to check equality instead of the
equals() method.

41) What is the String pool in Java? (answer)

hint: A pool of String literals. Remember it's moved to heap from perm gen space in JDK
7.
10

42) Can a Serializable class contains a non-serializable field in Java? (answer)

hint: Yes, but you need to make it either static or transient.

43) Difference between this and super in Java? (answer)

hint: this refers to the current instance while super refers to an instance of the
superclass.

44) Difference between Comparator and Comparable in Java? (answer)


11

hint: Comparator defines custom ordering while Comparable defines the natural order
of objects, e.g. the alphabetic order for String. See The Complete Java MasterClass to
learn more about sorting in Java.

45) Difference between java.util.Date and java.sql.Date in Java? (answer)

hint: former contains both date and time while later contains only date part.

46) Why wait and notify methods are declared in Object class in Java? (answer)

hint: because they require a lock that is only available to an object.


12

47) Why Java doesn’t support multiple inheritances? (answer)

hint: It doesn’t support because of a bad experience with C++, but with Java 8, it does in
some sense — only multiple inheritances of Type are not supported in Java now.

48) Difference between Checked and Unchecked Exception in Java? (answer)

hint: In case of checked, you must handle exception using catch block, while in case of
unchecked, it’s up to you; compile will not bother you.
13

49) Difference between Error and Exception in Java? (answer)

hint: I am tired of typing please check the answer

50) Difference between Race condition and Deadlock in Java? (answer)

hint: both are errors that occur in a concurrent application, one occurs because of
thread scheduling while others occur because of poor coding. See Multithreading and
Parallel Computing in Java to learn more about deadlock, Race Conditions, and other
multithreading issues.
14

Basic Java Interview Questions for Freshers


Q1. Explain JDK, JRE and JVM?

Q2. Explain public static void main(String args[]) in Java.


main() in Java is the entry point for any Java program. It is always written as public static
void main(String[] args).

● public: Public is an access modifier, which is used to specify who can access this
method. Public means that this Method will be accessible by any Class.
● static: It is a keyword in java which identifies it is class-based. main() is made
static in Java so that it can be accessed without creating the instance of a Class. In
case, main is not made static then the compiler will throw an error as main() is
called by the JVM before any objects are made and only static methods can be
directly invoked via the class.
● void: It is the return type of the method. Void defines the method which will not
return any value.
● main: It is the name of the method which is searched by JVM as a starting point
for an application with a particular signature only. It is the method where the
main execution occurs.
15

● String args[]: It is the parameter passed to the main method.

Q3. Why Java is platform independent?


Java is called platform independent because of its byte codes which can run on any
system irrespective of its underlying operating system.

Q4. Why Java is not 100% Object-oriented?

Java is not 100% Object-oriented because it makes use of eight primitive data types such
as boolean, byte, char, int, float, double, long, short which are not objects.

Q5. What are wrapper classes in Java?


Wrapper classes convert 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.

Q6. 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: In Java, a default constructor is the one which does not take
any inputs. In other words, default constructors are the no argument constructors
which will be created by default in case you no other constructor is defined by the
user. Its main purpose is to initialize the instance variables with the default values.
Also, it is majorly used for object creation.
2. Parameterized Constructor: The parameterized constructor in Java, is the
constructor which is capable of initializing the instance variables with the
provided values. In other words, the constructors which take the arguments are
called parameterized constructors.
16

Q7. What is singleton class in Java and how can we make a class singleton?
Singleton class is a class whose only one instance can be created at any given time, in
one JVM. A class can be made singleton by making its constructor private.

Q8. What is the difference between Array list and vector in Java?

Q9. What is the difference between equals() and == in Java?


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.

Q10. When can you use the super keyword?


In Java, the super keyword is a reference variable that refers to an immediate parent
class object.
17

When you create a subclass instance, you’re also creating an instance of the parent class,
which is referenced to by the super reference variable.

The uses of the Java super Keyword are-

1. To refer to an immediate parent class instance variable, use super.


2. The keyword super can be used to call the method of an immediate parent class.
3. Super() can be used to call the constructor of the immediate parent class.

Q11. What makes a HashSet different from a TreeSet?

Q12. What are the differences between HashMap and HashTable in Java?
18

Q13. What is the importance of reflection in Java?

Reflection is a runtime API for inspecting and changing the behavior of methods, classes,
and interfaces. Java Reflection is a powerful tool that can be really beneficial. Java
Reflection allows you to analyze classes, interfaces, fields, and methods during runtime
without knowing what they are called at compile time. Reflection can also be used to
create new objects, call methods, and get/set field values. External, user-defined classes
can be used by creating instances of extensibility objects with their fully-qualified
names. Debuggers can also use reflection to examine private members of classes.

Q14. How to not allow serialization of attributes of a class in Java?

The Non-Serialized attribute can be used to prevent member variables from being
serialized.

You should also make an object that potentially contains security-sensitive data
non-serializable if possible. Apply the Non-Serialized attribute to certain fields that store
sensitive data if the object must be serialized. If you don’t exclude these fields from
serialization, the data they store will be visible to any programs with serialization
permission.

Q15. Can you call a constructor of a class inside another constructor?

Yes, we can call a constructor of a class inside another constructor. This is also called as
constructor chaining. Constructor chaining can be done in 2 ways-
19

1. Within the same class: For constructors in the same class, the this() keyword can
be used.
2. From the base class: The super() keyword is used to call the constructor from the
base class.
The constructor chaining follows the process of inheritance. The constructor of
the sub class first calls the constructor of the super class. Due to this, the creation
of sub class’s object starts with the initialization of the data members of the super
class. The constructor chaining works similarly with any number of classes. Every
constructor keeps calling the chain till the top of the chain.

Q16. Contiguous memory locations are usually used for storing actual values in an array
but not in ArrayList. Explain.

An array generally contains elements of the primitive data types such as int, float, etc. In
such cases, the array directly stores these elements at contiguous memory locations.
While an ArrayList does not contain primitive data types. An arrayList contains the
reference of the objects at different memory locations instead of the object itself. That is
why the objects are not stored at contiguous memory locations.

Q17. How is the creation of a String using new() different from that of a literal?

When we create a string using new(), a new object is created. Whereas, if we create a
string using the string literal syntax, it may return an already existing object with the
same name.

Q18. Why is synchronization necessary? Explain with the help of a relevant example.

Java allows multiple threads to execute. They may be accessing the same variable or
object. Synchronization helps to execute threads one after another.

It is important as it helps to execute all concurrent threads while being in sync. It


prevents memory consistency errors due to access to shared memory. An example of
synchronization code is-
20

1
public synchronized void increment()
2
{
3
a++;
4
}
As we have synchronized this function, this thread can only use the object after the
previous thread has used it.

Q19. Explain the term “Double Brace Initialization” in Java?

Double Brace Initialization is a Java term that refers to the combination of two
independent processes. There are two braces used in this. The first brace creates an
anonymous inner class. The second brace is an initialization block. When these both are
used together, it is known as Double Brace Initialization. The inner class has a reference
to the enclosing outer class, generally using the ‘this’ pointer. It is used to do both
creation and initialization in a single statement. It is generally used to initialize
collections. It reduces the code and also makes it more readable.

Q20. Why is it said that the length() method of String class doesn’t return accurate
results?

The length() method of String class doesn’t return accurate results because

it simply takes into account the number of characters within in the String. In other
words, code points outside of the BMP (Basic Multilingual Plane), that is, code points
having a value of U+10000 or above, will be ignored.

The reason for this is historical. One of Java’s original goals was to consider all text as
Unicode; yet, Unicode did not define code points outside of the BMP at the time. It was
too late to modify char by the time Unicode specified such code points.

Q21. What are the differences between Heap and Stack Memory in Java?
21

Q22. What is a package in Java? List down various advantages of packages.


Packages in Java, are the collection of related classes and interfaces which are bundled
together. By using packages, developers can easily modularize the code and optimize its
reuse. Also, the code within the packages can be imported by other classes and reused.
Below I have listed down a few of its advantages:

● Packages help in avoiding name clashes


● They provide easier access control on the code
● Packages can also contain hidden classes which are not visible to the outer classes
and only used within the package
● Creates a proper hierarchical structure which makes it easier to locate the related
classes

Q23. Why pointers are not used in Java?


Java doesn’t use pointers because they are unsafe and increases the complexity of the
program. Since, Java is known for its simplicity of code, adding the concept of pointers
will be contradicting. Moreover, since JVM is responsible for implicit memory allocation,
thus in order to avoid direct access to memory by the user, pointers are discouraged in
Java.

Q24. What is JIT compiler in Java?


22

JIT stands for Just-In-Time compiler in Java. It is a program that helps in converting the
Java bytecode into instructions that are sent directly to the processor. By default, the JIT
compiler is enabled in Java and is activated whenever a Java method is invoked. The JIT
compiler then compiles the bytecode of the invoked method into native machine code,
compiling it “just in time” to execute. Once the method has been compiled, the JVM
summons the compiled code of that method directly rather than interpreting it. This is
why it is often responsible for the performance optimization of Java applications at the
run time.

Q25. What are access modifiers in Java?


In Java, access modifiers are special keywords which are used to restrict the access of a
class, constructor, data member and method in another class. Java supports four types
of access modifiers:

1. Default
2. Private
3. Protected
4. Public

Q26. Define a Java Class.


23

A class in Java is a blueprint which includes all your data. A class contains fields
(variables) and methods to describe the behavior of an object. Let’s have a look at the
syntax of a class.

1
class Abc {
2
member variables // class body
3
methods}

Q27. What is an object in Java and how is it created?

An object is a real-world entity that has a state and behavior. An object has three
characteristics:

1. State
2. Behavior
3. Identity

An object is created using the ‘new’ keyword. For example:

ClassName obj = new ClassName();

Q28. What is Object Oriented Programming?

Object-oriented programming or popularly known as OOPs is a programming model or


approach where the programs are organized around objects rather than logic and
functions. In other words, OOP mainly focuses on the objects that are required to be
manipulated instead of logic. This approach is ideal for the programs large and complex
codes and needs to be actively updated or maintained.

Q29. What are the main concepts of OOPs in Java?


Object-Oriented Programming or OOPs is a programming style that is associated with
concepts like:

1. Inheritance: Inheritance is a process where one class acquires the properties of


another.
24

2. Encapsulation: Encapsulation in Java is a mechanism of wrapping up the data and


code together as a single unit.
3. Abstraction: Abstraction is the methodology of hiding the implementation details
from the user and only providing the functionality to the users.
4. Polymorphism: Polymorphism is the ability of a variable, function or object to
take multiple forms.

Q30. What is the difference between a local variable and an instance variable?
In Java, a local variable is typically used inside a method, constructor, or a block and has
only local scope. Thus, this variable can be used only within the scope of a block. The
best benefit of having a local variable is that other methods in the class won’t be even
aware of that variable.

Example
1
if(x > 100)
2
{
3
String test = "Edureka";
4
}
Whereas, an instance variable in Java, is a variable which is bounded to its object itself.
These variables are declared within a class, but outside a method. Every object of that
class will create it’s own copy of the variable while using it. Thus, any changes made to
the variable won’t reflect in any other instances of that class and will be bound to that
particular instance only.

1
class Test{
2
public String EmpName;
3
public int empAge;
4
}
Q31. Differentiate between the constructors and methods in Java?
25

In case you are facing any challenges with these Core Java interview questions, please
comment on your problems in the section below.

Q32. What is final keyword in Java?


final is a special keyword in Java that is used as a non-access modifier. A final variable
can be used in different contexts such as:

● final variable

When the final keyword is used with a variable then its value can’t be changed once
assigned. In case the no value has been assigned to the final variable then using only the
class constructor a value can be assigned to it.

● final method

When a method is declared final then it can’t be overridden by the inheriting class.

● final class

When a class is declared as final in Java, it can’t be extended by any subclass class but it
can extend other class.

Q33. What is the difference between break and continue statements?


26

Example break:
1
2 for (int i = 0; i < 5; i++)
3 {
4
5 if (i == 3)
6
{
7
8 break;

System.out.println(i);

}
Example continue:
1
2 for (int i = 0; i < 5; i++)
3 {
4
5 if(i == 2)
6
{
7
8 continue;

System.out.println(i);
27

}
Q34. What is an infinite loop in Java? Explain with an example.
An infinite loop is an instruction sequence in Java that loops endlessly when a
functional exit isn’t met. This type of loop can be the result of a programming
error or may also be a deliberate action based on the application behavior. An
infinite loop will terminate automatically once the application exits.

For example:

1 public class InfiniteForLoopDemo

2 {

3 public static void main(String[] arg) {

4 for(;;)

5 System.out.println("Welcome to Edureka!");

6 // To terminate this program press ctrl + c in the console.

7 }

8 }

Q35. What is the difference between this() and super() in Java?


In Java, super() and this(), both are special keywords that are used to call the
constructor.
28

Q36. What is Java String Pool?

Java String pool refers to a collection of Strings which are stored in heap
memory. In this, whenever a new object is created, String pool first checks
whether the object is already present in the pool or not. If it is present, then the
same reference is returned to the variable else new object will be created in the
String pool and the respective reference will be returned.

Q37. Differentiate between static and non-static methods in Java.


29

Q38. Explain the term “Double Brace Initialisation” in Java?


Double Brace Initialization is a Java term that refers to the combination of two
independent processes. There are two braces used in this. The first brace creates
an anonymous inner class. The second brace is an initialization block. When
these both are used together, it is known as Double Brace Initialisation. The
inner class has a reference to the enclosing outer class, genertally using the ‘this’
pointer. It is used to do both creation and initialization in a single statement. It is
generally used to initialize collections. It reduces the code and also makes it
more readable.

Q39. What is constructor chaining in Java?


In Java, constructor chaining is the process of calling one constructor from
another with respect to the current object. Constructor chaining is possible only
through legacy where a subclass constructor is responsible for invoking the
superclass’ constructor first. There could be any number of classes in the
constructor chain. Constructor chaining can be achieved in two ways:

1. Within the same class using this()


2. From base class using super()

Q40. Difference between String, StringBuilder, and StringBuffer.

Q41. What is a classloader in Java?


The Java ClassLoader is a subset of JVM (Java Virtual Machine) that is responsible
for loading the class files. Whenever a Java program is executed it is first loaded
by the classloader. Java provides three built-in classloaders:
30

1. Bootstrap ClassLoader
2. Extension ClassLoader
3. System/Application ClassLoader

Q42. Why Java Strings are immutable in nature?


In Java, string objects are immutable in nature which simply means once the
String object is created its state cannot be modified. Whenever you try to update
the value of that object instead of updating the values of that particular object,
Java creates a new string object. Java String objects are immutable as String
objects are generally cached in the String pool. Since String literals are usually
shared between multiple clients, action from one client might affect the rest. It
enhances security, caching, synchronization, and performance of the application.

Q43. What is the difference between an array and an array list?

Q44. What is a Map in Java?


In Java, Map is an interface of Util package which maps unique keys to values.
The Map interface is not a subset of the main Collection interface and thus it
behaves little different from the other collection types. Below are a few of the
characteristics of Map interface:

1. Map doesn’t contain duplicate keys.


31

2. Each key can map at max one value.

Q45. What is collection class in Java? List down its methods and interfaces.
In Java, the collection is a framework that acts as an architecture for storing and
manipulating a group of objects. Using Collections you can perform various tasks
like searching, sorting, insertion, manipulation, deletion, etc. Java collection
framework includes the following:

● Interfaces
● Classes
● Methods

The below image shows the complete hierarchy of the Java Collection.

Q1. What is Polymorphism?


32

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.

Q2. What is runtime 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.

1
2 class Car {
3 void run()
4
5 {
6
System.out.println(&ldquo;car is running&rdquo;);
7
8 }
9
10 }
11
class Audi extends Car {
12
13 void run()
14
15 {
16
System.out.prinltn(&ldquo;Audi is running safely with 100km&rdquo;);
17
33

public static void main(String args[])

Car b= new Audi(); //upcasting

b.run();

}
Q3. What is abstraction in Java?
Abstraction refers to the quality of dealing with ideas rather than events. It
basically deals with hiding the details and showing the essential things to the
user. Thus you can say that abstraction in Java is the process of hiding the
implementation details from the user and revealing only the functionality to
them. Abstraction can be achieved in two ways:

1. Abstract Classes (0-100% of abstraction can be achieved)


2. Interfaces (100% of abstraction can be achieved)

Q4. What do you mean by an interface in Java?


An interface in Java is a blueprint of a class or you can say it is a collection of
abstract methods and static constants. In an interface, each method is public and
abstract but it does not contain any constructor. Thus, interface basically is a
group of related methods with empty bodies. Example:

public interface Animal {


public void eat();
public void sleep();
public void run();
}
Q5. What is the difference between abstract classes and interfaces?
34

Q6. What is inheritance in Java?


Inheritance in Java is the concept where the properties of one class can be
inherited by the other. It helps to reuse the code and establish a relationship
between different classes. Inheritance is performed between two types of
classes:

1. Parent class (Super or Base class)


2. Child class (Subclass or Derived class)

A class which inherits the properties is known as Child Class whereas a class
whose properties are inherited is known as Parent class.

Q7. What are the different types of inheritance in Java?


Java supports four types of inheritance which are:

1. Single Inheritance: In single inheritance, one class inherits the properties


of another i.e there will be only one parent as well as one child class.
2. Multilevel Inheritance: When a class is derived from a class which is also
derived from another class, i.e. a class having more than one parent class
35

but at different levels, such type of inheritance is called Multilevel


Inheritance.
3. Hierarchical Inheritance: When a class has more than one child classes
(subclasses) or in other words, more than one child classes have the same
parent class, then such kind of inheritance is known as hierarchical.
4. Hybrid Inheritance: Hybrid inheritance is a combination of two or more
types of inheritance.

Q8. 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 a different number of parameters or
parameters having different types and order.
● Method Overloading is to “add” or “extend” more to the method’s
behavior.
● It is a compile-time polymorphism.
● The methods must have a 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.

1
2 class Adder {
3 Static int add(int a, int b)
4
5 {
6
return a+b;
7
8 }
9
10 Static double add( double a, double b)
11
{
12
13 return a+b;
14
}
36

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, the subclass has the same method with the same
name and exactly the same number and type of parameters and same
return type as a superclass.
● Method Overriding is to “Change” existing behavior of the method.
● It is a run time polymorphism.
● The methods must have the same signature.
● It always requires inheritance in Method Overriding.

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

1
2 class Car {
3 void run(){
4
5 System.out.println(&ldquo;car is running&rdquo;);
6
}
7
8 Class Audi extends Car{
9
10 void run()
11
{
12
13 System.out.prinltn("Audi is running safely with 100km");
14
15 }

public static void main( String args[])


37

Car b=new Audi();

b.run();

}
Q9. 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 the same return type and same method arguments in child class
then it will hide the superclass method; this is known as method hiding.
Similarly, you cannot override a private method in subclass 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.

1
2 class Base {
3 private static void display() {
4
5 System.out.println("Static or class method from Base");
6
}
7
8 public void print() {
9
10 System.out.println("Non-static or instance method from Base");
11
}
12
13 class Derived extends Base {
14
15 private static void display() {
16
System.out.println("Static or class method from Derived");
17
18 }
38

19
20 public void print() {
21 System.out.println("Non-static or instance method from Derived");
22
}

public class test {

public static void main(String args[])

Base obj= new Derived();

obj1.display();

obj1.print();

}
Q10. 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 the
same method name, then at runtime it becomes difficult for the compiler to
decide which method to execute from the child class.
39

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


referred to as Diamond Problem.

In case you are facing any challenges with these java interview questions, please
comment on your problems in the section below.

Q11. What is encapsulation in Java?


Encapsulation is a mechanism where you bind your data(variables) and
code(methods) together as a single unit. Here, the data is hidden from the outer
world and can be accessed only via current class methods. This helps in
protecting the data from any unnecessary modification. We can achieve
encapsulation in Java by:

● Declaring the variables of a class as private.


● Providing public setter and getter methods to modify and view the values
of the variables.

Q12. What is an association?


Association is a relationship where all object have their own lifecycle and there is
no owner. Let’s take the example of Teacher and Student. Multiple students can
associate with a single teacher and a single student can associate with multiple
teachers but there is no ownership between the objects and both have their
own lifecycle. These relationships can be one to one, one to many, many to one
and many to many.

Q13. What do you mean by aggregation?


An aggregation is a specialized form of Association where all object has their
own lifecycle but there is ownership and child object can not belong to another
parent object. Let’s take an example of Department and teacher. A single teacher
can not belong to multiple departments, but if we delete the department
teacher object will not destroy.

Q14. What is composition in Java?


Composition is again a specialized form of Aggregation and we can call this as a
“death” relationship. It is a strong type of Aggregation. Child object does not
have their lifecycle and if parent object deletes all child object will also be
40

deleted. Let’s take again an example of a 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 houses if we delete the house
room will automatically delete.

Q15. What is a marker interface?

A Marker interface can be defined as the interface having no data member and
member functions. In simpler terms, an empty interface is called the Marker
interface. The most common examples of Marker interface in Java are
Serializable, Cloneable etc. The marker interface can be declared as follows.

1
2 public interface Serializable{

}
Q16. What is object cloning in Java?

Object cloning in Java is the process of creating an exact copy of an object. It


basically means the ability to create an object with a similar state as the original
object. To achieve this, Java provides a method clone() to make use of this
functionality. This method creates a new instance of the class of the current
object and then initializes all its fields with the exact same contents of
corresponding fields. To object clone(), the marker interface java.lang.Cloneable
must be implemented to avoid any runtime exceptions. One thing you must note
is Object clone() is a protected method, thus you need to override it.

Q17. What is a copy constructor in Java?


Copy constructor is a member function that is used to initialize an object using
another object of the same class. Though there is no need for copy constructor
in Java since all objects are passed by reference. Moreover, Java does not even
support automatic pass-by-value.

Q18. What is a constructor overloading in Java?


In Java, constructor overloading is a technique of adding any number of
constructors to a class each having a different parameter list. The compiler uses
41

the number of parameters and their types in the list to differentiate the
overloaded constructors.

1
2 class Demo
3 {
4
5 int i;
6
public Demo(int a)
7
8 {
9
10 i=k;
11
}
12
public Demo(int a, int b)

//body

}
In case you are facing any challenges with these java interview questions, please
comment on your problems in the section below. Apart from this Java Interview
Questions Blog, if you want to get trained from professionals on this technology,
you can opt for a structured training from edureka!

Servlets – Java Interview Questions


Q1. What is a servlet?
● Java Servlet is server-side technologies to extend the capability of web
servers by providing support for dynamic response and data persistence.
● The javax.servlet and javax.servlet.http packages provide interfaces and
classes for writing our own servlets.
42

● All servlets must implement the javax.servlet.Servlet interface, which


defines servlet lifecycle methods. When implementing a generic service,
we can extend the GenericServlet class provided with the Java Servlet API.
The HttpServlet class provides methods, such as doGet() and doPost(), for
handling HTTP-specific services.

Q3. What is Request Dispatcher?


RequestDispatcher interface is used to forward the request to another resource
that can be HTML, JSP or another servlet in same application. We can also use
this to include the content of another resource to the response.

There are two methods defined in this interface:

1.void forward()

2.void include()

Q4. What are the differences between forward() method and sendRedirect()
methods?

forward() method SendRedirect() method

forward() sends the same request to sendRedirect() method sends new


another resource. request always because it uses the URL
bar of the browser.
43

forward() method works at server sendRedirect() method works at client


side. side.

forward() method works within the sendRedirect() method works within


server only. and outside the server.

Exception and Thread Java Interview Questions


Q1. What is the difference between Error and Exception?
An error is an irrecoverable condition occurring at runtime. Such as
OutOfMemory error. These JVM errors you cannot repair them at runtime.
Though error can be caught in the catch block but the execution of application
will come to a halt and is not recoverable.

While exceptions are conditions that occur because of bad input or human error
etc. e.g. FileNotFoundException will be thrown if the specified file does not exist.
Or a NullPointerException will take place if you try using a null reference. In most
of the cases it is possible to recover from an exception (probably by giving the
user feedback for entering proper values etc.

Q2. How can you handle Java exceptions?


There are five keywords used to handle exceptions in Java:

1. try
2. catch
3. finally
4. throw
5. throws

Q3. What are the differences between Checked Exception and Unchecked
Exception?
Checked Exception
● The classes that extend Throwable class except RuntimeException and
Error are known as checked exceptions.
● Checked exceptions are checked at compile-time.
44

● Example: IOException, SQLException etc.

Unchecked Exception
● The classes that extend RuntimeException are known as unchecked
exceptions.
● Unchecked exceptions are not checked at compile-time.
● Example: ArithmeticException, NullPointerException etc.

Q4. What are the different ways of thread usage?


There are two ways to create a thread:

● Extending Thread class

This creates a thread by creating an instance of a new class that extends the
Thread class. The extending class must override the run() function, which is the
thread’s entry point.

● Implementing Runnable interface

This is the easiest way to create a thread, by creating a class that implements the
runnable interface. After implementing the runnable interface, the class must
implement the public void run() method ()

The run() method creates a parallel thread in your programme. When run()
returns, the thread will come to an end.

The run() method creates a parallel thread in your programme. When run()
returns, the thread will come to an end.

Within the run() method, you must specify the thread’s code.

Like any other method, the run() method can call other methods, use other
classes, and define variables.

Java works as “pass by value” or “pass by reference” phenomenon?


45

Java is always pass-by-value. This means that it creates a copy of the contents of
the parameter in memory. In Java, object variables always refer to the memory
heap’s real object.

Q5. Will the finally block get executed when the return statement is written at
the end of try block and catch block as shown below?
The finally block always gets executed even hen the return statement is written
at the end of the try block and the catch block. It always executes , whether
there is an exception or not. There are only a few situations in which the finally
block does not execute, such as VM crash, power failure, software crash, etc. If
you don’t want to execute the finally block, you need to call the System.exit()
method explicitly in the finally block.

Q6. How does an exception propagate in the code?


If an exception is not caught, it is thrown from the top of the stack and falls
down the call stack to the previous procedure. If the exception isn’t caught
there, it falls back to the previous function, and so on, until it’s caught or the call
stack reaches the bottom. The term for this is Exception propagation.

Q7. Can you explain the Java thread lifecycle?


The java thread lifecycle has the following states-

New-

When a thread is created, and before the program starts the thread, it is in the
new state. It is also referred to as a born thread.

Runnable

When a thread is started, it is in the Runnable state. In this state, the thread is
executing its task.

Waiting
46

Sometimes, a thread goes to the waiting state, where it remains idle because
another thread is executing. When the other thread has finished, the waiting
thread again comes into the running state.

Timed Waiting

In timed waiting, the thread goes to waiting state. But, it remains in waiting state
for only a specified interval of time after which it starts executing.It remains
waiting either till the time interval ends or till the other thread has finished.

Terminated

A thread is said to be in this state once it terminates. It may be because the


thread has completed its task or due to any other reason.

Q8. What purpose do the keywords final, finally, and finalize fulfill?
Final:
Final is used to apply restrictions on class, method, and variable. A final class
can’t be inherited, final method can’t be overridden and final variable value
can’t be changed. Let’s take a look at the example below to understand it better.

1
2 class FinalVarExample {
3 public static void main( String args[])
4
5 {
6
final int a=10; // Final variable

a=50; //Error as value can't be changed

}
Finally
Finally is used to place important code, it will be executed whether the exception
is handled or not. Let’s take a look at the example below to understand it better.
47

1
2 class FinallyExample {
3 public static void main(String args[]){
4
5 try {
6
int x=100;
7
8 }
9
10 catch(Exception e) {
11
System.out.println(e);
12
}

finally {

System.out.println("finally block is executing");}

}}

}
Finalize
Finalize is used to perform clean up processing just before the object is garbage
collected. Let’s take a look at the example below to understand it better.

1
2 class FinalizeExample {
3 public void finalize() {
4
5 System.out.println("Finalize is called");
6
}
7
8 public static void main(String args[])
9
10 {
11
FinalizeExample f1=new FinalizeExample();
48

12
13 FinalizeExample f2=new FinalizeExample();

f1= NULL;

f2=NULL;

System.gc();

}
Q9. What are the differences between throw and throws?

In case you are facing any challenges with these java interview questions, please
comment on your problems in the section below.
Q10. What is exception hierarchy in java?
The hierarchy is as follows:

Throwable is a parent class of all Exception classes. There are two types of
Exceptions: Checked exceptions and UncheckedExceptions or
RunTimeExceptions. Both type of exceptions extends Exception class whereas
errors are further classified into Virtual Machine error and Assertion error.
49

Q11. How to create a custom Exception?


To create you own exception extend the Exception class or any of its subclasses.

● class New1Exception extends Exception { } // this will create


Checked Exception
● class NewException extends IOException { } // this will create
Checked exception
● class NewException extends NullPonterExcpetion { } // this will create
UnChecked exception

Q12. What are the important methods of Java Exception Class?


Exception and all of it’s subclasses doesn’t provide any specific methods and all
of the methods are defined in the base class Throwable.

1. String getMessage() – This method returns the message String of


Throwable and the message can be provided while creating the exception
through it’s constructor.
2. String getLocalizedMessage() – This method is provided so that subclasses
can override it to provide locale specific message to the calling program.
Throwable class implementation of this method simply use getMessage()
method to return the exception message.
50

3. Synchronized Throwable getCause() – This method returns the cause of


the exception or null id the cause is unknown.
4. String toString() – This method returns the information about Throwable
in String format, the returned String contains the name of Throwable class
and localized message.
5. void printStackTrace() – This method prints the stack trace information to
the standard error stream, this method is overloaded and we can pass
PrintStream or PrintWriter as an argument to write the stack trace
information to the file or stream.

Q13. What are the differences between processes and threads?

Q14. What is a finally block? Is there a case when finally will not execute?
Finally block is a block which always executes a set of statements. It is always
associated with a try block regardless of any exception that occurs or not.

Yes, finally will not be executed if the program exits either by calling
System.exit() or by causing a fatal error that causes the process to abort.

Q15. What is synchronization?


Synchronization refers to multi-threading. A synchronized block of code can be
executed by only one thread at a time. As Java supports execution of multiple
threads, two or more threads may access the same fields or objects.
Synchronization is a process which keeps all concurrent threads in execution to
51

be in sync. Synchronization avoids memory consistency errors caused due to


inconsistent view of shared memory. When a method is declared as
synchronized the thread holds the monitor for that method’s object. If another
thread is executing the synchronized method the thread is blocked until that
thread releases the monitor.

Q16. Can we write multiple catch blocks under single try block?
Yes we can have multiple catch blocks under single try block but the approach
should be from specific to general. Let’s understand this with a programmatic
example.

1
2 public class Example {
3 public static void main(String args[]) {
4
5 try {
6
int a[]= new int[10];
7
8 a[10]= 10/0;
9
10 }
11
catch(ArithmeticException e)
12
13 {
14
15 System.out.println("Arithmetic exception in first catch block");
52

16
17 }
18 catch(ArrayIndexOutOfBoundsException e)
19
{

System.out.println("Array index out of bounds in second catch block");

catch(Exception e)

System.out.println("Any exception in third catch block");

}
Q17. What are the important methods of Java Exception Class?
Methods are defined in the base class Throwable. Some of the important
methods of Java exception class are stated below.

1. String getMessage() – This method returns the message String about the
exception. The message can be provided through its constructor.
2. public StackTraceElement[] getStackTrace() – This method returns an
array containing each element on the stack trace. The element at index 0
represents the top of the call stack whereas the last element in the array
represents the method at the bottom of the call stack.
3. Synchronized Throwable getCause() – This method returns the cause of
the exception or null id as represented by a Throwable object.
4. String toString() – This method returns the information in String format.
The returned String contains the name of Throwable class and localized
message.
5. void printStackTrace() – This method prints the stack trace information to
the standard error stream.

Q18. What is OutOfMemoryError in Java?


53

OutOfMemoryError is the subclass of java.lang.Error which generally occurs


when our JVM runs out of memory.

Q19. What is a Thread?


A thread is the smallest piece of programmed instructions which can be
executed independently by a scheduler. In Java, all the programs will have at
least one thread which is known as the main thread. This main thread is created
by the JVM when the program starts its execution. The main thread is used to
invoke the main() of the program.

Q20. What are the two ways to create a thread?


In Java, threads can be created in the following two ways:-

● By implementing the Runnable interface.


● By extending the Thread

Q21. What are the different types of garbage collectors in Java?


Garbage collection in Java a program which helps in implicit memory
management. Since in Java, using the new keyword you can create objects
dynamically, which once created will consume some memory. Once the job is
done and there are no more references left to the object, Java using garbage
collection destroys the object and relieves the memory occupied by it. Java
provides four types of garbage collectors:

● Serial Garbage Collector


● Parallel Garbage Collector
● CMS Garbage Collector
● G1 Garbage Collector
54

2. List the features of the Java Programming language?

A few of the significant features of Java Programming Language are:

Easy: Java is a language that is considered easy to learn. One fundamental


concept of OOP Java has a catch to understand.

Secured Feature: Java has a secured feature that helps develop a virus-free and
tamper-free system for the users.

OOP: OOP stands for Object-Oriented Programming language. OOP signifies that,
in Java, everything is considered an object.

Independent Platform: Java is not compiled into a platform-specific machine;


instead, it is compiled into platform-independent bytecode. This code is
interpreted by the Virtual Machine on which the platform runs.

17. Define Wrapper Classes in Java.

In Java, when you declare primitive datatypes, then Wrapper classes are
responsible for converting them into objects(Reference types).

18. What is a singleton class in Java? And How to implement a singleton class?

A class that can possess only one object at a time is called a singleton class. To
implement a singleton class given steps are to be followed:

1. Make sure that the class has only one object


2. Give global access to that object

19. Define package in Java.


55

The package is a collective bundle of classes and interfaces and the necessary
libraries and JAR files. The use of packages helps in code reusability.

20. Can you implement pointers in a Java Program?

Java Virtual Machine takes care of memory management implicitly. Java's


primary motto was to keep programming simple. So, accessing memory directly
through pointers is not a recommended action. Hence, pointers are eliminated in
Java.

21. Differentiate between instance and local variables.

For instance, variables are declared inside a class, and the scope of variables in
javascript is limited to only a specific object.

A local variable can be anywhere inside a method or a specific block of code.


Also, the scope is limited to the code segment where the variable is declared.

22. Explain Java String Pool.

A collection of strings in Java's Heap memory is referred to as Java String Pool. In


case you try to create a new string object, JVM first checks for the presence of
the object in the pool. If available, the same object reference is shared with the
variable, else a new object is created.

23. What is an Exception?

An Exception handling in Java is considered an unexpected event that can disrupt


the program's normal flow. These events can be fixed through the process of
Exception Handling.

24. What is the final keyword in Java?


56

The term final is a predefined word in Java that is used while declaring values to
variables. When a value is declared using the final keyword, then the variable's
value remains constant throughout the program's execution.

25. What happens when the main() isn't declared as static?

When the main method is not declared as static, then the program may be
compiled correctly but ends up with a severe ambiguity and throws a run time
error that reads "NoSuchMethodError."

26. Why is Java a platform independent language?

One of the most well-known and widely used programming languages is Java. It
is a programming language that is independent of platforms. Java doesn't
demand that the complete programme be rewritten for every possible platform.
The Java Virtual Machine and Java Bytecode are used to support platform
independence. Any JVM operating system can run this platform-neutral byte
code. The application is run after JVM translates the byte code into machine
code. Because Java programmes can operate on numerous systems without
having to be individually rewritten for each platform, the language is referred to
as "Write Once, Run Anywhere" (WORA).

27. Why is the main method static in Java?

Java's main() function is static by default, allowing the compiler to call it either
before or after creating a class object. The main () function is where the compiler
begins programme execution in every Java programme. Thus, the main ()
method needs to be called by the compiler. If the main () method is permitted to
be non-static, the JVM must instantiate its class when calling the function.

28. What part of memory - Stack or Heap - is cleaned in the garbage collection
process?
57

On Heap memory, garbage collection is employed to release the memory used


by objects with no references. Every object created in the Heap space has access
to the entire application and may be referred to from anywhere.

29. What is the difference between the program and the process?

A programme is a non-active entity that includes the collection of codes


necessary to carry out a specific operation. When a programme is run, an active
instance of the programme called a process is launched. A process is begun by a
programme once it has been run. The process carries out the program's
specified instructions.

30. What are the differences between constructor and method of a class in Java?

Initializing the state of the object is done by constructors. A function Object () {


[native code] }, like methods, contains a group of statements (or instructions)
that are carried out when an object is created. A method is a group of
statements that work together to complete a certain task and return the
outcome to the caller. A method has the option of working without returning
anything.

31. Which among String or String Buffer should be preferred when there are a
lot of updates required to be done in the data?

Because StringBuilder is quicker than StringBuffer, it is advised to utilize it


wherever possible. However, StringBuffer objects are the best choice if thread
safety is required.

32. What happens if the static modifier is not included in the main method
signature in Java?

The main function is called by the JVM even before the objects are created, thus
even if the code correctly compiles, there will still be an error at runtime.
58

33. Can we make the main() thread a daemon thread?

This technique designates whether the active thread is a user thread or a


daemon thread. For instance, tU.setDaemon(true) would convert a user thread
named tU into a daemon thread. On the other side, executing
tD.setDaemon(false) would convert a Daemon thread, tD, into a user thread.

34. What happens if there are multiple main methods inside one class in Java?

There is no limit to the number of major approaches you can use. Overloading is
the ability to have main methods with different signatures than main (String []),
and the JVM will disregard those main methods.

35. How does an exception propagate in the code?

In the event that an exception is not caught, it is initially thrown from the top of
the stack and then moves down the call stack to the preceding method. The
runtime system looks for a way to handle an exception that a method throws.
The ordered list of methods that were called to get to the method where the
error occurred is the collection of potential "somethings" that can be used to
manage the exception. The call stack is the list of methods, and exception
propagation is the search technique.

36. How do exceptions affect the program if it doesn't handle them?

If you don't deal with an exception once it occurs, the programme will end
abruptly and the code after the line where the exception occurred won't run.

37. Is it mandatory for a catch block to be followed after a try block?

Each attempt block does not necessarily have to be followed by a catch block.
Either a catch block or a final block ought to come after it. Additionally, any
59

exceptions that are expected to be thrown should be mentioned in the method's


throws clause.

38. Can you call a constructor of a class inside another constructor?

Yes, a class may include any number of constructors, and each function Object ()
{[native code] } may call the others using the this() function Object() { [native
code] } call function [please do not mix the this() function Object() { [native
code] } call function with this keyword]. The constructor's first line should be
either this () or this(args). Overloading of constructors is what this is called.

39. Contiguous memory locations are usually used for storing actual values in an
array but not in ArrayList. Explain.

Primitive data types like int, float, and others are typically present in an array. In
such circumstances, the array immediately saves these elements at contiguous
memory regions. While an ArrayList does not contain primitive data types.
Instead of the actual object, an ArrayList includes the references to the objects'
many locations in memory. The objects are not kept in consecutive memory
regions because of this.

40. Why does the java array index start with 0?

The distance from the array's beginning is just an offset. There is no distance
because the first element is at the beginning of the array. Consequently, the
offset is 0.

41. Why is the remove method faster in the linked list than in an array?

Because there is no background scaling of an array, insertion, addition, and


removal operations are quicker with a LinkedList. Only references in adjacent
items need to update when a new item is added in the middle of the list.
60

42. How many overloaded add() and addAll() methods are available in the List
interface? Describe the need and uses.

List is an interface in the Java Collections Framework. The add() and addAll()
methods are the main methods at the List interface. The add() method is used
to add an element to the list, while the addAll() method is used to add a
collection of elements to the list.

The List interface contains two overloaded versions of the add() method:

The first add() method accepts a single argument of type E, the element to be
added to the list.

The second add() method accepts a variable number of arguments of type E,


which are the elements to be added to the list.

The List interface also contains two overloaded versions of the addAll() method:

The first addAll() method accepts a single argument of type Collection<? Extends
E>, which is the collection of elements to be added to the list.

The second addAll() method accepts a variable number of arguments of type E,


which are the elements to be added to the list.

43. How does the size of ArrayList grow dynamically? And also state how it is
implemented internally?

A resizable array implementation in Java is called ArrayList. Dynamically


expanding array lists make it possible to add new elements at any time. The
underlying data structure of the ArrayList is an array of the Object class. The
ArrayList class in Java has three constructors. There are available readObject and
writeObject methods specific to it. The Object Array in an ArrayList is temporary.
61

There are implemented and Serialization-capable versions of RandomAccess,


Cloneable, and java.io (that are Marker Interface in Java).

44. Although inheritance is a popular OOPs concept, it is less advantageous than


composition. Explain.

A class's testability is improved through composition over inheritance. If a class is


comprised of another class, it is simple to create a mock object to simulate the
combined class for testing purposes. This privilege is not given by inheritance.
Even while Composition and Inheritance both let you reuse code, Inheritance
has the drawback of breaking encapsulation. If the function of the subclass
depends on the superclass's action, it suddenly becomes vulnerable. Sub-class
functionality may be broken without any alteration on the part of the super-class
when its behaviour changes.

45. What are Composition and Aggregation? State the difference.

Aggregation (HAS-A) and composition are its two forms (Belongs-to). In contrast
to composition, which has a significant correlation, the aggregation has a very
modest association. Aggregation can be thought of as a more confined version of
the composition. Since all compositions are aggregates but not all aggregates are
compositions, aggregate can be thought of as the superset of composition.

46. How is the creation of a String using new() different from that of a literal?

The new () operator always produces a new object in heap memory when
creating a String object. The String pool may return an existing object if we build
an object using the String literal syntax, such as "Baeldung," on the other hand.

47. How is the ‘new' operator different from the ‘newInstance()' operator in
java?

Both the new operator and the newInstance() method are used to create objects
in Java. If we already know the kind of object to create, we can use the new
62

operator; however, if the type of object to create is supplied to us at runtime, we


must use the newInstance() function.

48. Is exceeding the memory limit possible in a program despite having a


garbage collector?

Yes, even with a garbage collector in place, the programme could still run out of
memory. Garbage collection aids in identifying and removing programme objects
that are no longer needed in order to release the resources they use. When an
object in a programme cannot be reached, trash collection is executed with
respect to that object. If there is not enough memory available to create new
objects, a garbage collector is used to free up memory for things that have been
removed from the scope. When the amount of memory released is insufficient
for the creation of new objects, the program's memory limit is exceeded.

49. Why is synchronization necessary? Explain with the help of a relevant


example.

Multiple threads trying to access the same resources in a multi-threaded


software may frequently result in unexpected and incorrect outcomes.
Therefore, it must be ensured through some form of synchronization that only
one thread can access the resource at any given time. Java offers a method for
setting up threads and synchronizing their operations with the aid of
synchronized blocks. The synchronized keyword in Java is used to identify
synchronized blocks. In Java, a synchronized block is one that is tied to an object.
Only one thread can be running at a time inside synchronized blocks since they
are all synchronized on the same object. Until the thread inside the synchronized
block exits the block, all other threads trying to enter the block are blocked.

50. Define System.out.println().


63

System.out.println() in Java outputs the argument that was supplied to it. On the
monitor, the println() method displays the findings. An objectname is typically
used to call a method.

51. Can you explain the Java thread lifecycle?

A thread can be in any of the following states in Java. These are the states:

● New: A new thread is always in the new state when it is first formed.
The function hasn't been run yet, thus it hasn't started to execute for a
thread in the new state.
● Active: A thread switches from the new state to the active state when
it calls the start() method. The runnable state and the running state are
both contained within the active state.
● Blocked or Waiting: A thread is either in the blocked state or the
waiting state when it is inactive for a while (but not indefinitely).
● Timed waiting: When we use the sleep () method on a particular
thread, we are actually engaging in timed waiting. The thread enters
the timed wait state using the sleep () function. The thread awakens
when the allotted time has passed and resumes execution where it left
off.
● Termination: A thread that has been terminated means it is no longer
active in the system. In other words, the thread is inactive and cannot
be revived (made active again after being killed).

52. What could be the tradeoff between the usage of an unordered array versus
the usage of an ordered array?

When opposed to an unordered array, which has a time complexity of O, an


ordered array's search times have a time complexity of O(log n) (n). Due to the
need to shift the elements with higher values to create room for the new
member, an ordered array has a temporal complexity of O(n) during the
64

insertion process. Instead, an unordered array's insertion operation requires a


constant O amount of time (1).

53. Is it possible to import the same class or package twice in Java and what
happens to it during runtime?

The same package or class may be imported more than once. Neither the JVM
nor the compiler raise an objection. Even if you import the same class several
times, the JVM will only internally load it once.

54. In case a package has sub packages, will it suffice to import only the main
package? e.g. Does importing of com.myMainPackage.* also import
com.myMainPackage.mySubPackage.*?

Sub-packages won't be imported when a package is imported. When you import


a package, all of its classes and interfaces—with the exception of those from its
sub-packages—are imported.

55. Will the final block be executed if the code System.exit(0) is written at the
end of the try block?

The system is established as the last line to be run, after which nothing will
happen, therefore both the catch and finally blocks are essentially ignored.

56. Explain the term “Double Brace Initialisation” in Java?

The outer braces of the double-brace initialization construct an anonymous class


that is descended from the provided class and gives an initializer block for that
class (the inner braces).

57. Why is it said that the length() method of String class doesn't return accurate
results?
65

Since this char [] array is used by the Java String class internally, the length
variable cannot be made public.

58. What are the possible ways of making objects eligible for garbage collection
(GC) in Java?

If a reference variable for an object is removed from the programme while it is


running, the object may be trash collected. They are also referred to as
inaccessible objects occasionally. The new operator returns a reference to an
object after dynamically allocating memory for it.

59. In the below Java Program, how many objects are eligible for garbage
collection?

I don't know about the program, but generally, three objects are eligible for
garbage collection.

The first object is created when the program is started and is no longer needed
when the program ends.

The second object is created when the user inputs their name and is no longer
required when the program ends.

The third object is created when the user inputs their address and is no longer
needed when the program ends.

60. What is the best way to inject dependency? Also, state the reason.

Constructor injection. A class requesting its dependencies through its function


Object() { [native code] } is the most typical instance of dependency injection.
Since the client cannot be constructed without the required dependencies, this
guarantees that it is always in a correct state.
66

61. How we can set the spring bean scope. And what supported scopes does it
have?

There are four ways to set the scope of a Spring bean: singleton, prototype,
request, and session.

The singleton scope creates a single instance of a bean, which is shared by all
objects that request it.

The prototype scope creates a new instance of a bean for each object that
requests it.

The request and session scopes are only available in a web-based context. The
request scope creates a new bean instance for each HTTP request, and the
session scope creates a single instance of a bean shared by all objects in a single
HTTP session.

62. What are the different categories of Java Design patterns?

The three categories of Java design patterns are creational, structural, and
behavioural design patterns.

63. What is a Memory Leak? Discuss some common causes of it.

A memory leak is the slow degradation of system performance over time


brought on by the fragmentation of a computer's RAM as a result of shoddy
application design or programming that fails to release memory chunks when
they are no longer required. These memory leaks frequently result from session
items in excess, insertion into Collection objects without deletion, infinite
caches, excessive page switching on the operating system, listener methods that
are not called, and bespoke data structures that are poorly written.
67

64. Assume a thread has a lock on it, calling the sleep() method on that thread
will release the lock?

No, the thread might release the locks using notify, notifyAll(), and wait()
methods.

65. Write a Java Program to print Fibonacci Series using Recursion.

class FibonacciExample2{

static int n1=0,n2=1,n3=0;

static void printFibonacci(int count){

if(count>0){

n3 = n1 + n2;

n1 = n2;

n2 = n3;

System.out.print(" "+n3);

printFibonacci(count-1);

public static void main(String args[]){


68

int count=10;

System.out.print(n1+" "+n2);//printing 0 and 1

printFibonacci(count-2);//n-2 because 2 numbers are already printed

66. Write a Java program to check if the two strings are anagrams.

import java.util.Arrays;

public class AnagramString {

static void isAnagram(String str1, String str2) {

String s1 = str1.replaceAll("\\s", "");

String s2 = str2.replaceAll("\\s", "");

boolean status = true;

if (s1.length() != s2.length()) {

status = false;

} else {

char[] ArrayS1 = s1.toLowerCase().toCharArray();


69

char[] ArrayS2 = s2.toLowerCase().toCharArray();

Arrays.sort(ArrayS1);

Arrays.sort(ArrayS2);

status = Arrays.equals(ArrayS1, ArrayS2);

if (status) {

System.out.println(s1 + " and " + s2 + " are anagrams");

} else {

System.out.println(s1 + " and " + s2 + " are not anagrams");

public static void main(String[] args) {

isAnagram("Keep", "Peek");

isAnagram("Mother In Law", "Hitler Woman");

}
70

Output

Keep and Peek are anagrams

MotherInLaw and HitlerWoman are anagrams

67. Write a Java Program to find the factorial of a given number.

4! = 4*3*2*1 = 24

5! = 5*4*3*2*1 = 120

68. Given an array of non-duplicating numbers from 1 to n where one number is


missing, write an efficient java program to find that missing number.

Input: arr[] = {1, 2, 4, 6, 3, 7, 8}, N = 8

Output: 5

Explanation: The missing number between 1 to 8 is 5

69. Write a Java Program to check if any number is a magic number or not. A
number is said to be a magic number if after doing the sum of digits in each step
and in turn doing the sum of digits of that sum, the ultimate result (when there
is only one digit left) is 1.

// Java program to check if

// a number is Magic number.

class GFG
71

public static boolean isMagic(int n)

int sum = 0;

// Note that the loop continues

// if n is 0 and sum is non-zero.

// It stops when n becomes 0 and

// sum becomes single digit.

while (n > 0 || sum > 9)

if (n == 0)

n = sum;

sum = 0;

sum += n % 10;
72

n /= 10;

// Return true if sum becomes 1.

return (sum == 1);

// Driver code

public static void main(String args[])

int n = 1234;

if (isMagic(n))

System.out.println("Magic Number");

else

System.out.println("Not a magic Number");

}
73

class InvalidAgeException extends Exception

public InvalidAgeException (String str)

// calling the constructor of parent Exception

super(str);

70. Write a Java program to create and throw custom exceptions.

// class that uses custom exception InvalidAgeException

public class TestCustomException1

// method to check the age

static void validate (int age) throws InvalidAgeException{

if(age < 18){


74

// throw an object of user defined exception

throw new InvalidAgeException("age is not valid to vote");

else {

System.out.println("welcome to vote");

// main method

public static void main(String args[])

try

// calling the method

validate(13);

catch (InvalidAgeException ex)


75

System.out.println("Caught the exception");

// printing the message from InvalidAgeException object

System.out.println("Exception occured: " + ex);

System.out.println("rest of the code...");

71. Write a Java program to rotate arrays 90 degree clockwise by taking matrices
from user input.

public class RotateMatrixClockwise

public static void main(String args[])

//matrix to rotate

int a[][]= {{1,2,3},{4,5,6},{7,8,9}};


76

System.out.println("Original Matrix: \n");

//loop for rows

for(int i=0;i<3;i++)

//loop for columns

for(int j=0;j<3;j++)

//prints the elements of the original matrix

System.out.print(" "+a[i][j]+"\t");

System.out.println("\n");

System.out.println("Rotate Matrix by 90 Degrees Clockwise: \n");

for(int i=0;i<3;i++)

for(int j=2;j>=0;j--)
77

//prints the elements of the rotated matrix

System.out.print(""+a[j][i]+"\t");

System.out.println("\n");

72. Write a java program to check if any number given as input is the sum of 2
prime numbers.

// C program to check if a prime number

// can be expressed as sum of

// two Prime Numbers

#include <stdio.h>

#include <math.h>

#include <stdbool.h>

// Function to check whether a number


78

// is prime or not

bool isPrime(int n)

if (n <= 1)

return false;

for (int i = 2; i <= sqrt(n); i++)

if (n % i == 0)

return false;

return true;

// Function to check if a prime number

// can be expressed as sum of

// two Prime Numbers

bool isPossible(int N)
79

// if the number is prime,

// and number-2 is also prime

if (isPrime(N) && isPrime(N - 2))

return true;

else

return false;

// Driver code

int main()

int n = 13;

if (isPossible(n))

printf("%s", "Yes");

else
80

printf("%s", "No");

return 0;

73. Write a Java program for solving the Tower of Hanoi Problem.

// Java recursive program to solve tower of hanoi puzzle

class GFG

// Java recursive function to solve tower of hanoi puzzle

static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)

if (n == 1)

System.out.println("Move disk 1 from rod " +


from_rod + " to rod " +to_rod);

return;

}
81

towerOfHanoi(n-1, from_rod, aux_rod, to_rod);

System.out.println("Move disk " + n + " from rod " + from_rod + "


to rod " +to_rod);

towerOfHanoi(n-1, aux_rod, to_rod, from_rod);

// Driver method

public static void main(String args[])

int n = 4; // Number of disks

towerOfHanoi(n, \'A\', \'C\', \'B\'); // A, B and C are names of rods

74. Implement Binary Search in Java using recursion.

// Java Program to Illustrate Recursive Binary Search

// Importing required classes

import java.util.*;

// Main class
82

class GFG {

// Method 1

// Recursive binary search

// Returns index of x if it is present

// in arr[l..r], else return -1

int binarySearch(int arr[], int l, int r, int x)

// Restrict the boundary of right index

// and the left index to prevent

// overflow of indices

if (r >= l && l <= arr.length - 1) {

int mid = l + (r - l) / 2;

// If the element is present

// at the middle itself

if (arr[mid] == x)

return mid;
83

// If element is smaller than mid, then it can

// only be present in left subarray

if (arr[mid] > x)

return binarySearch(arr, l, mid - 1, x);

// Else the element can only be present

// in right subarray

return binarySearch(arr, mid + 1, r, x);

// We reach here when element is not present in

// array

return -1;

// Method 2

// Main driver method

public static void main(String args[])


84

// Creating object of above class

GFG ob = new GFG();

// Custom input array

int arr[] = { 2, 3, 4, 10, 40 };

// Length of array

int n = arr.length;

// Custom element to be checked

// whether present or not

int x = 10;

// Calling above method

int result = ob.binarySearch(arr, 0, n - 1, x);

// Element present

if (result == -1)

// Print statement
85

System.out.println("Element not present");

// Element not present

else

// Print statement

System.out.println("Element found at index "

+ result);

75. Is delete, next, main, exit or null keyword in java?

No, these keywords do not exist in Java. Delete, Next, Exit are the operations
performed in the Java program, Main is the predefined method, and Null is the
default String type.

With this we are done with the first section that is Basic Java Interview Question,
Now, lets move on to our next section of Intermediate Java Interview Questions.

Java Interview Coding Questions For Intermediate

Now, let's have a look at some of the most asked Java technical interview
questions for intermediate experienced professionals.
86

76. What is JDK? Mention the variants of JDK?

JDK is an abbreviation for Java Development Kit. It is a combined Package of JRE


and Developer tools used for designing Java Applications and Applets. Oracle has
the following variants.

● JDK Standard Edition


● JDK Enterprise Edition
● JDK Micro Edition

77. What is the difference between JDK, JRE, and JVM?

JVM has a Just in Time (JIT) compiler tool that converts all the Java source code
into the low-level compatible machine language. Therefore, it runs faster than
the regular application.

JRE has class libraries and other JVM supporting files. But it doesn’t have any
tool for java development such as compiler or debugger.

JDK has tools that are required to write Java Programs and uses JRE to execute
them. It has a compiler, Java application launcher, and an applet viewer.

78. What is a JIT compiler?

JIT compiler refers to Just in Time compiler. It is the simplest way of executing
the computer code that takes in compilation during the execution of a program
rather than before performance. It commonly uses bytecode translation to
machine code. It is then executed directly.

79. What are Brief Access Specifiers and Types of Access Specifiers?

Access Specifiers are predefined keywords used to help JVM understand the
scope of a variable, method, and class. We have four access specifiers.
87

● Public Access Specifier


● Private Access Specifier
● Protected Access Specifier
● Default Access Specifier

80. How many types of constructors are used in Java?

There are two types of constructors in Java.

Parameterized Constructors: Parameterized constructor accepts the parameters


with which users can initialize the instance variables. Users can initialize the class
variables dynamically at the time of instantiating the class.

Default constructors: This type doesn’t accept any parameters; rather, it


instantiates the class variables with their default values. It is used mainly for
object creation.

81. Can a constructor return a value?

Yes, A constructor can return a value. It replaces the class's current instance
implicitly; you cannot make a constructor return a value explicitly.

82. Explain ‘this’ keyword in Java.

The term "this" is a particular keyword designated as a reference keyword. The


"this" keyword is used to refer to the current class properties like method,
instance, variable, and constructors.

83. Explain ‘super’ keyword in Java.

The term "super" is a particular keyword designated as a reference keyword. The


"super" keyword refers to the immediate parent class object.
88

84. Explain Method Overloading in Java.

The process of creating multiple method signatures using one method name is
called Method Overloading in Java. Two ways to achieve method overloading
are:

1. Varying the number of arguments


2. Changing the return type of the Method

85. Can we overload a static method?

No, Java does not support the Overloading of a static method. The process
would throw an error reading "static method cannot be referenced."

86. Define Late Binding.

Binding is a process of unifying the method call with the method's code
segment. Late binding happens when the method's code segment is unknown
until it is called during the runtime.

87. Define Dynamic Method Dispatch.

The Dynamic method dispatch is a process where the method call is executed
during the runtime. A reference variable is used to call the super-class. This
process is also known as Run-Time Polymorphism.

88. Why is the delete function faster in the linked list than an array?

Delete Function is faster in linked lists in Java as the user needs to make a minor
update to the pointer value so that the node can point to the next successor in
the list
89

89. Give a briefing on the life cycle of a thread.

The life cycle of a thread includes five stages, as mentioned below.

1. New Born State


2. Runnable State
3. Running State
4. Blocked State
5. Dead State

90. Explain the difference between >> and >>> operators.

Although they look similar, there is a massive difference between both.

● >> operator does the job of right shifting the sign bits
● >>> operator is used in shifting out the zero-filled bits

91. Brief the life cycle of an applet.

The life cycle of an applet involves the following.

1. Initialization
2. Start
3. Stop
4. Destroy
5. Paint

92. Why are generics used in Java Programming?

Compile-time type safety is provided by using generics. Compile-time type safety


allows users to catch unnecessary invalid types at compile time. Generic
methods and classes help programmers specify a single method declaration, a
set of related methods, or related types with an available class declaration.
90

93. Explain the Externalizable interface.

The Externalizable interface helps with control over the process of serialization.
An "externalisable" interface incorporates readExternal and writeExternal
methods.

94. What is the Daemon Thread?

The Daemon thread can be defined as a thread with the least priority. This
Daemon thread is designed to run in the background during the Garbage
Collection in Java.

The setDaemon() method creates a Daemon thread in Java.

95. Explain the term enumeration in Java.

Enumeration or enum is an interface in Java. Enum allows the sequential access


of the elements stored in a collection in Java.

96. Why is Java is Dynamic?

Java is designed to adapt to an evolving environment. Java programs include a


large amount of runtime information that is used to resolve access to objects in
real-time.

97. Can you run a code before executing the main method?

Yes, we can execute any code, even before the main method. We will be using a
static block of code when creating the objects at the class's load time. Any
statements within this static block of code will get executed at once while
loading the class, even before creating objects in the main method.
91

98. How many times is the finalize method called?

The finalize method is called the Garbage collector. For every object, the
Garbage Collector calls the finalize() method just for one time.

Java Interview Questions for Experienced

Now, lets move on to our last section of Advanced Core Java Interview Questions
which is primarly useful for experienced and working professionals.

99. Can "this" and "super" keywords be used together?

No, "this" and "super" keywords should be used in the first statement in the
class constructor. The following code gives you a brief idea.

public class baseClass {

baseClass() {

super();

this();

System.out.println(" baseClass object is created");

public static void main(String []args){

baseClass bclass = new baseClass();


92

100. What is a JSP page?

JSP is an abbreviation for Java Servlet Page. The JSP page consists of two types of
text.

● Static Data
● JSP elements

101. What is JDBC?

JDBC is an abbreviation for Java Database Connector.

JDBC is an abstraction layer used to establish connectivity between an existing


database and a Java application

102. Explain the various directives in JSP.

Directives are instructions processed by JSP Engine. After the JSP page is
compiled into a Servlet, Directives set page-level instructions, insert external
files, and define customized tag libraries. Directives are defined using the
symbols below:

start with "< %@" and then end with "% >"

The various types of directives are shown below:

● Include directive
93

It includes a file and combines the content of the whole file with the currently
active pages.

● Page directive

Page Directive defines specific attributes in the JSP page, like the buffer and
error page.

● Taglib

Taglib declares a custom tag library, which is used on the page.

103. What are the observer and observable classes?

Objects that inherit the "Observable class" take care of a list of "observers."

When an Observable object gets upgraded, it calls the update() method of each
of its observers.

After that, it notifies all the observers that there is a change of state.

The Observer interface gets implemented by objects that observe Observable


objects.

Q1) 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.
94

Q3) What’s the purpose of Static methods and static variables?


Ans: When there is a requirement to share a method or a variable between multiple
objects of a class instead of creating separate copies for each object, we use static
keyword to make a method or variable shared for all objects.

Q4) What is data encapsulation and what’s its significance?


Ans: Encapsulation is a concept in Object Oriented Programming for combining
properties and methods in a single unit.
Encapsulation helps programmers to follow a modular approach for software
development as each object has its own set of methods and variables and serves its
functions independent of other objects. Encapsulation also serves data hiding purpose.
Q5) What is a singleton class? Give a practical example of its usage.
A singleton class in java can have only one instance and hence all its methods and
variables belong to just one instance. Singleton class concept is useful for the situations
when there is a need to limit the number of objects for a class.
The best example of singleton usage scenario is when there is a limit of having only one
connection to a database due to some driver limitations or because of any licensing
issues.

Q6) 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.
95

Q7: What is an infinite Loop? How infinite loop is declared?


Ans: An infinite loop runs without any condition and runs infinitely. An infinite loop can
be broken by defining any breaking logic in the body of the statement blocks.
Infinite loop is declared as follows:
for (;;)
{
// Statements to execute

// Add any loop breaking logic


}

Q8) What is the difference between continue and break statement?


Ans: break and continue are two important keywords used in Loops. When a break
keyword is used in a loop, loop is broken instantly while when continue keyword is used,
current iteration is broken and loop continues with next iteration.
In below example, Loop is broken when counter reaches 4.
for (counter = 0; counter & lt; 10; counter++)
system.out.println(counter);

if (counter == 4) {

break;
}

In the below example when counter reaches 4, loop jumps to next iteration and any
statements after the continue keyword are skipped for current iteration.
for (counter = 0; counter < 10; counter++)
system.out.println(counter);

if (counter == 4) {
96

continue;
}
system.out.println("This will not get printed when counter is 4");
}

Q9) What is the difference between double and float variables in Java?
Ans: In java, float takes 4 bytes in memory while Double takes 8 bytes in memory. Float
is single precision floating point decimal number while Double is double precision
decimal number.

Q10) What is Final Keyword in Java? Give an example.


Ans: In java, a constant is declared using the keyword Final. Value can be assigned only
once and after assignment, value of a constant can’t be changed.
In below example, a constant with the name const_val is declared and assigned avalue:
Private Final int const_val=100
When a method is declared as final, it can NOT be overridden by the subclasses. This
method are faster than any other method, because they are resolved at complied time.
When a class is declares as final, it cannot be subclassed. Example String, Integer and
other wrapper classes.

Q11) 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);
}
}
97

Q12) How can you generate random numbers in Java?


Ans:
● 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

Q13) What is default switch case? Give example.


Ans: In a switch statement, default case is executed when no other switch condition
matches. Default case is an optional case .It can be declared only once all other switch
cases have been coded.
In the below example, when score is not 1 or 2, default case is used.
public class switchExample {
int score = 4;
public static void main(String args[]) {
switch (score) {
case 1:
system.out.println("Score is 1");
break;
case 2:
system.out.println("Score is 2");
break;
default:
system.out.println("Default Case");
}
}
}

Q14) What’s the base class in Java from which all classes are derived?
Ans: java.lang.object

Q15) Can main() method in Java can return any data?


98

Ans: In java, main() method can’t return any data and hence, it’s always declared with a
void return type.

Q16) What are Java Packages? What’s the significance of packages?


Ans: In Java, package is a collection of classes and interfaces which are bundled together
as they are related to each other. Use of packages helps developers to modularize the
code and group the code for proper re-use. Once code has been packaged in Packages, it
can be imported in other classes and used.

Q17) Can we declare a class as Abstract without having any abstract method?
Ans: Yes we can create an abstract class by using abstract keyword before class name
even if it doesn’t have any abstract method. However, if a class has even one abstract
method, it must be declared as abstract otherwise it will give an error.

Q18) What’s the difference between an Abstract Class and Interface in Java?
Ans: The primary difference between an abstract class and interface is that an interface
can only possess declaration of public static methods with no concrete implementation
while an abstract class can have members with any access specifiers (public, private etc)
with or without concrete implementation.
Another key difference in the use of abstract classes and interfaces is that a class which
implements an interface must implement all the methods of the interface while a class
which inherits from an abstract class doesn’t require implementation of all the methods
of its super class.
A class can implement multiple interfaces but it can extend only one abstract class.

Q19) What are the performance implications of Interfaces over abstract classes?
Ans: Interfaces are slower in performance as compared to abstract classes as extra
indirections are required for interfaces. Another key factor for developers to take into
consideration is that any class can extend only one abstract class while a class can
implement many interfaces.
Use of interfaces also puts an extra burden on the developers as any time an interface is
implemented in a class; developer is forced to implement each and every method of
interface.
99

Q20) Does Importing a package imports its sub-packages as well in Java?


Ans: In java, when a package is imported, its sub-packages aren’t imported and
developer needs to import them separately if required.
For example, if a developer imports a package university.*, all classes in the package
named university are loaded but no classes from the sub-package are loaded. To load
the classes from its sub-package (say department), developer has to import it explicitly
as follows:
Import university.department.*

Q21) Can we declare the main method of our class as private?


Ans: In java, main method must be public static in order to run any application correctly.
If main method is declared as private, developer won’t get any compilation error
however, it will not get executed and will give a runtime error.

Q22) How can we pass argument to a function by reference instead of pass by value?
Ans: In java, we can pass argument to a function only by value and not by reference.

Q23) How an object is serialized in java?


Ans: In java, to convert an object into byte stream by serialization, an interface with the
name Serializable is implemented by the class. All objects of a class implementing
serializable interface get serialized and their state is saved in byte stream.

Q24) When we should use serialization?


Ans: Serialization is used when data needs to be transmitted over the network. Using
serialization, object’s state is saved and converted into byte stream .The byte stream is
transferred over the network and the object is re-created at destination.

Q25) Is it compulsory for a Try Block to be followed by a Catch Block in Java for
Exception handling?
Ans: Try block needs to be followed by either Catch block or Finally block or both. Any
exception thrown from try block needs to be either caught in the catch block or else any
specific tasks to be performed before code abortion are put in the Finally block.
100

Q26) Is there any way to skip Finally block of exception even if some exception occurs
in the exception block?
Ans: If an exception is raised in Try block, control passes to catch block if it exists
otherwise to finally block. Finally block is always executed when an exception occurs and
the only way to avoid execution of any statements in Finally block is by aborting the code
forcibly by writing following line of code at the end of try block:
System.exit(0);

Q27) When the constructor of a class is invoked?


Ans: The constructor of a class is invoked every time an object is created with new
keyword.
For example, in the following class two objects are created using new keyword and
hence, constructor is invoked two times.
public class const_example {

const_example() {

system.out.println("Inside constructor");
}
public static void main(String args[]) {

const_example c1 = new const_example();

const_example c2 = new const_example();


}
}

Q28) Can a class have multiple constructors?


Ans: Yes, a class can have multiple constructors with different parameters. Which
constructor gets used for object creation depends on the arguments passed while
creating the objects.
Q29) Can we override static methods of a class?
101

Ans: We cannot override static methods. Static methods belong to a class and not to
individual objects and are resolved at the time of compilation (not at runtime).Even if we
try to override static method, we will not get an complitaion error,nor the impact of
overriding when running the code.

Q30) In the below example, what will be the output?


public class superclass {

public void displayResult() {

system.out.println("Printing from superclass");

public class subclass extends superclass {

public void displayResult() {

system.out.println("Displaying from subClass");

super.displayResult();

public static void main(String args[]) {

subclass obj = new subclass();

obj.displayResult();

}
102

Ans: Output will be:


Displaying from subClass
Printing from superclass

Q31) Is String a data type in java?


Ans: String is not a primitive data type in java. When a string is created in java, it’s
actually an object of Java.Lang.String class that gets created. After creation of this string
object, all built-in methods of String class can be used on the string object.

Q32) In the below example, how many String Objects are created?
String s1="I am Java Expert";

String s2="I am C Expert";

String s3="I am Java Expert";


Ans: In the above example, two objects of Java.Lang.String class are created. s1 and s3
are references to same object.

Q33) Why Strings in Java are called as Immutable?


Ans: In java, string objects are called immutable as once value has been assigned to a
string, it can’t be changed and if changed, a new object is created.
In below example, reference str refers to a string object having value “Value one”.
String str="Value One";
When a new value is assigned to it, a new String object gets created and the reference is
moved to the new object.
str="New Value";

Q34) What’s the difference between an array and Vector?


Ans: An array groups data of same primitive type and is static in nature while vectors are
dynamic in nature and can hold data of different data types.

Q35) What is multi-threading?


103

Ans: Multi threading is a programming concept to run multiple tasks in a concurrent


manner within a single program. Threads share same process stack and running in
parallel. It helps in performance improvement of any program.

Q36) Why Runnable Interface is used in Java?


Ans: Runnable interface is used in java for implementing multi threaded applications.
Java.Lang.Runnable interface is implemented by a class to support multi threading.

Q37) What are the two ways of implementing multi-threading in Java?


Ans: Multi threaded applications can be developed in Java by using any of the following
two methodologies:
1) By using Java.Lang.Runnable Interface. Classes implement this interface to enable
multi threading. There is a Run() method in this interface which is implemented.
2) By writing a class that extend Java.Lang.Thread class.

Q38) When a lot of changes are required in data, which one should be a preference to
be used? String or StringBuffer?
Ans: Since StringBuffers are dynamic in nature and we can change the values of
StringBuffer objects unlike String which is immutable, it’s always a good choice to use
StringBuffer when data is being changed too much. If we use String in such a case, for
every data change a new String object will be created which will be an extra overhead.

Q39) What’s the purpose of using Break in each case of Switch Statement?
Ans: Break is used after each case (except the last one) in a switch so that code breaks
after the valid case and doesn’t flow in the proceeding cases too.
If break isn’t used after each case, all cases after the valid case also get executed
resulting in wrong results.

Q40) How garbage collection is done in Java?


Ans: In java, when an object is not referenced any more, garbage collection takes place
and the object is destroyed automatically. For automatic garbage collection java calls
either System.gc() method or Runtime.gc() method.
104

Q41) How we can execute any code even before main method?
Ans: If we want to execute any statements before even creation of objects at load time
of class, we can use a static block of code in the class. Any statements inside this static
block of code will get executed once at the time of loading the class even before creation
of objects in the main method.

Q42) Can a class be a super class and a sub-class at the same time? Give example.
Ans: If there is a hierarchy of inheritance used, a class can be a super class for another
class and a sub-class for another one at the same time.
In the example below, continent class is sub-class of world class and it’s super class of
country class.
public class world {

..........

}
public class continenet extends world {

............

}
public class country extends continent {

......................

Q43) How objects of a class are created if no constructor is defined in the class?
Ans: Even if no explicit constructor is defined in a java class, objects get created
successfully as a default constructor is implicitly used for object creation. This
constructor has no parameters.
105

Q44) In multi-threading how can we ensure that a resource isn’t used by multiple
threads simultaneously?
Ans: In multi-threading, access to the resources which are shared among multiple
threads can be controlled by using the concept of synchronization. Using synchronized
keyword, we can ensure that only one thread can use shared resource at a time and
others can get control of the resource only once it has become free from the other one
using it.

Q45) Can we call the constructor of a class more than once for an object?
Ans: Constructor is called automatically when we create an object using new keyword.
It’s called only once for an object at the time of object creation and hence, we can’t
invoke the constructor again for an object after its creation.

Q46) There are two classes named classA and classB. Both classes are in the same
package. Can a private member of classA can be accessed by an object of classB?
Ans: Private members of a class aren’t accessible outside the scope of that class and any
other class even in the same package can’t access them.

Q47) Can we have two methods in a class with the same name?
Ans: We can define two methods in a class with the same name but with different
number/type of parameters. Which method is to get invoked will depend upon the
parameters passed.
For example in the class below we have two print methods with same name but
different parameters. Depending upon the parameters, appropriate one will be called:
public class methodExample {

public void print() {

system.out.println("Print method without parameters.");

public void print(String name) {


106

system.out.println("Print method with parameter");

public static void main(String args[]) {

methodExample obj1 = new methodExample();

obj1.print();

obj1.print("xx");

Q48) How can we make copy of a java object?


Ans: We can use the concept of cloning to create copy of an object. Using clone, we
create copies with the actual state of an object.
Clone() is a method of Cloneable interface and hence, Cloneable interface needs to be
implemented for making object copies.

Q49) What’s the benefit of using inheritance?


Ans: Key benefit of using inheritance is reusability of code as inheritance enables
sub-classes to reuse the code of its super class. Polymorphism (Extensibility) is another
great benefit which allow new functionality to be introduced without effecting existing
derived classes.

Q50) What’s the default access specifier for variables and methods of a class?
Ans: Default access specifier for variables and method is package protected i.e variables
and class is available to any other class but in the same package, not outside the
package.
107

Q51) Give an example of use of Pointers in Java class.


Ans: There are no pointers in Java. So we can’t use concept of pointers in Java.

Q52) How can we restrict inheritance for a class so that no class can be inherited from
it?
Ans: If we want a class not to be extended further by any class, we can use the keyword
Final with the class name.
In the following example, Stone class is Final and can’t be extend
public Final Class Stone {
// Class methods and Variables
}

Q53) What’s the access scope of Protected Access specifier?


Ans: When a method or a variable is declared with Protected access specifier, it becomes
accessible in the same class, any other class of the same package as well as a sub-class.
Modifier Class Package Subclass World

public Y Y Y Y

protected Y Y Y N

no modifier Y Y N N

private Y N N N

Q54) What’s difference between Stack and Queue?


Ans: Stack and Queue both are used as placeholder for a collection of data. The primary
difference between a stack and a queue is that stack is based on Last in First out (LIFO)
principle while a queue is based on FIFO (First In First Out) principle.

Q55) In java, how we can disallow serialization of variables?


108

Ans: If we want certain variables of a class not to be serialized, we can use the keyword
transient while declaring them. For example, the variable trans_var below is a transient
variable and can’t be serialized:
public class transientExample {
private transient trans_var;
// rest of the code
}

Q56) How can we use primitive data types as objects?


Ans: Primitive data types like int can be handled as objects by the use of their respective
wrapper classes. For example, Integer is a wrapper class for primitive data type int. We
can apply different methods to a wrapper class, just like any other object.

Q57) Which types of exceptions are caught at compile time?


Ans: Checked exceptions can be caught at the time of program compilation. Checked
exceptions must be handled by using try catch block in the code in order to successfully
compile the code.

Q58) Describe different states of a thread.


Ans: A thread in Java can be in either of the following states:
● Ready: When a thread is created, it’s in Ready state.
● Running: A thread currently being executed is in running state.
● Waiting: A thread waiting for another thread to free certain resources is in
waiting state.
● Dead: A thread which has gone dead after execution is in dead state.

Q59) Can we use a default constructor of a class even if an explicit constructor is


defined?
Ans: Java provides a default no argument constructor if no explicit constructor is defined
in a Java class. But if an explicit constructor has been defined, default constructor can’t
be invoked and developer can use only those constructors which are defined in the class.
109

Q60) Can we override a method by using same method name and arguments but
different return types?
Ans: The basic condition of method overriding is that method name, arguments as well
as return type must be exactly same as is that of the method being overridden. Hence
using a different return type doesn’t override a method.

Q61) What will be the output of following piece of code?


public class operatorExample {

public static void main(String args[]) {

int x = 4;

system.out.println(x++);
}
}

Ans: In this case postfix ++ operator is used which first returns the value and then
increments. Hence it’s output will be 4.

Q61) A person says that he compiled a java class successfully without even having a
main method in it? Is it possible?
Ans: main method is an entry point of Java class and is required for execution of the
program however; a class gets compiled successfully even if it doesn’t have a main
method. It can’t be run though.

Q62) Can we call a non-static method from inside a static method?


Ans: Non-Static methods are owned by objects of a class and have object level scope and
in order to call the non-Static methods from a static block (like from a static main
method), an object of the class needs to be created first. Then using object reference,
these methods can be invoked.

Q63) What are the two environment variables that must be set in order to run any
Java programs?
110

Ans: Java programs can be executed in a machine only once following two environment
variables have been properly set:
1. PATH variable
2. CLASSPATH variable

Q64) Can variables be used in Java without initialization?


Ans: In Java, if a variable is used in a code without prior initialization by a valid value,
program doesn’t compile and gives an error as no default value is assigned to variables
in Java.

Q65) Can a class in Java be inherited from more than one class?
Ans: In Java, a class can be derived from only one class and not from multiple classes.
Multiple inheritances is not supported by Java.

Q66) Can a constructor have different name than a Class name in Java?
Ans: Constructor in Java must have same name as the class name and if the name is
different, it doesn’t act as a constructor and compiler thinks of it as a normal method.

Q67) What will be the output of Round(3.7) and Ceil(3.7)?


Ans: Round(3.7) returns 4 and Ceil(3.7) returns 4.

Q68) Can we use goto in Java to go to a particular line?


Ans: In Java, there is not goto keyword and java doesn’t support this feature of going to
a particular labeled line.

Q69) Can a dead thread be started again?


Ans: In java, a thread which is in dead state can’t be started again. There is no way to
restart a dead thread.

Q70) Is the following class declaration correct?


Ans:
public abstract final class testClass {
111

// Class methods and variables


}

Ans: The above class declaration is incorrect as an abstract class can’t be declared as
Final.

Q71) Is JDK required on each machine to run a Java program?


Ans: JDK is development Kit of Java and is required for development only and to run a
Java program on a machine, JDK isn’t required. Only JRE is required.

Q72) What’s the difference between comparison done by equals method and ==
operator?
Ans: In Java, equals() method is used to compare the contents of two string objects and
returns true if the two have same value while == operator compares the references of
two string objects.
In the following example, equals() returns true as the two string objects have same
values. However == operator returns false as both string objects are referencing to
different objects:
public class equalsTest {

public static void main(String args[]) {

String str1 = new String("Hello World");

String str2 = new String("Hello World");

if (str1.equals(str2))

{ // this condition is true

System.out.println("str1 and str2 are equal in terms of values");

}
112

if (str1 == str2) {

//This condition is true

System.out.println("Both strings are referencing same object");

} else

// This condition is NOT true

System.out.println("Both strings are referencing different objects");

Q73) Is it possible to define a method in Java class but provide it’s implementation in
the code of another language like C?
Ans: Yes, we can do this by use of native methods. In case of native method based
development, we define public static methods in our Java class without its
implementation and then implementation is done in another language like C separately.

Q74) How are destructors defined in Java?


Ans: In Java, there are no destructors defined in the class as there is no need to do so.
Java has its own garbage collection mechanism which does the job automatically by
destroying the objects when no longer referenced.

Q75) Can a variable be local and static at the same time?


113

Ans: No a variable can’t be static as well as local at the same time. Defining a local
variable as static gives compilation error.

Q76) Can we have static methods in an Interface?


Ans: Static methods can’t be overridden in any class while any methods in an interface
are by default abstract and are supposed to be implemented in the classes being
implementing the interface. So it makes no sense to have static methods in an interface
in Java.

Q77) In a class implementing an interface, can we change the value of any variable
defined in the interface?
Ans: No, we can’t change the value of any variable of an interface in the implementing
class as all variables defined in the interface are by default public, static and Final and
final variables are like constants which can’t be changed later.

Q78) Is it correct to say that due to garbage collection feature in Java, a java program
never goes out of memory?
Ans: Even though automatic garbage collection is provided by Java, it doesn’t ensure
that a Java program will not go out of memory as there is a possibility that creation of
Java objects is being done at a faster pace compared to garbage collection resulting in
filling of all the available memory resources.
So, garbage collection helps in reducing the chances of a program going out of memory
but it doesn’t ensure that.

Q79) Can we have any other return type than void for main method?
Ans: No, Java class main method can have only void return type for the program to get
successfully executed.
Nonetheless , if you absolutely must return a value to at the completion of main method
, you can use System.exit(int status)

Q80) I want to re-reach and use an object once it has been garbage collected. How it’s
possible?
114

Ans: Once an object has been destroyed by garbage collector, it no longer exists on the
heap and it can’t be accessed again. There is no way to reference it again.

Q81) In Java thread programming, which method is a must implementation for all
threads?
Ans: Run() is a method of Runnable interface that must be implemented by all threads.

Q82) I want to control database connections in my program and want that only one
thread should be able to make database connection at a time. How can I implement
this logic?
Ans: This can be implemented by use of the concept of synchronization. Database
related code can be placed in a method which hs synchronized keyword so that only one
thread can access it at a time.

Q83) How can an exception be thrown manually by a programmer?


Ans: In order to throw an exception in a block of code manually, throw keyword is used.
Then this exception is caught and handled in the catch block.
public void topMethod() {
try {
excMethod();
} catch (ManualException e) {}
}

public void excMethod {


String name = null;
if (name == null) {
throw (new ManualException("Exception thrown manually ");
}
}
Q84) I want my class to be developed in such a way that no other class (even derived
class) can create its objects. How can I do so?
Ans: If we declare the constructor of a class as private, it will not be accessible by any
other class and hence, no other class will be able to instantiate it and formation of its
object will be limited to itself only.
115

Q85) How objects are stored in Java?


Ans: In java, each object when created gets a memory space from a heap. When an
object is destroyed by a garbage collector, the space allocated to it from the heap is
re-allocated to the heap and becomes available for any new objects.

Q86) How can we find the actual size of an object on the heap?
Ans: In java, there is no way to find out the exact size of an object on the heap.

Q87) Which of the following classes will have more memory allocated?
Class A: Three methods, four variables, no object
Class B: Five methods, three variables, no object
Ans: Memory isn’t allocated before creation of objects. Since for both classes, there are
no objects created so no memory is allocated on heap for any class.

Q88) What happens if an exception is not handled in a program?


Ans: If an exception is not handled in a program using try catch blocks, program gets
aborted and no statement executes after the statement which caused exception
throwing.

Q89) I have multiple constructors defined in a class. Is it possible to call a constructor


from another constructor’s body?
Ans: If a class has multiple constructors, it’s possible to call one constructor from the
body of another one using this().

Q90) What’s meant by anonymous class?


Ans: An anonymous class is a class defined without any name in a single line of code
using new keyword.
For example, in below code we have defined an anonymous class in one line of code:
public java.util.Enumeration testMethod()

{
116

return new java.util.Enumeration()

@Override

public boolean hasMoreElements()

// TODO Auto-generated method stub

return false;

@Override

public Object nextElement()

// TODO Auto-generated method stub

return null;

Q91) Is there a way to increase the size of an array after its declaration?
Ans: Arrays are static and once we have specified its size, we can’t change it. If we want
to use such collections where we may require a change of size (no of items), we should
prefer vector over array.
117

Q92) If an application has multiple classes in it, is it okay to have a main method in
more than one class?
Ans: If there is main method in more than one classes in a java application, it won’t
cause any issue as entry point for any application will be a specific class and code will
start from the main method of that particular class only.

Q93) I want to persist data of objects for later use. What’s the best approach to do so?
Ans: The best way to persist data for future use is to use the concept of serialization.

Q94) What is a Local class in Java?


Ans: In Java, if we define a new class inside a particular block, it’s called a local class.
Such a class has local scope and isn’t usable outside the block where its defined.

Q95) String and StringBuffer both represent String objects. Can we compare String and
StringBuffer in Java?
Ans: Although String and StringBuffer both represent String objects, we can’t compare
them with each other and if we try to compare them, we get an error.

Q96) Which API is provided by Java for operations on set of objects?


Ans: Java provides a Collection API which provides many useful methods which can be
applied on a set of objects. Some of the important classes provided by Collection API
include ArrayList, HashMap, TreeSet and TreeMap.

Q97) Can we cast any other type to Boolean Type with type casting?
Ans: No, we can neither cast any other primitive type to Boolean data type nor can cast
Boolean data type to any other primitive data type.

Q98) Can we use different return types for methods when overridden?
Ans: The basic requirement of method overriding in Java is that the overridden method
should have same name, and parameters.But a method can be overridden with a
different return type as long as the new return type extends the original.
118

For example , method is returning a reference type.


Class B extends A {

A method(int x) {

//original method

B method(int x) {

//overridden method

Q99) What’s the base class of all exception classes?


Ans: In Java, Java.lang.Throwable is the super class of all exception classes and all
exception classes are derived from this base class.

Q100) What’s the order of call of constructors in inheritance?


Ans: In case of inheritance, when a new object of a derived class is created, first the
constructor of the super class is invoked and then the constructor of the derived class is
invoked.
119

2. In which programming paradigm Java 8 falls?


● Object-oriented programming language.
● Functional programming language.
● Procedural programming language.
● Logic programming language

3. What are the significant advantages of Java 8?


● Compact, readable, and reusable code.
● Less boilerplate code.
● Parallel operations and execution.
● Can be ported across operating systems.
● High stability.
● Stable environment.
● Adequate support
120

8. What are static methods in Interfaces?


Static methods, which contains method implementation is owned by the interface and is
invoked using the name of the interface, it is suitable for defining the utility methods
and cannot be overridden.

9. What are some standard Java pre-defined functional interfaces?


121

Some of the famous pre-defined functional interfaces from previous Java versions are
Runnable, Callable, Comparator, and Comparable. While Java 8 introduces functional
interfaces like Supplier, Consumer, Predicate, etc. Please refer to the java.util.function
doc for other predefined functional interfaces and its description introduced in Java 8.

Runnable: use to execute the instances of a class over another thread with no
arguments and no return value.

Callable: use to execute the instances of a class over another thread with no arguments
and it either returns a value or throws an exception.

Comparator: use to sort different objects in a user-defined order

Comparable: use to sort objects in the natural sort order

10. What are the various categories of pre-defined function interfaces?


Function: To transform arguments in returnable value.

Predicate: To perform a test and return a Boolean value.

Consumer: Accept arguments but do not return any values.

Supplier: Do not accept any arguments but return a value.

Operator: Perform a reduction type operation that accepts the same input types.

11. What is the lambda expression in Java and How does a lambda expression relate to
a functional interface?
Lambda expression is a type of function without a name. It may or may not have results
and parameters. It is known as an anonymous function as it does not have type
information by itself. It is executed on-demand. It is beneficial in iterating, filtering, and
extracting data from a collection.
122

As lambda expressions are similar to anonymous functions, they can only be applied to
the single abstract method of Functional Interface. It will infer the return type, type, and
several arguments from the signature of the abstract method of functional interface.

Java 8 Interview Questions for Experienced

12. What is the basic structure/syntax of a lambda expression?


FunctionalInterface fi = (String name) -> {
System.out.println("Hello "+name);
return "Hello "+name;
}
Lambda expression can be divided into three distinct parts as below:

1. List of Arguments/Params:

(String name)

A list of params is passed in () round brackets. It can have zero or more params.
Declaring the type of parameter is optional and can be inferred for the context.

2. Arrow Token:

->

Arrow token is known as the lambda arrow operator. It is used to separate the
parameters from the body, or it points the list of arguments to the body. 3.
Expression/Body:

{
System.out.println("Hello "+name);
return "Hello "+name;
}
123

A body can have expressions or statements. {} curly braces are only required when there
is more than one line. In one statement, the return type is the same as the return type
of the statement. In other cases, the return type is either inferred by the return keyword
or void if nothing is returned.

13. What are the features of a lambda expression?


Below are the two significant features of the methods that are defined as the lambda
expressions:

● Lambda expressions can be passed as a parameter to another method.


● Lambda expressions can be standalone without belonging to any class.

14. What is a type interface?


Type interface is available even in earlier versions of Java. It is used to infer the type of
argument by the compiler at the compile time by looking at method invocation and
corresponding declaration.

15. What are the types and common ways to use lambda expressions?
A lambda expression does not have any specific type by itself. A lambda expression
receives type once it is assigned to a functional interface. That same lambda expression
can be assigned to different functional interface types and can have a different type.

For eg consider expression s -> s.isEmpty() :

Predicate<String> stringPredicate = s -> s.isEmpty();

Predicate<List> listPredicate = s -> s.isEmpty();

Function<String, Boolean> func = s -> s.isEmpty();

Consumer<String> stringConsumer = s -> s.isEmpty();


124

Common ways to use the expression

Assignment to a functional Interface —> Predicate<String> stringPredicate = s ->


s.isEmpty();

Can be passed as a parameter that has a functional type —> stream.filter(s ->
s.isEmpty())

Returning it from a function —> return s -> s.isEmpty()

Casting it to a functional type —> (Predicate<String>) s -> s.isEmpty()

16. In Java 8, what is Method Reference?


Method reference is a compact way of referring to a method of functional interface. It is
used to refer to a method without invoking it. :: (double colon) is used for describing the
method reference. The syntax is class::methodName

For e.g.:

Integer::parseInt(str) \\ method reference

str -> Integer.ParseInt(str); \\ equivalent lambda

7. What does the String::ValueOf expression mean?


It is a static method reference to method Valueof() of class String. It will return the string
representation of the argument passed.

18. What is an Optional class?


Optional is a container type which may or may not contain value i.e. zero(null) or
one(not-null) value. It is part of java.util package. There are pre-defined methods like
125

isPresent(), which returns true if the value is present or else false and the method get(),
which will return the value if it is present.

static Optional<String> changeCase(String word) {


if (name != null && word.startsWith("A")) {
return Optional.of(word.toUpperCase());
}
else {
return Optional.ofNullable(word); // someString can be null
}
}

19. What are the advantages of using the Optional class?


Below are the main advantage of using the Optional class:

It encapsulates optional values, i.e., null or not-null values, which helps in avoiding null
checks, which results in better, readable, and robust code It acts as a wrapper around
the object and returns an object instead of a value, which can be used to avoid run-time
NullPointerExceptions.

20. What are Java 8 streams?


A stream is an abstraction to express data processing queries in a declarative way.

A Stream, which represents a sequence of data objects & series of operations on that
data is a data pipeline that is not related to Java I/O Streams does not hold any data
permanently.

The key interface is java.util.stream.Stream<T>. It accepts Functional Interfaces so that


lambdas can be passed. Streams support a fluent interface or chaining. Below is the
basic stream timeline marble diagram:
126

22. What are the sources of data objects a Stream can process?
A Stream can process the following data:

● A collection of an Array.
● An I/O channel or an input device.
● A reactive source (e.g., comments in social media or tweets/re-tweets)
● A stream generator function or a static factory.

23. What are Intermediate and Terminal operations?


Intermediate Operations:

● Process the stream elements.


● Typically transforms a stream into another stream.
● Are lazy, i.e., not executed till a terminal operation is invoked.
● Does internal iteration of all source elements.
● Any number of operations can be chained in the processing pipeline.
● Operations are applied as per the defined order.
● Intermediate operations are mostly lambda functions.
Terminal Operations:

● Kick-starts the Stream pipeline.


● used to collect the processed Stream data.
int count = Stream.of(1, 2, 3, 4, 5)
.filter(i -> i <4) // Intermediate Operation filter
.count(); // Terminal Operation count

24. What are the most commonly used Intermediate operations?


Filter(Predicate<T>) - Allows selective processing of Stream elements. It returns
elements that are satisfying the supplied condition by the predicate.

map(Funtion<T, R>) - Returns a new Stream, transforming each of the elements by


applying the supplied mapper function.= sorted() - Sorts the input elements and then
passes them to the next stage.
127

distinct() - Only pass on elements to the next stage, not passed yet.

limit(long maxsize) - Limit the stream size to maxsize.

skip(long start) - Skip the initial elements till the start.

peek(Consumer) - Apply a consumer without modification to the stream.

flatMap(mapper) - Transform each element to a stream of its constituent elements and


flatten all the streams into a single stream.

25. What is the stateful intermediate operation? Give some examples of stateful
intermediate operations.
To complete some of the intermediate operations, some state is to be maintained, and
such intermediate operations are called stateful intermediate operations. Parallel
execution of these types of operations is complex.

For Eg: sorted() , distinct() , limit() , skip() etc.

Sending data elements to further steps in the pipeline stops till all the data is sorted for
sorted() and stream data elements are stored in temporary data structures.

26. What is the most common type of Terminal operations?


● collect() - Collects single result from all elements of the stream sequence.
● reduce() - Produces a single result from all elements of the stream sequence
○ count() - Returns the number of elements on the stream.
○ min() - Returns the min element from the stream.
○ max() - Returns the max element from the stream.
● Search/Query operations
○ anyMatch() , noneMatch() , allMatch() , ... - Short-circuiting operations.
○ Takes a Predicate as input for the match condition.
128

○ Stream processing will be stopped, as and when the result can be


determined.
● Iterative operations
○ forEach() - Useful to do something with each of the Stream elements. It
accepts a consumer.
○ forEachOrdered() - It is helpful to maintain order in parallel streams.

27. What is the difference between findFirst() and findAny()?

findFirst() findAny()

Returns the first element in the Return any element from the
Stream Stream

Deterministic in nature Non-deterministic in nature

28. How are Collections different from Stream?


Collections are the source for the Stream. Java 8 collection API is enhanced with the
default methods returning Stream<T> from the collections.

Collections Streams
129

Data structure holds all the No data is stored. Have the capacity to
data elements process an infinite number of elements on
demand

External Iteration Internal Iteration

Can be processed any Traversed only once


number of times

Elements are easy to access No direct way of accessing specific


elements

Is a data store Is an API to process the data

29. What is the feature of the new Date and Time API in Java 8?
130

● Immutable classes and Thread-safe


● Timezone support
● Fluent methods for object creation and arithmetic
● Addresses I18N issue for earlier APIs
● Influenced by popular joda-time package
● All packages are based on the ISO-8601 calendar system

30. What are the important packages for the new Data and Time API?
● java.time
○ dates
○ times
○ Instants
○ durations
○ time-zones
○ periods
● Java.time.format
● Java.time.temporal
● java.time.zone

31. Explain with example, LocalDate, LocalTime, and LocalDateTime APIs.


LocalDate

● Date with no time component


● Default format - yyyy-MM-dd (2020-02-20)
● LocalDate today = LocalDate.now(); // gives today’s date
● LocalDate aDate = LocalDate.of(2011, 12, 30); //(year, month, date)
LocalTime

● Time with no date with nanosecond precision


● Default format - hh:mm:ss:zzz (12:06:03.015) nanosecond is optional
● LocalTime now = LocalTime.now(); // gives time now
● LocalTime aTime2 = LocalTime.of(18, 20, 30); // (hours, min, sec)
LocalDateTime
131

● Holds both Date and Time


● Default format - yyyy-MM-dd-HH-mm-ss.zzz (2020-02-20T12:06:03.015)
● LocalDateTime timestamp = LocalDateTime.now(); // gives timestamp now
● //(year, month, date, hours, min, sec)
● LocalDateTime dt1 = LocalDateTime.of(2011, 12, 30, 18, 20, 30);

32. Define Nashorn in Java 8


Nashorn is a JavaScript processing engine that is bundled with Java 8. It provides better
compliance with ECMA (European Computer Manufacturers Association) normalized
JavaScript specifications and better performance at run-time than older versions.

33. What is the use of JJS in Java 8?


As part of Java 8, JJS is a command-line tool that helps to execute the JavaScript code in
the console. Below is the example of CLI commands:

JAVA>jjs

jjs> print("Hello, Java 8 - I am the new JJS!")

Hello, Java 8 - I am the new JJS!

jjs> quit()

>>

You might also like