Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
142 views149 pages

Interview Questions

This document provides 15 questions and answers about Java functional programming and Stream API concepts that are commonly asked in interviews. Some key topics covered include the differences between Collections and Streams, how methods like map(), filter(), and flatMap() work, the difference between intermediate and terminal Stream operations, lazy evaluation of Streams, functional interfaces like Predicate and Consumer, and how to parallelize Stream processing.

Uploaded by

RahulKhot
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
142 views149 pages

Interview Questions

This document provides 15 questions and answers about Java functional programming and Stream API concepts that are commonly asked in interviews. Some key topics covered include the differences between Collections and Streams, how methods like map(), filter(), and flatMap() work, the difference between intermediate and terminal Stream operations, lazy evaluation of Streams, functional interfaces like Predicate and Consumer, and how to parallelize Stream processing.

Uploaded by

RahulKhot
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 149

10 Java Functional Programming and Stream Interview Questions

Without any further ado, here is a list of some of the common yet popular functional programming and Stream interview questions for Java programmers. If you have
any other Java functional programming question or anything related to JDK 8 Stream API, feel free to share with us, and I'll try to find an answer for you.

1. What is the difference between Collection and Stream? (answer)


The main difference between a Collection and Stream is that Collection contains their elements, but Stream doesn't. Stream work on a view where elements are
actually stored by Collection or array, but unlike other views, any change made on Stream doesn't reflect on the original Collection.

2. What does the map() function do? why you use it? (answer)
The map() function perform map functional operation in Java. This means it can transform one type of object to others by applying a function.

For example, if you have a List of String and you want to convert that to a List of Integer, you can use map() to do so.

Just supply a function to convert String to Integer e.g., parseInt() to map() and it will apply that to all elements of List and give you a List of Integer. In other words,
the map can convert one object to another.

If you want to learn more about these new methods introduced in Java S.E. 8, I suggest you take a look at The Complete Java Masterclass course on Udemy. One
of the most comprehensive courses which cover everything Java developers need to know.
3. What does the filter() method do? when you use it? (answer)
The filter method is used to filter elements that satisfy a certain condition that is specified using a Predicate function.

A predicate function is nothing but a function that takes an Object and returns a boolean. For example, if you have a List of Integer and you want a list of even
integers.

In this case, you can use the filter to achieve that. You supply a function to check if a number is even or odd, just like this function and filter will apply this to stream
elements and filter the elements which satisfy the condition and which doesn't.

4. What does the flatmap() function do? why you need it? (answer)
The flatmap function is an extension of the map function. Apart from transforming one object into another, it can also flatten it.

For example, if you have a list of the list but you want to combine all elements of lists into just one list. In this case, you can use flatMap() for flattening. At the
same time, you can also transform an object like you do use map() function.

5. What is difference between flatMap() and map() functions? (answer)


Even though both map() and flatMap() can be used to transform one object to another by applying a method on each element.

The main difference is that flatMap() can also flatten the Stream. For example, if you have a list of the list, then you can convert it to a big list by
using flatMap() function.

Btw, if you find trouble understanding these functional programming methods like map, flatMap, filter, etc., I suggest you go through From Collections to Streams in
Java 8 course on Pluralsight. It's an advanced course but very good.
Btw, you would need a Pluralsight membership to access this course, which costs around $29 monthly or $299 annually (14% discount). I have one, and I also
suggest all developers have that plan because Pluralsight is like NetFlix for Software developers.

It has more than 5000+ good quality courses on all the latest topics. Since we programmers have to learn new things every day, an investment of $299 USD is not
bad.

Btw, it also offers a 10-day free trial without any obligation, which allows you to watch 200 hours of content. You can watch this course for free by signing for that
trial.

6. What is the difference between intermediate and terminal operations on Stream? (answer)
The intermediate Stream operation returns another Stream, which means you can further call other methods of Stream class to compose a pipeline.

For example after calling map() or flatMap() you can still call filter() method on Stream.

On the other hand, the terminal operation produces a result other than Streams like a value or a Collection.
Once a terminal method like forEach() or collect() is called, you cannot call any other method of Stream or reuse the Stream.

7. What does the peek() method do? When should you use it? (answer)
The peek() method of Stream class allows you to see through a Stream pipeline. You can peek through each step and print meaningful messages on the console.
It's generally used for debugging issues related to lambda expression and Stream processing.

8. What do you mean by saying Stream is lazy? (answer)


When we say Stream is lazy, we mean that most of the methods defined on Java .util.stream.Stream class is lazy i.e. they will not work by just including them
on Stream pipeline.

They only work when you call a terminal method on the Stream and finish as soon as they find the data they are looking for rather than scanning through the whole
set of data.
9. What is a functional interface in Java 8? (answer)
As the name suggests, a functional interface is an interface that represents a function. Technically, an interface with just one abstract method is called a functional
interface.

You can also use @FunctionalInterface to annotated a functional interface. In that case, the compiler will verify if the interface actually contains just one abstract
method or not. It's like the @Override annotation, which prevents you from accidental errors.

Another useful thing to know is that If a method accepts a functional interface, then you can pass a lambda expression to it.

Some examples of the functional interface are Runnable, Callable, Comparator, and Comparable from old API and Supplier, Consumer,
and Predicate, etc. from new function API. You can learn more about those interfaces in Java What's New in Java 8 on Pluralsight.

10. What is the difference between a normal and functional interface in Java? (answer)
The normal interface in Java can contain any number of abstract methods, while the functional interface can only contain just one abstract method.

You might be thinking why they are called functional interfaces? Once you know the answer, it might be a little easier for you to remember the concept.

Well, they are called functional interfaces because they wrap a function as an interface. The function is represented by the single abstract method on the interface.
11. What is the difference between the findFirst() and findAny() method? (answer)
The findFirst() method will return the first element meeting the criterion i.e. Predicate, while the findAny() method will return any element meeting the
criterion, very useful while working with a parallel stream. You can further see this article for a working example of the findFirst() method in Java 8.

12. What is a Predicate interface? (answer)


A Predicate is a functional interface that represents a function, which takes an Object and returns a boolean. It is used in several Stream methods like filter(), which
uses Predicate to filter unwanted elements.

here is how a Predicate function looks like:

public boolean test(T object){


return boolean;
}

You can see it just has one test() method which takes an object and returns a boolean. The method is used to test a condition if it passes; it returns true otherwise
false.

13. What are Supplier and Consumer Functional interface? (answer)


The Supplier is a functional interface that returns an object. It's similar to the factory method or new(), which returns an object.

The Supplier has get() functional method, which doesn't take any argument and return an object of type T. This means you can use it anytime you need an
object.

Since it is a functional interface, you can also use it as the assignment target for a lambda expression or method reference.

A Consumer is also a functional interface in JDK 8, which represents an operation that accepts a single input argument and returns no result.

Unlike other functional interfaces, Consumer is expected to operate via side-effects. The functional method of Consumer is accept(T t), and because it's a
functional interface, you can use it as the assignment target for a lambda expression or method interface in Java 8.
14. Can you convert an array to Stream? How? (answer)
Yes, you can convert an array to Stream in Java. The Stream class provides a factory method to create a Stream from an array, like Stream .of(T ...) which
accepts a variable argument, that means you can also pass an array to it as shown in the following example:

String[] languages = {"Java", "Python", "JavaScript"};


Stream numbers = Stream.of(languages);
numbers.forEach(System.out::println);

Output:
Java
Python
JavaScript

So, yes, it's possible to convert an array to Stream in Java 8. You can even convert an ArrayList to Stream, as explained in that article.

15. What is the parallel Stream? How can you get a parallel stream from a List? (answer)
A parallel stream can parallel execute stream processing tasks. For example, if you have a parallel stream of 1 million orders and you are looking for orders worth
more than 1 million, then you can use a filter to do that.

Unlike sequential Stream, the parallel Stream can launch multiple threads to search for those orders on the different part of Stream and then combine the result.

In short, the parallel Stream can paralyze execution, but, as Cay S. Horstman mentioned in Core Java S.E. 9 for the Impatient, there is significant overhead or
parallelism, which only pays off if you are doing bulk data operation.

That's all about some of the common Java 8 Stream and Functional programming concepts based interview questions. Since Java 8 is now the modern way of
writing Java code, more and more companies are looking for Java developers with good Java 8 skills. This means you can expect more Java 8 based questions on
Java interviews in years to come.

----------------------------------------------------------------------------------------------------------------------------------------------------
Top 50 Java Interview Questions for 2 to 3 years Experienced Programmers
So, without wasting any more of your time, here is my list of some of the frequently asked Core Java Interview
Questions for beginner programmers. This list focuses on beginners and less experienced devs, like someone with 2
to 3 years of experience in Java.

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.
5) What is double checked locking in Singleton? (answer)
hint: two-time check whether instances is 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) Difference between Serializable and Externalizable in Java? (answer)


hint: Externalizable gives you more control over the Serialization process.
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) When to use the volatile variable in Java? (answer)


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.

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.

13) Difference between **List**and **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.

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-Courseby Java Champion Heinz Kabutz to learn more about threading basics.

20) Why 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 other doesn't. Insertion and deletion 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.
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. SeeJava 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)
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 class, which is required by Polymorphism,
which provides dynamic behavior. See Object Oriented Java Programming: Data Structures and Beyond
Specialization on Coursera, to learn more about OOP features. One of the most in-depth course for beginners.

33) Can we override 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)\


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 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 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.
38) Difference between fail-safe and fail-fast iterators in Java? (answer)
hint: fail-safe doesn't throw ConcurrentModificationException while fail-fast does 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.

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)\


hint: Comparator defines custom ordering while Comparable defines the natural order of objects, e.g. the alphabetic order
for String. SeeThe 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 method are declared in **Object** class in Java? (answer)
hint: because they require lock which is only available to an object.

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

Why is Java called the ‘Platform Independent Programming Language’?

Platform independence means that execution of your program does not dependent on type of operating system(it could be any :
Linux, windows, Mac ..etc). So compile code only once and run it on any System (In C/C++, we need to compile the code for eve ry
machine on which we run it). Java is both compiler(javac) and interpreter(jvm) based lauguage. Your java source code is first
compiled into byte code using javac compiler. This byte code can be easily converted to equivalent machine code using JVM.
JVM(Java Virtual Machine) is available in all operating systems we install. Hence, byte code generated by javac is universal and
can be converted to machine code on any operating system, this is the reason why java is platform independent.

Explain Final keyword in java?

Final keyword in java is used to restrict usage of variable, class and method.

Variable: Value of Final variable is constant, you can not change it.
Method: you can’t override a Final method.
Class: you can’t inherit from Final class.
Refer this for details
When is the super keyword used?

super keyword is used to refer:


 immediate parent class constructor,
 immediate parent class variable,
 immediate parent class method.
Refer this for details.

What is the difference between StringBuffer and String?

String is an Immutable class, i.e. you can not modify its content once created. While StringBuffer is a mutable class, means you can
change its content later. Whenever we alter content of String object, it creates a new string and refer to that,it does not modify the
existing one. This is the reason that the performance with StringBuffer is better than with String.
Refer this for details.

Why multiple inheritance is not supported in java?

Java supports multiple inheritance but not through classes, it supports only through its interfaces. The reason for not supporting
multiple inheritance is to avoid the conflict and complexity arises due to it and keep Java a Simple Object Oriented Language . If we
recall this in C++, there is a special case of multiple inheritance (diamond problem) where you have a multiple inheritance with two
classes which have methods in conflicts. So, Java developers decided to avoid such conflicts and didn’t allow multiple inheritance
through classes at all.

Can a top level class be private or protected?

Top level classes in java can’t be private or protected, but inner classes in java can. The reason for not making a top level class as
private is very obvious, because nobody can see a private class and thus they can not use it. Declaring a class as protected also
doesn’t make any sense. The only difference between default visibility and protected visibility is that we can use it in any package
by inheriting it. Since in java there is no such concept of package inheritance, defining a class as protected is no different from
default.

What is the difference between ‘throw’ and ‘throws’ in Java Exception Handling?

Following are the differences between two:


 throw keyword is used to throw Exception from any method or static block whereas throws is used to indicate that which
Exception can possibly be thrown by this method
 If any method throws checked Exception, then caller can either handle this exception(using try catch block )or can re throw it by
declaring another ‘throws’ clause in method declaration.
 throw clause can be used in any part of code where you feel a specific exception needs to be thrown to the calling method
E.g.
throw
throw new Exception(“You have some exception”)
throw new IOException(“Connection failed!!”)
throws
throws IOException, NullPointerException, ArithmeticException

What is finalize() method?

Unlike c++ , we don’t need to destroy objects explicitly in Java. ‘Garbage Collector‘ does that automatically for us. Garbage
Collector checks if no references to an object exist, that object is assumed to be no longer required, and the memory occupied by
the object can be freed. Sometimes an object can hold non-java resources such as file handle or database connection, then you
want to make sure these resources are also released before object is destroyed. To perform such operation Java provide protec ted
void finalize() in object class. You can override this method in your class and do the requ ired tasks. Right before an object is freed,
the java run time calls the finalize() method on that object. Refer this for more details.

Difference in Set and List interface?

Set and List both are child interface of Collection interface. There are following two main differences between them
 List can hold duplicate values but Set doesn’t allow this.
 In List interface data is present in the order you inserted but in the case of Set insertion order is not preserved.

What will happen if you put System.exit(0) on try or catch block? Will finally block execute?

By Calling System.exit(0) in try or catch block, we can skip the finally block. System.exit(int) method can throw a SecurityE xception.
If Sysytem.exit(0) exits the JVM without throwing that exception then finally block will not execute. But, if System.exit(0) does throw
security exception then finally block will be executed.
What is Object Oriented Programming?
Object Oriented Programming (OOP) is a programming paradigm where the complete software operates as a bunch of objects
talking to each other. An object is a collection of data and methods that operate on its data.
Why OOP?
The main advantage of OOP is better manageable code that covers following.
1) The overall understanding of the software is increased as the distance between the language spoken by developers and that
spoken by users.
2) Object orientation eases maintenance by the use of encapsulation. One can easily change the underlying representation by
keeping the methods same.
OOP paradigm is mainly useful for relatively big software.
What are main features of OOP?
Encapsulation
Polymorphism
Inheritance

What is encapsulation?
Encapsulation is referred to one of the following two notions.
1) Data hiding: A language feature to restrict access to members of an object. For example, private and protected members in C++.
2) Bundling of data and methods together: Data and methods that operate on that data are bundled toget her.
What is Polymorphism? How is it supported by C++?
Polymorphism means that some code or operations or objects behave differently in different contexts. In C++, following features
support polymorphism.
Compile Time Polymorphism: Compile time polymorphism means compiler knows which function should be called when a
polymorphic call is made. C++ supports compiler time polymorphism by supporting features like templates, function overloading
and default arguments.
Run Time Polymorphism: Run time polymorphism is supported by virtual functions. The idea is, virtual functions are called
according to the type of object pointed or referred, not according to the type of pointer or reference. In other words, virtual functions
are resolved late, at runtime.
What is Inheritance? What is the purpose?
The idea of inheritance is simple, a class is based on another class and uses data and implementation of the other class.
The purpose of inheritance is Code Reuse.
What is Abstraction?
The first thing with which one is confronted when writing programs is the problem. Typically we are confr onted with “real-life”
problems and we want to make life easier by providing a program for the problem. However, real -life problems are nebulous and
the first thing we have to do is to try to understand the problem to separate necessary from unnecessary details: We try to obtain
our own abstract view, or model, of the problem. This process of modeling is called abstraction.

1) What are new features which got introduced in Java 8?


There are lots of new features which were added in Java 8. Here is the list of important features:

 Lambda Expression
 Stream API
 Default methods in the interface
 Functional Interface
 Optional
 Method reference
 Date API
 Nashorn, JavaScript Engine

2) What are main advantages of using Java 8?

 More compact code


 Less boiler plate code
 More readable and reusable code
 More testable code
 Parallel operations

3) What is lambda expression?


Lambda expression is anonymous function which have set of parameters and a lambda (->) and a function body .You can call it
function without name.

Structure of Lambda Expressions


1

2 (Argument List) ->{expression;} or

3 (Argument List) ->{statements;}

Let see a simple example of thread execution:


1

2 public class ThreadSample {


3

4 public static void main(String[] args) {

6 // old way

7 new Thread(new Runnable() {

9 @Override

10 public void run() {

11 System.out.println("Thread is started");

12 }

13 }).start();

14

15 // using lambda Expression

16 new Thread(()->System.out.println("Thread is started")).start();

17 }

18

19 }

20

You can refer to lambda expression in java for more details.

4) Can you explain the syntax of Lambda expression?


So we can divide structure of Lambda expression to three parts:
1. Argument list or parameters

Lambda expression can have zero or more arguments.


1

2 ()->{System.out.println("Hello")}; //Without argument, will print hello

3 (int a)->{System.out.println(a)} //; One argument, will print value of a

4 (int a,int b)-> {a+b};//two argument, will return sum of these two integers

You can choose to not declare type of arguments as it can be inferred from context.
1

2 (a,b)->{a+b};//two argument, will return sum of these two numbers

you can not declare one argument’s type and do not declare type for other argument.
1

2 (int a,b)->{a+b};//Compilation error

When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses
1

2 a->{System.out.println(a)}; // Will print value of number a

2. Array token (->)

3. Body

 Body can have expression or statements.


 If there is only one statement in body,curly brace is not needed and return type of the anonymous function is same as
of body expression
 If there are more than one statements, then it should be in curly braces and return type of anonymous function is same as
value return from code block, void if nothing is returned.

5) What are functional interfaces?


Functional interfaces are those interfaces which can have only one abstract method.It can have static method, default methods
or can override Object’s class methods.

There are many functional interfaces already present in java such as Comparable, Runnable.

As we have only one method in Runnable, hence it is considered as functional interface.

You can read more about the functional interface.


6) How lambda expression and functional interfaces are related?
Lambda expressions can only be applied to abstract method of functional interface.
For example

Runnable has only one abstract method called run, so it can be used as below:

2 // Using lambda expression

3 Thread t1=new Thread(

4 ()->System.out.println("In Run method")

5 );

Here we are using Thread constructor which takes Runnable as parameter. As you can see we did not specify any function
name here, as Runnable has only one abstract method, java will implicitly create anonymous Runnable and execute run method.
It will be as good as below code.

2 Thread t1=new Thread(new Runnable() {

3 @Override

4 public void run() {

5 System.out.println("In Run method");

6 }
7 });

7) Can you create your own functional interface?


Yes, you can create your own functional interface. Java can implicitly identify functional interface but you can also annotate it
with @FunctionalInterface.
Example:
Create interface named "Printable" as below

2 package org.arpit.java2blog;

4 public interface Printable {

6 void print();

7 default void printColor()

8 {

9 System.out.println("Printing Color copy");

10 }

11 }

12

Create main class named "FunctionalIntefaceMain"


1

2 package org.arpit.java2blog.constructor;

4 public class FunctionalIntefaceMain {

6 public static void main(String[] args)

7 {

8 FunctionalIntefaceMain pMain=new FunctionalIntefaceMain();

9 pMain.printForm(() -> System.out.println("Printing form"));

10 }

11

12 public void printForm(Printable p)

13 {

14 p.print();

15 }

16 }

17

When you run above program, you will get below output:

Printing form

As you can see, since Printable has only one abstract method called print(), we were able to call it using lambda expression.
8) What is method reference in java 8?
Method reference is used refer method of functional interface. It is nothing but compact way of lambda expression.You can
simply replace lambda expression with method reference.
Syntax:
class::methodname

9) What is Optional? Why and how can you use it?


Java 8 has introduced new class Called Optional. This class is basically introduced to avoid NullPointerException in java.
Optional class encapsulates optional value which is either present or not.
It is a wrapper around object and can be use to avoid NullPointerExceptions.
Let’s take a simple example

You have written below function to get first non repeated character in String.

2 public static Character getNonRepeatedCharacter(String str) {

3 Map<Character, Integer> countCharacters = new LinkedHashMap<Character, Integer>();

4 for (int i = 0; i < str.length() - 1; i++) {

5 Character c = str.charAt(i);

6 if (!countCharacters.containsKey(c)) {

7 countCharacters.put(c, 1);

8 } else {
9 countCharacters.put(c, countCharacters.get(c) + 1);

10 }

11 }

12 // As LinkedHashMap maintains insertion order, first character with

13 // count 1 should return first non repeated character

14 for (Entry<Character, Integer> e : countCharacters.entrySet()) {

15 if (e.getValue() == 1)

16 return e.getKey();

17

18 }

19 return null;

20

21 }

22

You call above method as below.

2 Character c=getNonRepeatedCharacter("SASAS");

3 System.out.println("Non repeated character is :"+c.toString());

Do you see the problem, there is no non repeating character for getNonRepeatedCharacter("SASAS") hence it will return null
and we are calling c.toString, so it will obviously throw NullPointerException.
You can use Optional to avoid this NullPointerException.
Let’s change the method to return Optional object rather than String.

2 public static Optional<Character> getNonRepeatedCharacterOpt(String str) {

3 Map<Character, Integer> countCharacters = new LinkedHashMap<Character, Integer>();

4 for (int i = 0; i < str.length() - 1; i++) {

5 Character c = str.charAt(i);

6 if (!countCharacters.containsKey(c)) {

7 countCharacters.put(c, 1);

8 } else {

9 countCharacters.put(c, countCharacters.get(c) + 1);

10 }

11 }

12 // As LinkedHashMap maintains insertion order, first character with

13 // count 1 should return first non repeated character

14 for (Entry<Character, Integer> e : countCharacters.entrySet()) {

15 if (e.getValue() == 1)

16 return Optional.of(e.getKey());

17

18 }

19 return Optional.ofNullable(null);

20
21 }

22

When above method returned Optional, you are already aware that it can return null value too.
You can call Optional’s isPresent method to check if there is any value wrapped in Optional.

2 Optional<Character> opCh=getNonRepeatedCharacterOpt("SASAS");

3 if(opCh.isPresent())

4 System.out.println("Non repeated character is :"+opCh.toString());

5 else

6 {

7 System.out.println("No non repeated character found in String");

8 }

If there is no value present in Optional, it will simply print "No non repeated character found in String".

10) What are defaults methods?


Default method are those methods in interface which have body and use default keywords.Default method are introduced in
Java 8 mainly because of backward compatibility.
You can refer to default method in java for more details.
11) What is the difference between Predicate and Function?
Both are functional interfaces.
Predicate<T> is single argument function and either it returns true or false.This can be used as the assignment target for a
lambda expression or method reference.

Function<T,R> is also single argument function but it returns an Object.Here T denotes type of input to the function and R
denotes type of Result.

This can also be used as the assignment target for a lambda expression or method reference.

12) Are you aware of Date and Time API introduced in Java 8? What the issues with Old
Date and time API?
Issues with old Date and TIme API:

Thread Safety: You might be already aware that java.util.Date is mutable and not thread safe. Even java.text.SimpleDateFormat
is also not Thread-Safe. New Java 8 date and time APIs are thread safe.

Performance: Java 8 ‘s new APIs are better in performance than old Java APIs.

More Readable: Old APIs such Calendar and Date are poorly designed and hard to understand. Java 8 Date and Time APIs are
easy to understand and comply with ISO standards.
13) Can you provide some APIs of Java 8 Date and TIme?
LocalDate, LocalTime, and LocalDateTime are the Core API classes for Java 8. As the name suggests, these classes are local
to context of observer. It denotes current date and time in context of Observer.

14) How will you get current date and time using Java 8 Date and TIme API?
You can simply use now method of LocalDate to get today’s date.

2 LocalDate currentDate = LocalDate.now();

3 System.out.println(currentDate);

It will give you output in below format:

2017-09-09

You can use now method of LocalTime to get current time.

2 LocalTime currentTime = LocalTime.now();

3 System.out.println(currentTime);

4
It will give you output in below format:

23:17:51.817

15) Do we have PermGen in Java 8? Are you aware of MetaSpace?


Until Java 7, JVM used an area called PermGen to store classes. It got removed in Java 8 and replaced by MetaSpace.
Major advantage of MetaSpace over permgen:
PermGen was fixed in term of mazimum size and can not grow dynamically but Metaspace can grow dynamically and do not
have any size constraint.

Next 7 questions will be based on below class.

2 package org.arpit.java2blog;

4 public class Employee {

5 private String name;

6 private int age;

8 public Employee(String name, int age) {

9 super();
10 this.name = name;

11 this.age = age;

12 }

13 public String getName() {

14 return name;

15 }

16 public void setName(String name) {

17 this.name = name;

18 }

19 public int getAge() {

20 return age;

21 }

22 public void setAge(int age) {

23 this.age = age;

24 }

25 public String toString()

26 {

27 return "Employee Name: "+name+" age: "+age;

28 }

29 }

30
16) Given a list of employees, you need to filter all the employee whose age is greater
than 20 and print the employee names.(Java 8 APIs only)

Answer:
You can simply do it using below statement.

2 List<String> employeeFilteredList = employeeList.stream()

3 .filter(e->e.getAge()>20)

4 .map(Employee::getName)

5 .collect(Collectors.toList());

Complete main program for above logic.

2 package org.arpit.java2blog;

4 import java.util.ArrayList;

5 import java.util.List;

6 import java.util.stream.Collectors;

7
8 public class MaximumUsingStreamMain {

9 public static void main(String args[])

10 {

11 List<Employee> employeeList = createEmployeeList();

12 List<String> employeeFilteredList = employeeList.stream()

13 .filter(e->e.getAge()>20)

14 .map(Employee::getName)

15 .collect(Collectors.toList());

16

17 employeeFilteredList.forEach((name)-> System.out.println(name));

18

19 }

20

21 public static List<Employee> createEmployeeList()

22 {

23 List<Employee> employeeList=new ArrayList<>();

24

25 Employee e1=new Employee("John",21);

26 Employee e2=new Employee("Martin",19);

27 Employee e3=new Employee("Mary",31);

28 Employee e4=new Employee("Stephan",18);

29 Employee e5=new Employee("Gary",26);

30
31 employeeList.add(e1);

32 employeeList.add(e2);

33 employeeList.add(e3);

34 employeeList.add(e4);

35 employeeList.add(e5);

36

37 return employeeList;

38 }

39 }

40

17) Given the list of employees, count number of employees with age 25?

Answer:
You can use combination of filter and count to find this.

2 List<Employee> employeeList = createEmployeeList();

3 long count = employeeList.stream()

4 .filter(e->e.getAge()>25)

5 .count();
6 System.out.println("Number of employees with age 25 are : "+count);

18) Given the list of employees, find the employee with name “Mary”.

Answer:
It is again very simple logic, change the main function in above class as following.

2 List<Employee> employeeList = createEmployeeList();

3 Optional<Employee> e1 = employeeList.stream()

4 .filter(e->e.getName().equalsIgnoreCase("Mary")).findAny();

6 if(e1.isPresent())

7 System.out.println(e1.get());

19)Given a list of employee, find maximum age of employee?


Answer:
It is again very simple logic, change the main function in above class as following.

2 List<Employee> employeeList = createEmployeeList();

3 OptionalInt max = employeeList.stream().

4 mapToInt(Employee::getAge).max();

6 if(max.isPresent())

7 System.out.println("Maximum age of Employee: "+max.getAsInt());

20) Given a list of employees, sort all the employee on the basis of age? Use java 8 APIs
only

You can simply use sort method of list to sort the list of employees.

2 List<Employee> employeeList = createEmployeeList();

3 employeeList.sort((e1,e2)->e1.getAge()-e2.getAge());
4 employeeList.forEach(System.out::println);

21) Join the all employee names with “,” using java 8?

Answer:

2 List<Employee> employeeList = createEmployeeList();

3 List<String> employeeNames = employeeList

4 .stream()

5 .map(Employee::getName)

6 .collect(Collectors.toList());

7 String employeeNamesStr = String.join(",", employeeNames);

8 System.out.println("Employees are: "+employeeNamesStr);

Output:

Employees are: John,Martin,Mary,Stephan,Gary


22) Given the list of employee, group them by employee name?

Answer:
You can use Collections.groupBy() to group list of employees by employee name.

2 package org.arpit.java2blog;

4 import java.util.ArrayList;

5 import java.util.List;

6 import java.util.Map;

7 import java.util.stream.Collectors;

9 public class MaximumUsingStreamMain {

10 public static void main(String args[])

11 {

12 List<Employee> employeeList = createEmployeeList();

13 Map<String, List<Employee>> map = employeeList.stream()

14 .collect(Collectors.groupingBy(Employee::getName));

15 map.forEach((name,employeeListTemp)->System.out.println("Name: "+name+" ==>"+employeeListTemp));

16 }

17
18 public static List<Employee> createEmployeeList()

19 {

20 List<Employee> employeeList=new ArrayList<>();

21

22 Employee e1=new Employee("John",21);

23 Employee e2=new Employee("Martin",19);

24 Employee e3=new Employee("Mary",31);

25 Employee e4=new Employee("Mary",18);

26 Employee e5=new Employee("John",26);

27

28 employeeList.add(e1);

29 employeeList.add(e2);

30 employeeList.add(e3);

31 employeeList.add(e4);

32 employeeList.add(e5);

33

34 return employeeList;

35 }

36 }

37

Output:
Name: John ==>[Employee Name: John age: 21, Employee Name: John age: 26] Name: Martin ==>[Employee Name: Martin
age: 19] Name: Mary ==>[Employee Name: Mary age: 31, Employee Name: Mary age: 18]

23) Difference between Intermediate and terminal operations in Stream?

Answer:
Java 8 Stream supports both intermediate and terminal operation.

Intermediate operations are lazy in nature and do not get executed immediately. Terminal operations are not lazy, they are
executed as soon as encountered. Intermediate operation is memorized and is called when terminal operation is called.

All Intermediate operations return stream as it just transforms stream into another and terminal operation don’t.

Example of Intermediate operations are:

filter(Predicate)
map(Function)
flatmap(Function)
sorted(Comparator)
distinct()
limit(long n)
skip(long n)
Example of terminal operations are :

forEach
toArray
reduce
collect
min
max
count
anyMatch
allMatch
noneMatch
findFirst
findAny

24) Given the list of numbers, remove the duplicate elements from the list.

Answer:
You can simply use stream and then collect it to set using Collections.toSet() method.

2 package org.arpit.java2blog;

3
4 import java.util.Arrays;

5 import java.util.List;

6 import java.util.Set;

7 import java.util.stream.Collectors;

9 public class RemoveDuplicatesFromListMain {

10 public static void main(String[] args)

11 {

12 Integer[] arr=new Integer[]{1,2,3,4,3,2,4,2};

13 List<Integer> listWithDuplicates = Arrays.asList(arr);

14

15 Set<Integer> setWithoutDups = listWithDuplicates.stream().collect(Collectors.toSet());

16 setWithoutDups.forEach((i)->System.out.print(" "+i));

17 }

18 }

19

You can use distinct as well to avoid duplicates as following.


change main method of above program as below.

2 Integer[] arr=new Integer[]{1,2,3,4,3,2,4,2};

3 List<Integer> listWithDuplicates = Arrays.asList(arr);


4 List<Integer> listWithoutDups = listWithDuplicates.stream().distinct().collect(Collectors.toList());

5 listWithoutDups.forEach((i)->System.out.print(" "+i));

25) Difference between Stream’s findFirst() and findAny()?

findFirst will always return the first element from the stream whereas findAny is allowed to choose any element from the stream.
findFirst has deterministic behavior whereas findAny is nondeterministic behavior.

26) Given a list of numbers, square them and filter the numbers which are greater 10000
and then find average of them.( Java 8 APIs only)

Answer:
You can use the map function to square the number and then filter to avoid numbers which are less than 10000.We will use
average as terminating function in this case.

2 package org.arpit.java2blog;
3

4 import java.util.Arrays;

5 import java.util.List;

6 import java.util.OptionalDouble;

8 public class RemoveDuplicatesFromListMain {

9 public static void main(String[] args)

10 {

11 Integer[] arr=new Integer[]{100,24,13,44,114,200,40,112};

12 List<Integer> list = Arrays.asList(arr);

13 OptionalDouble average = list.stream()

14 .mapToInt(n->n*n)

15 .filter(n->n>10000)

16 .average();

17

18 if(average.isPresent())

19 System.out.println(average.getAsDouble());

20

21 }

22 }

23

output:
21846.666666666668

27) What is use of Optional in Java 8?

Answer:
Java 8 optional can be used to avoid NullPointerException.You can read about the detailed tutorial.

Read Java 8 optional

28) What is predicate function interface?


Answer:
Predicate is single argument function which returns true or false. It has test method which returns boolean.
When we are using filter in above example, we are actually passing Predicate functional interface to it.

Read Java 8 predicate


29) What is consumer function interface?

Answer:
Consumer is single argument functional interface which does not return any value.
When we are using foreach in above example, we are actually passing Consumer functional interface to it.

Read Java 8 consumer

30) What is supplier function interface?

Answer:
Supplier is function interface which does not take any parameter but returns the value using get method.

Basic Java Interview Questions


Q1. Explain JDK, JRE and JVM?
JDK vs JRE vs JVM

JDK JRE JVM

It stands for Java Runtime


It stands for Java Development Kit. It stands for Java Virtual Machine.
Environment.

It is the tool necessary to compile, JRE refers to a runtime It is an abstract machine. It is a specification
document and package Java environment in which Java that provides a run-time environment in
programs. bytecode can be executed. which Java bytecode can be executed.

JVM follows three notations:


It contains JRE + development It’s an implementation of the JVM
Specification, Implementation, and Runtime
tools. which physically exists.
Instance.

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

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?

ArrayList Vector

Array List is not synchronized. Vector is synchronized.

Array List is fast as it’s non-synchronized. Vector is slow as it is thread safe.


If an element is inserted into the Array List, it increases its Array size by 50%. Vector defaults to doubling size of its array.

Array List does not define the increment size. Vector defines the increment size.

Array List can only use Iterator for traversing an Array List. Vector can use both Enumeration and Iterator for traversing.

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. What are the differences between Heap and Stack Memory in Java?

The major difference between Heap and Stack memory are:

Features Stack Heap

Memory Stack memory is used only by one thread of execution. Heap memory is used by all the parts of the application.

Access Stack memory can’t be accessed by other threads. Objects stored in the heap are globally accessible.

Memory Memory management is based on the generation associated with each


Follows LIFO manner to free memory.
Management object.

Lifetime Exists until the end of execution of the thread. Heap memory lives from the start till the end of application execution.

Stack memory only contains local primitive and reference variables


Usage Whenever an object is created, it’s always stored in the Heap space.
to objects in heap space.
Q11. 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

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

Q13. What is JIT compiler in Java?

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.

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

Modifier Default Private Protected Public


Same class YES YES YES YES

Same Package subclass YES NO YES YES

Same Package non-subclass YES NO YES YES

Different package subclass NO NO YES YES

Different package non-subclass NO NO NO YES

Q15. Define a Java Class.

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}

Q16. 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();

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

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

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

class Test{
1
public String EmpName;
2
public int empAge;
3 }

Q20. Differentiate between the constructors and methods in Java?

Methods Constructors

1. Used to represent the behavior of an object 1. Used to initialize the state of an object

2. Must have a return type 2. Do not have any return type

3. Needs to be invoked explicitly 3. Is invoked implicitly

4. No default method is provided by the compiler 4. A default constructor is provided by the compiler if the class has none

5. Method name may or may not be same as class name 5. Constructor name must always be the same as the class name

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

Q21. 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.
Q22. What is the difference between break and continue statements?

break continue

1. Can be used in switch and loop (for, while, do while) statements 1. Can be only used with loop statements

2. It causes the switch or loop statements to terminate the moment it


2. It doesn’t terminate the loop but causes the loop to jump to the next iteration
is executed

3. A continue within a loop nested with a switch will cause the next loop iteration to
3. It terminates the innermost enclosing loop or switch immediately
execute

Example break:

1
for (int i = 0; i < 5; i++)
2 {

3 if (i == 3)

4 {

5 break;

6 }

System.out.println(i);
7
}
8

Example continue:

1 for (int i = 0; i < 5; i++)

2 {

3 if(i == 2)
4 {

5 continue;

}
6
System.out.println(i);
7
}
8

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

Q24. 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.
this() super()

1. this() represents the current instance of a class 1. super() represents the current instance of a parent/base class

2. Used to call the default constructor of the same class 2. Used to call the default constructor of the parent/base class

3. Used to access methods of the current class 3. Used to access methods of the base class

4. Used for pointing the current class instance 4. Used for pointing the superclass instance

5. Must be the first line of a block 5. Must be the first line of a block

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

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


Static Method Non-Static Method

1. The static keyword must be used before the method name 1. No need to use the static keyword before the method name

2. It is called using the class (className.methodName) 2. It is can be called like any general method

3. It can access any static method and any static variable without creating an instance
3. They can’t access any non-static instance variables or methods
of the class

Q27. 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()

Q28. Difference between String, StringBuilder, and StringBuffer.

Factor String StringBuilder StringBuffer

Storage Area Constant String Pool Heap Area Heap Area

Mutability Immutable Mutable Mutable

Thread Safety Yes No Yes

Performance Fast More efficient Less efficient

If you think this article on Java Interview Questions is helpful, you can check out Edureka’s Java Online Training as well.

Q29. 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:
1. Bootstrap ClassLoader
2. Extension ClassLoader
3. System/Application ClassLoader

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

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

Array ArrayList

Cannot contain values of different data types Can contain values of different data types.

Size must be defined at the time of declaration Size can be dynamically changed

Need to specify the index in order to add data No need to specify the index

Arrays are not type parameterized Arraylists are type

Arrays can contain primitive data types as well as objects Arraylists can contain only objects, no primitive data types are allowed

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


2. Each key can map at max one value.

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

In case you are facing any challenges with these java interview questions, please comment on your problems in the section below.
OOPS Java Interview Questions
Q1. What is Polymorphism?

Polymorphism is briefly described as “one interface, many implementations”. Polymorphism is a characteristic of being able to assign a different
meaning or usage to something in different contexts – specifically, to allow an entity such as a variable, a function, or an object to have more

than one form. There are two types of polymorphism:

1. Compile time polymorphism


2. Run time polymorphism

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

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.

class Car {
1
void run()
2
{
3
System.out.println(“car is running”);
4
}
5 }

6 class Audi extends Car {

void run()
7
{
8
System.out.prinltn(“Audi is running safely with 100km”);
9
}
10
public static void main(String args[])
11
{
12 Car b= new Audi(); //upcasting

13 b.run();

14 }

15 }

16

17

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?

Abstract Class Interfaces

An abstract class can provide complete, default code and/or just the details that
An interface cannot provide any code at all, just the signature
have to be overridden

In the case of an abstract class, a class may extend only one abstract class A Class may implement several interfaces

An abstract class can have non-abstract methods All methods of an Interface are abstract

An abstract class can have instance variables An Interface cannot have instance variables

An abstract class can have any visibility: public, private, protected An Interface visibility must be public (or) none

If we add a new method to an abstract class then we have the option of providing If we add a new method to an Interface then we have to track down all the
default implementation and therefore all the existing code might work properly implementations of the interface and define implementation for the new method

An abstract class can contain constructors An Interface cannot contain constructors

Interfaces are slow as it requires extra indirection to find the corresponding method in
Abstract classes are fast
the actual class
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
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 class Adder {

2 Static int add(int a, int b)


3 {

4 return a+b;

}
5
Static double add( double a, double b)
6
{
7
return a+b;
8
}
9
public static void main(String args[])
10 {

11 System.out.println(Adder.add(11,11));

12 System.out.println(Adder.add(12.3,12.6));

13 }}

14

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.

Explore Curriculum
1
class Car {
2
void run(){
3
System.out.println(“car is running”);
4
}
5
Class Audi extends Car{
6 void run()

7 {

8 System.out.prinltn("Audi is running safely with 100km");

9 }

public static void main( String args[])


10
{
11
Car b=new Audi();
12
b.run();
13
}
14
}
15

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 class Base {
2 private static void display() {

3 System.out.println("Static or class method from Base");

}
4
public void print() {
5
System.out.println("Non-static or instance method from Base");
6
}
7
class Derived extends Base {
8
private static void display() {
9 System.out.println("Static or class method from Derived");

10 }

11 public void print() {

12 System.out.println("Non-static or instance method from Derived");

}
13
public class test {
14
public static void main(String args[])
15
{
16
Base obj= new Derived();
17
obj1.display();
18
obj1.print();

19 }

20 }

21
22

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.

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 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 public interface Serializable{

2 }

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 the number of parameters and their types in the list to differentiate the overloaded constructors.

1
class Demo
2
{
3
int i;
4 public Demo(int a)

5 {

6 i=k;

7 }

8 public Demo(int a, int b)

{
9
//body
10
}
11
}
12

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!
Spring Framework – Java Interview Questions
Q1. What is Spring?

Wikipedia defines the Spring framework as “an application framework and inversion of control container for the Java platform. The framework’s
core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform.” Spring
is essentially a lightweight, integrated framework that can be used for developing enterprise applications in java.

Q2. Name the different modules of the Spring framework.

Some of the important Spring Framework modules are:

 Spring Context – for dependency injection.


 Spring AOP – for aspect oriented programming.
 Spring DAO – for database operations using DAO pattern
 Spring JDBC – for JDBC and DataSource support.
 Spring ORM – for ORM tools support such as Hibernate
 Spring Web Module – for creating web applications.
 Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.
Q3. List some of the important annotations in annotation-based Spring configuration.

The important annotations are:

 @Required
 @Autowired
 @Qualifier
 @Resource
 @PostConstruct
 @PreDestroy

Q4. Explain Bean in Spring and List the different Scopes of Spring bean.

Beans are objects that form the backbone of a Spring application. They are managed by the Spring IoC container. In other words, a bean is an
object that is instantiated, assembled, and managed by a Spring IoC container.

There are five Scopes defined in Spring beans.


 Singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope,
make sure spring bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues because it’s not thread-safe.
 Prototype: A new instance will be created every time the bean is requested.
 Request: This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each
HTTP request.
 Session: A new bean will be created for each HTTP session by the container.
 Global-session: This is used to create global session beans for Portlet applications.

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

Q5. Explain the role of DispatcherServlet and ContextLoaderListener.

DispatcherServlet is basically the front controller in the Spring MVC application as it loads the spring bean configuration file and initializes all the
beans that have been configured. If annotations are enabled, it also scans the packages to configure any bean annotated with @Component,
@Controller, @Repository or @Service annotations.
ContextLoaderListener, on the other hand, is the listener to start up and shut down the WebApplicationContext in Spring root. Some of its
important functions includes tying up the lifecycle of Application Context to the lifecycle of the ServletContext and automating the creation of
ApplicationContext.

Q6. What are the differences between constructor injection and setter injection?

No. Constructor Injection Setter Injection

1) No Partial Injection Partial Injection

2) Doesn’t override the setter property Overrides the constructor property if both are defined.

Doesn’t create a new instance if you change the property


3) Creates a new instance if any modification occurs
value

4) Better for too many properties Better for a few properties.

Q7. What is autowiring in Spring? What are the autowiring modes?

Autowiring enables the programmer to inject the bean automatically. We don’t need to write explicit injection logic. Let’s see the code to inject
bean using dependency injection.

1. <bean id=“emp” class=“com.javatpoint.Employee” autowire=“byName” />


The autowiring modes are given below:

No. Mode Description

1) no this is the default mode, it means autowiring is not enabled.

2) byName Injects the bean based on the property name. It uses setter method.

3) byType Injects the bean based on the property type. It uses setter method.

4) constructor It injects the bean using constructor

Q8. How to handle exceptions in Spring MVC Framework?

Spring MVC Framework provides the following ways to help us achieving robust exception handling.

Controller Based:
We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler
annotation.

Global Exception Handler:


Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our
global exception handler.

HandlerExceptionResolver implementation:
For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can
implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework
also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling
benefits.

Q9. What are some of the important Spring annotations which you have used?

Some of the Spring annotations that I have used in my project are:

@Controller – for controller classes in Spring MVC project.


@RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation, so you should go through
Spring MVC RequestMapping Annotation Examples

@ResponseBody – for sending Object as response, usually for sending XML or JSON data as response.

@PathVariable – for mapping dynamic values from the URI to handler method arguments.

@Autowired – for autowiring dependencies in spring beans.

@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.

@Service – for service classes.

@Scope – for configuring the scope of the spring bean.

@Configuration, @ComponentScan and @Bean – for java based configurations.

AspectJ annotations for configuring aspects and advices , @Aspect, @Before, @After, @Around, @Pointcut, etc.

Q10. How to integrate Spring and Hibernate Frameworks?

We can use Spring ORM module to integrate Spring and Hibernate frameworks if you are using Hibernate 3+ where SessionFactory provides
current session, then you should avoid using HibernateTemplate or HibernateDaoSupport classes and better to use DAO pattern with
dependency injection for the integration.

Also, Spring ORM provides support for using Spring declarative transaction management, so you should utilize that rather than going for
hibernate boiler-plate code for transaction management.

Q11. Name the types of transaction management that Spring supports.

Two types of transaction management are supported by Spring. They are:

1. Programmatic transaction management: In this, the transaction is managed with the help of programming. It provides you extreme flexibility, but it is
very difficult to maintain.
2. Declarative transaction management: In this, transaction management is separated from the business code. Only annotations or XML based
configurations are used to manage the transactions.
In case you are facing any challenges with these java interview questions, please comment 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 structured training from edureka!

Hibernate – Java Interview Questions


1. What is Hibernate Framework?

Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables.
Hibernate is Java-based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice
versa.

Hibernate provides a reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose
coupling. We can use the Hibernate persistence API for CRUD operations. Hibernate framework provide option to map plain old java objects to
traditional database tables with the use of JPA annotations as well as XML based configuration.

Similarly, hibernate configurations are flexible and can be done from XML configuration file as well as programmatically.

2. What are the important benefits of using Hibernate Framework?

Some of the important benefits of using hibernate framework are:

1. Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
2. Hibernate framework provides support for XML as well as JPA annotations, that makes our code implementation independent.
3. Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like
inheritance, polymorphism, and association.
4. Hibernate is an open source project from Red Hat Community and used worldwide. This makes it a better choice than others because learning curve is
small and there are tons of online documentation and help is easily available in forums.
5. Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating hibernate
with Spring applications.
6. Hibernate supports lazy initialization using proxy objects and perform actual database queries only when it’s required.
7. Hibernate cache helps us in getting better performance.
8. For database vendor specific feature, hibernate is suitable because we can also execute native sql queries.

Overall hibernate is the best choice in current market for ORM tool, it contains all the features that you will ever need in an ORM tool.
3. Explain Hibernate architecture.

Hibernate has a layered architecture which helps the user to operate without having to know the underlying APIs. Hibernate makes use of the
database and configuration data to provide persistence services (and persistent objects) to the application. It includes many objects such as
persistent object, session factory, transaction factory, connection factory, session, transaction etc.

The Hibernate architecture is categorized in four layers.

 Java application layer


 Hibernate framework layer
 Backhand API layer
 Database layer

4. What are the differences between get and load methods?


The differences between get() and load() methods are given below.

No. get() load()

1) Returns null if object is not found. Throws ObjectNotFoundException if an object is not found.

2) get() method always hit the database. load() method doesn’t hit the database.

3) It returns a real object, not a proxy. It returns a proxy object.

It should be used if you are not sure about the


4) It should be used if you are sure that the instance exists.
existence of instance.

5. What are the advantages of Hibernate over JDBC?

Some of the important advantages of Hibernate framework over JDBC are:

1. Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks cleaner and readable.
2. Hibernate supports inheritance, associations, and collections. These features are not present with JDBC API.
3. Hibernate implicitly provides transaction management, in fact, most of the queries can’t be executed outside transaction. In JDBC API, we need to
write code for transaction management using commit and rollback.
4. JDBC API throws SQLException that is a checked exception, so we need to write a lot of try-catch block code. Most of the times it’s redundant in every
JDBC call and used for transaction management. Hibernate wraps JDBC exceptions and throw JDBCException or HibernateException un-checked
exception, so we don’t need to write code to handle it. Hibernate built-in transaction management removes the usage of try-catch blocks.
5. Hibernate Query Language (HQL) is more object-oriented and close to Java programming language. For JDBC, we need to write native SQL queries.
6. Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
7. Hibernate provides option through which we can create database tables too, for JDBC tables must exist in the database.
8. Hibernate configuration helps us in using JDBC like connection as well as JNDI DataSource for the connection pool. This is a very important feature in
enterprise application and completely missing in JDBC API.
9. Hibernate supports JPA annotations, so the code is independent of the implementation and easily replaceable with other ORM tools. JDBC code is
very tightly coupled with the application.

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 structured training from
edureka!
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.
 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 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 class FinalVarExample {

2 public static void main( String args[])

3 {

4 final int a=10; // Final variable

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

}
6

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.

1 class FinallyExample {

2 public static void main(String args[]){

try {
3
int x=100;
4
}
5
catch(Exception e) {
6
System.out.println(e);
7
}
8 finally {

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

10 }}
11 }

12

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
class FinalizeExample {
2
public void finalize() {
3
System.out.println("Finalize is called");
4
}
5 public static void main(String args[])

6 {

7 FinalizeExample f1=new FinalizeExample();

8 FinalizeExample f2=new FinalizeExample();

f1= NULL;
9
f2=NULL;
10
System.gc();
11
}
12
}
13

Q5. What are the differences between throw and throws?

throw keyword throws keyword

Throw is used to explicitly throw an exception. Throws is used to declare an exception.


Checked exceptions can not be propagated with
Checked exception can be propagated with throws.
throw only.

Throw is followed by an instance. Throws is followed by class.

Throw is used within the method. Throws is used with the method signature.

You can declare multiple exception e.g. public void method()throws


You cannot throw multiple exception
IOException,SQLException.

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

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

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

Q9. What are the differences between processes and threads?

Process Thread

An executing instance of a program is


Definition A thread is a subset of the process.
called a process.

Processes must use inter-process


Threads can directly communicate with other threads
Communication communication to communicate with
of its process.
sibling processes.

Processes can only exercise control over Threads can exercise considerable control over
Control
child processes. threads of the same process.

Changes Any change in the parent process does Any change in the main thread may affect the
not affect child processes. behavior of the other threads of the process.

Memory Run in separate memory spaces. Run in shared memory spaces.

Process is controlled by the operating


Controlled by Threads are controlled by programmer in a program.
system.

Dependence Processes are independent. Threads are dependent.

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

Q11. 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 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.
Q12. 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 public class Example {

public static void main(String args[]) {


2
try {
3
int a[]= new int[10];
4
a[10]= 10/0;
5
}
6
catch(ArithmeticException e)
7 {

8 System.out.println("Arithmetic exception in first catch block");

9 }

10 catch(ArrayIndexOutOfBoundsException e)

{
11
System.out.println("Array index out of bounds in second catch block");
12
}
13
catch(Exception e)
14
{
15
System.out.println("Any exception in third catch block");
16 }

17 }
18

19

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

Q14. What is OutOfMemoryError in Java?

OutOfMemoryError is the subclass of java.lang.Error which generally occurs when our JVM runs out of memory.

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

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

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

--------------------------------------------------------------------------------------------------------------------------------

17 Java Overview Interview Q&As


Posted on July 1, 2017

Q1. Why use Java?


A1. One needs to use the best tool for the job, whether that tool is Java or not. When choosing a technology to solve your business problems, you
need to consider many factors like development cost, infrastructure cost, ongoing support cost, robustness, flexibility, security, performance, etc.
— Java provides client technologies, server technologies, and integration technologies to solve small scale to very large scale business
problems.
— Firstly, Java is a proven and matured technology used in many mission critical projects, and there are millions of developers world wide,
thousands of frameworks, tools, and libraries for it, and millions of sites, blogs, and books to find relevant information.
— The emergence of open-source technologies has truly made Java a powerful competitor in the server and integration technology space. You can
always find a proven framework that best solves your business problems.

— The platform also comes with a rich set of APIs. This means developers spend less time writing support libraries, and more time developing
content for their applications.

— Built-in support for multi-threading, socket communication, and automatic memory management (i.e. automatic garbage collection).

Q2. Is Java a 100% Object Oriented (OO) language? if yes why? and if no, why not?
A2. I would say Java is not 100% object oriented, but it embodies practical OO concepts. There are 6 qualities to make a programming language
to be pure object oriented. They are:
1. Encapsulation – data hiding and modularity.
2. Inheritance – you define new classes and behavior based on existing classes to obtain code reuse.
3. Polymorphism – the same message sent to different objects results in behavior that’s dependent on the nature of the object receiving the
message.
4. All predefined types are objects.
5. All operations are performed by sending messages to objects.
6. All user defined types are objects.
points 1- 3, stands for PIE (Polymorphism, Inheritance, and Encapsulation).
Reason #1: The main reason why Java cannot be considered 100% OO is due to its existence of 8 primitive variables (i.e. violates point number 4)
like int, long, char, float, etc. These data types have been excused from being objects for simplicity and to improve performance. Since primitive
data types are not objects, they don’t have any qualities such as inheritance or polymorphism. Even though Java provides immutable wrapper
classes like Integer, Long, Character, etc representing corresponding primitive data as objects, the fact that it allowed non object oriented primitive
variables to exist, makes it not fully OO.
Reason #2: Another reason why Java is considered not full OO is due to its existence of static methods and variables (i.e. violates point number 5).
Since static methods can be invoked without instantiating an object, we could say that it breaks the rules of encapsulation.
Reason #3: Java does not support multiple class inheritance to solve the diamond problem because different classes may have different variables
with same name that may be contradicted and can cause confusions and result in errors. In Java, any class can extend only one other class, but can
implement multiple interfaces.
We could also argue that Java is not 100% OO according to this point of view. But Java realizes some of the key benefits of multiple inheritance
through its support for multiple interface inheritance and in Java 8, you can have multiple behavior (not state) inheritance as you can have
default methods in interfaces.
Reason #4: Operator overloading is not possible in Java except for string concatenation and addition operations. String concatenation and addition
example,

1 System.out.println(1 + 2 + ”3”);//outputs 33

2 System.out.println(“1” + 2 + 3); //outputs 123

Since this is a kind of polymorphism for other operators like * (multiplication), / (division), or – (subtraction), and Java does not support this, hence
one could debate that Java is not 100% OO. Working with a primitive in Java is more elegant than working with an object like BigDecimal. For
example,
1 int a,b, c;

2 //without operator overloading

3 a=b–c*d

What happens in Java when you have to deal with large decimal numbers that must be accurate and of unlimited size and precision? You must use
a BigDecimal. BigDecimal looks verbose for larger calculations without the operator overloading as shown below:

1 BigDecimal b = new BigDecimal(“25.24”);

2 BigDecimal c = new BigDecimal(“3.99”);

3 BigDecimal d = new BigDecimal(“2.78”);

4 BigDecimal a = b.subtract(c).multiply(d); //verbose and wrong

Also, the last line above is wrong. The rules of precedence have changed. With chained method calls like this, evaluation is strictly left-to-right.
Instead of subtracting the product of c and d from b, we are multiplying the difference between b and c by d. We would have to rewrite the last line
as shown below:
1 BigDecimal a = b.subtract(c.multiply(d)); //correct

So, it is error prone as well. Another point is that the BigDecimal class is immutable and, as such, each of the “operator” methods returns a new
instance. In future Java versions, you may have operator overloading for BigDecimal, and it would make your code more readable as shown below.

1 BigDecimal a = b – (c * d); //much better

Q3. What is the difference between C++ and Java?


A3. Both C++ and Java use similar syntax and are Object Oriented, but:
1) Java does not support pointers. Pointers are inherently tricky to use and troublesome.
2) Java does not support multiple inheritances because it causes more problems than it solves. Instead Java supports multiple interface behavior
inheritance (In Java 8, you can have interfaces with default & static methods, but can’t have state), which allows an object to inherit many method
signatures from different interfaces with the condition that the inheriting object must implement those inherited methods.
3) Java does not support destructors but rather adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming
the memory occupied by the object, which has the finalize() method. This means you do not know when the objects are going to be finalized.
Avoid using finalize() method to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite
number of these resources and you do not know when the garbage collection is going to kick in to release these resources through the finalize()
method.
4) Java does not include structures or unions. Java make use of the Java Collection framework.
5) All the code in Java program is encapsulated within classes therefore Java does not have global variables or functions.
6) C++ requires explicit memory management, while Java includes automatic garbage collection.
Q4. What is the main difference between the Java platform and the other software platforms?
A4. Java platform is a software-only platform, which runs on top of other hardware-based platforms like Unix, Windows, Mac OS, etc.

Java platform

The Java platform has 2 components:

1) Java Virtual Machine (JVM) – ‘JVM’ is a software that can be ported onto various hardware platforms. Byte codes are the machine language of
the JVM.
2) Java Application Programming Interface (Java API) – is nothing but a set of classes and interfaces that come with the JDK. All these classes are
written using the Java language and contains a library of methods for common programming tasks like manipulating strings and data structures,
networking, file transfer, etc. The source *.java files are in the src.zip archive and the executable *.class files are in the rt.jar archive.
Q5. How would you differentiate JDK, JRE, JVM, and JIT?
A5. There is no better way to get the big picture than a diagram.
JDK, JRE, JVM, and JIT
1) JDK: You can download a copy of the Java Development Kit (JDK) for your operating system like Unix, Windows, etc.
2) JRE: Java Runtime Environment is an implementation of the JVM. The JDK typically includes the Java Runtime Environment (JRE) which
contains the virtual machine and other dependencies to run Java applications.
3) JIT: A JIT is a code generator that converts Java byte code into native machine code. Java programs invoked with a JIT generally run much
faster than when the byte code is executed by the interpreter. The JIT compiler is a standard tool that is part of the JVM and invoked whenever you
use the Java interpreter command. You can disable the JIT compiler using the -Djava.compiler=NONE option to the Java VM. You might want to
disable the JIT compiler if you are running the Java VM in remote debug mode, or if you want to see source line numbers instead of the label
(Compiled Code) in your Java stack traces.
Q6. Is it possible to convert byte code into source code?
A6. Yes. A Java decompiler is a computer program capable of reversing the work done by a compiler. In essence, it can convert back the byte
code (i.e. the .class file) into the source code (i.e the .java file). There are many decompilers that exist today, but the most widely used JD – Java
Decompiler is available both as stand-alone GUI program and as an eclipse plug-in.
Q7. When would you use a decompiler?
A7.
1) When you have *.class files and you do not have access to the source code (*.java files). For example, some vendors do not ship the source code
for java class files or you accidentally lost (e.g deleted) your source code, in which case you can use the Java decompiler to reconstruct the source
file.
2) Another scenario is that if you generated your .class files from another language like a groovy script, using the groovyc command, you may want
to use a Java decompiler to inspect the Java source code for the groovy generated class files to debug or get a better understanding of groovy
integration with Java.
3) To ensure that your code is adequately obfuscated before releasing it into the public domain.
4) Fixing and debugging .class files when developers are slow to respond to questions that need immediate answers. To learn both Java and how
the Java VM works.
5) Learn and debug how code with generics has been converted after compilation.
Q8. Is it possible to prevent the conversion from byte code into source code?
A8. If you want to protect your Java class files from being decompiled, you can take a look at a Java obfuscator tool like yGuard or ProGuard,
otherwise you will have to kiss your intellectual property good bye.
Q9. What are the two flavors of JVM?
A9. Client mode and server mode.
Client mode is suited for short lived programs like stand-alone GUI applications and applets. Specially tuned to reduce application start-up time
and memory footprint, making it well suited for client applications. For example: c:\> java -client MyProgram
Server mode is suited for long running server applications, which can be active for weeks or months at a time. Specially tuned to maximize peak
operating speed. The fastest possible operating speed is more important than fast start-up time or smaller runtime memory footprint. c:\> java -
server MyProgram
Q10. How do you know in which mode your JVM is running?
A10. c:\> java -version
Q11. What are the two different bits of JVM? What is the major limitation of 32 bit JVM?
A11. JVMs are available in 32 bits (-d32 JVM argument) and 64 bits (-d64 JVM argument). 64-bit JVMs are typically only available from JDK
5.0 onwards. It is recommended that the 32-bit be used as the default JVM and 64-bit used if more memory is needed than what can be allocated to
a 32-bit JVM. The Oracle Java VM cannot grow beyond ~2GB on a 32bit server machine even if you install more than 2GB of RAM into your
server. It is recommended that a 64bit OS with larger memory hardware is used when larger heap sizes are required. For example, >4GB is
assigned to the JVM and used for deployments of >250 concurrent or >2500 casual users.
Q12. What are some of the JVM arguments you have used in your projects?
A12. To set a system property that can be retrieved using System.getPropety(“name”);

1 $java -Dname=value MyApp

To set the classpath: -cp or -classpath

1 $java -cp library.jar MyApp


To set minimum and maximum heap sizes:

1 $java -Xms1024 -Xmx1024 MyApp

To set garbage collection options:

1 $ java -Xincgc MyApp

Q13. How do you monitor the JVMs?


A13. Since Java SE 5.0, the JRE provides a mean to manage and monitor the Java Virtual Machine. It comes in two flavors:
JVM Monitoring
1) The JVM has built-in instrumentation that enables you to monitor and manage it using Java Management eXtension (JMX). You can also
monitor instrumented applications with JMX. To start a Java application with the management agent for local monitoring, set the following JVM
argument when you run your application.

1 $JAVA_HOME/bin/java -Dcom.sun.management.jmxremote MyApp

2
To start the JConsole:

1 $JAVA_HOME/bin/jconsole

2) The other is a Simple Network Management Protocol (SNMP) agent that builds upon the management and monitoring API of the Java SE
platform, and exposes the same information through SNMP. SNMP events can be sent Splunk. Nagios, Zenoss, OpenNMS, and netsnmp are some
of the popular SNMP tools.
Q14. What is a jar file? How does it differ from a zip file?
A14. The jar stands for Java ARchive. A jar file usually has a file name extension .jar. It mainly contains Java class files but any types of files
can be included. For example, XML files, properties files, HTML files, image files, binary files, etc. You can use the “jar” application utility
bundled inside /JDK1.6.0/jre/bin to create, extract, and view its contents. You can also use any zip file utility program to view its contents. A jar
file cannot contain other jar files., whereas a war or ear file used in Java EE.

Basically, a jar file is same as a zip file, except that it contains a META-INF directory to store meta data or attributes. The most known file is
META-INF/MANIFEST.MF. When you create a JAR file, it automatically receives a default manifest file. There can be only one manifest file in
an archive. Most uses of JAR files beyond simple archiving and compression require special information to be in the manifest file. For example,

— If you have an application bundled in a JAR file, you need some way to indicate which class within the JAR file is your application’s entry
point. The entry point is the class having a method with signature public static void main(String[ ] args). For example, Main-Class: Test.class

— A package within a JAR file can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR
file. You might want to seal a package, for example, to ensure version consistency among the classes in your software or as a security measure.

Name: myCompany/myPackage/
Sealed: true
Q15. What do you need to develop and run Java programs? How would you go about getting started?
A15. Step 1: Download and install the Java Development Kit (JDK) SE (Standard Edition) for your operating system (e.g. Windows, Linux, etc)
and processor (32 bit, 64 bit, etc) .
Step 2: Configure your environment. The first environment variable you need to set is the JAVA_HOME.

1 JAVA_HOME=C:\DEV\java\jdk-1.6.0_11 #on windows

2 export JAVA_HOME=/usr/java/jdk-1.6.0_11 #on Unix

The second environment variable is PATH.

1 PATH=%JAVA_HOME%\bin; #on windows

2 export PATH=$PATH:$JAVA_HOME/bin #on Unix

Step 3: Verify your configurations with the following commands:

1 echo %JAVA_HOME% #windows


2 echo %PATH% #windows

3 $ echo $JAVA_HOME #Unix

4 $ echo $PATH #Unix

Step 5: Verify your installation with

1 $ javac -version

2 $ java -version

Q16. How do you create a class under a package in Java? What is the first statement in Java?
A16. ou can create a class under a package as follows with the package keyword, which is the first keyword in any Java program followed by the
import statements. The java.lang package is imported implicitly by default and all the other packages must be explicitly imported. The core Java
packages like java.lang.*, java.net.*, java.io*, etc and its class files are distributed in the archive file named rt.jar.

1 package com.xyz.client ;

2 import java.io.File;

3 import java.net.URL;

4
Q17. What do you need to do to run a class with a main( ) method in a package? For example: Say, you have a class named Pet in a project folder
C:\projects\Test\src and package named com.xyz.client, will you be able to compile and run it as it is?
A17. Step 1: Write source code “Pet.java” as shown below

1 package com.xyz.client;

3 public class Pet {

4 public static void main(String[ ] args) {

5 System.out.println("I am found in the classpath");

6 }

7}

Step 2: The source code can be compiled into byte code i.e. Pet.class file as shown below:

1 C:\projects\Test\src>javac -d ../bin com/xyz/client/Pet.java

Note: The compiled byte code file Pet.class will be saved in the folder C:\projects\Test\bin\com\xyz\client.
Step 3: If you run it inside where the Pet.class is stored, the answer is yes.
1 C:\projects\Test\bin>java com/xyz/client/Pet

The Pet.class file will be found since com.xyz.client.Pet class file is in the projects\Test\bin folder. If you run it in any other folder say c:\

1 C:\> java com.xyz.client.Pet

The answer is no, and you will get the following exception: Exception in thread “main” java.lang.NoClassDefFoundError: com/xyz/client/Pet.
To fix this, you need to tell how to find the Pet.class by setting or providing the classpath. How can you do that? One of the following ways:
1) Set the operating system CLASSPATH environment variable to have the project folder c:\projects\Test\bin.

1 CLASSPATH=C:/projects/Test2/bin

2) Set the operating system CLASSPATH environment variable to have a jar file c:/projects/Test/pet.jar, which has the Pet.class file in it
1 CLASSPATH=c:/projects/Test/pet.jar

3) Run it with -cp or -classpath option as shown below.

1 C:\>java -cp projects\Test\bin com/xyz/client/Pet

2 C:\>java -classpath c:/projects/Test/pet.jar com.xyz.client.Pet

3 C:\projects\Test\src>java -cp ../bin com/xyz/client/Pet

Java 8 Interview Questions for Freshers


1. Describe the newly added features in Java 8?

Here are the newly added features of Java 8:

Feature Name Description


Lambda expression A function that can be shared or referred to as an object.
Functional Interfaces Single abstract method interface.
Method References Uses function as a parameter to invoke a method.
Default method It provides an implementation of methods within interfaces enabling 'Interface evolution' facilities.
Stream API Abstract layer that provides pipeline processing of the data.
Date Time API New improved joda-time inspired APIs to overcome the drawbacks in previous versions
Feature Name Description
Optional Wrapper class to check the null values and helps in further processing based on the value.
Nashorn, JavaScript Engine An improvised version of JavaScript Engine that enables JavaScript executions in Java, to replace Rhino.

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

4. What is MetaSpace? How does it differ from PermGen?


JVM

PremGen: MetaData information of classes was stored in PremGen (Permanent-Generation) memory type before Java 8. PremGen is fixed in size
and cannot be dynamically resized. It was a contiguous Java Heap Memory.

MetaSpace: Java 8 stores the MetaData of classes in native memory called 'MetaSpace'. It is not a contiguous Heap Memory and hence can be
grown dynamically which helps to overcome the size constraints. This improves the garbage collection, auto-tuning, and de-allocation of
metadata.

5. What are functional or SAM interfaces?


Functional Interfaces are an interface with only one abstract method. Due to which it is also known as the Single Abstract Method (SAM)
interface. It is known as a functional interface because it wraps a function as an interface or in other words a function is represented by a single
abstract method of the interface.

Functional interfaces can have any number of default, static, and overridden methods. For declaring Functional Interfaces @FunctionalInterface
annotation is optional to use. If this annotation is used for interfaces with more than one abstract method, it will generate a compiler error.

@FunctionalInterface // Annotation is optional


public interface Foo() {
// Default Method - Optional can be 0 or more
public default String HelloWorld() {
return "Hello World";
}
// Static Method - Optional can be 0 or more
public static String CustomMessage(String msg) {
return msg;
}
// Single Abstract Method
public void bar();
}

public class FooImplementation implements Foo {


// Default Method - Optional to Override
@Override
public default String HelloWorld() {
return "Hello Java 8";
}
// Method Override
@Override
public void bar() {
System.out.println(“Hello World”);
}
}

public static void main(String[] args) {

FooImplementation fi = new FooImplementation();


System.out.println(fi.HelloWorld());
System.out.println(fi.CustomMessage(“Hi”));
fi.bar();
}
6. Can a functional interface extend/inherit another interface?

A functional interface cannot extend another interface with abstract methods as it will void the rule of one abstract method per functional
interface. E.g:

interface Parent {
public int parentMethod();
}
@FunctionalInterface // This cannot be FunctionalInterface
interface Child extends Parent {
public int childMethod();
// It will also extend the abstract method of the Parent Interface
// Hence it will have more than one abstract method
// And will give a compiler error
}

It can extend other interfaces which do not have any abstract method and only have the default, static, another class is overridden, and normal
methods. For eg:

interface Parent {
public void parentMethod(){
System.out.println("Hello");
}
}
@FunctionalInterface
interface Child extends Parent {
public int childMethod();
}

7. What is the default method, and why is it required?

A method in the interface that has a predefined body is known as the default method. It uses the keyword default. default methods were
introduced in Java 8 to have 'Backward Compatibility in case JDK modifies any interfaces. In case a new abstract method is added to the interface,
all classes implementing the interface will break and will have to implement the new method. With default methods, there will not be any impact
on the interface implementing classes. default methods can be overridden if needed in the implementation. Also, it does not qualify as
synchronized or final.

@FunctionalInterface // Annotation is optional


public interface Foo() {
// Default Method - Optional can be 0 or more
public default String HelloWorld() {
return "Hello World";
}
// Single Abstract Method
public void bar();
}

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?

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.

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

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();

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

17. 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 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
}
}
Optional Class

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:
Java 8 Streams

21. What are the main components of a Stream?

Components of the stream are:

 A data source
 Set of Intermediate Operations to process the data source
 Single Terminal Operation that produces the result

Components of Stream

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.
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
o count() - Returns the number of elements on the stream.
o min() - Returns the min element from the stream.
o max() - Returns the max element from the stream.
 Search/Query operations
o anyMatch() , noneMatch() , allMatch() , ... - Short-circuiting operations.
o Takes a Predicate as input for the match condition.
o Stream processing will be stopped, as and when the result can be determined.
 Iterative operations
o forEach() - Useful to do something with each of the Stream elements. It accepts a consumer.
o 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 Stream Return any element from the 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
Data structure holds all the data elements No data is stored. Have the capacity to process an infinite number of elements on demand
External Iteration Internal Iteration
Can be processed any number of times Traversed only once
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?
 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
o dates
o times
o Instants
o durations
o time-zones
o 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

 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()
>>

Core Java Interview Questions and Answers for Freshers and Experienced
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.

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

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

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

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

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

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.

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) {

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

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?

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.

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.

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?

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();

Ans: Output will be:

Displaying from subclass

Displaying 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?

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.

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.

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) {

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.

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?

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.

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?

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 {


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

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?

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?

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.

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()

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.

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.

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.

----------------------------------------------------------------------------------------------------------------------------- -----------------------------------------

You might also like