Interview Questions
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.
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.
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.
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.
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.
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:
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.
17) Which two methods you will override for an **Object** to be used as **Key** in **HashMap**? (answer)
hint: equals and hashcode
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.
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
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.
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.
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?
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.
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.
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?
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.
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.
Lambda Expression
Stream API
Default methods in the interface
Functional Interface
Optional
Method reference
Date API
Nashorn, JavaScript Engine
6 // old way
9 @Override
11 System.out.println("Thread is started");
12 }
13 }).start();
14
17 }
18
19 }
20
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
you can not declare one argument’s type and do not declare type for other argument.
1
When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses
1
3. Body
There are many functional interfaces already present in java such as Comparable, Runnable.
Runnable has only one abstract method called run, so it can be used as below:
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.
3 @Override
6 }
7 });
2 package org.arpit.java2blog;
6 void print();
8 {
10 }
11 }
12
2 package org.arpit.java2blog.constructor;
7 {
10 }
11
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
You have written below function to get first non repeated character in String.
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 }
15 if (e.getValue() == 1)
16 return e.getKey();
17
18 }
19 return null;
20
21 }
22
2 Character c=getNonRepeatedCharacter("SASAS");
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.
5 Character c = str.charAt(i);
6 if (!countCharacters.containsKey(c)) {
7 countCharacters.put(c, 1);
8 } else {
10 }
11 }
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())
5 else
6 {
8 }
If there is no value present in Optional, it will simply print "No non repeated character found in String".
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.
3 System.out.println(currentDate);
2017-09-09
3 System.out.println(currentTime);
4
It will give you output in below format:
23:17:51.817
2 package org.arpit.java2blog;
9 super();
10 this.name = name;
11 this.age = age;
12 }
14 return name;
15 }
17 this.name = name;
18 }
20 return age;
21 }
23 this.age = age;
24 }
26 {
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.
3 .filter(e->e.getAge()>20)
4 .map(Employee::getName)
5 .collect(Collectors.toList());
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 {
10 {
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
22 {
24
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.
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.
3 Optional<Employee> e1 = employeeList.stream()
4 .filter(e->e.getName().equalsIgnoreCase("Mary")).findAny();
6 if(e1.isPresent())
7 System.out.println(e1.get());
4 mapToInt(Employee::getAge).max();
6 if(max.isPresent())
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.
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:
4 .stream()
5 .map(Employee::getName)
6 .collect(Collectors.toList());
Output:
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;
11 {
14 .collect(Collectors.groupingBy(Employee::getName));
16 }
17
18 public static List<Employee> createEmployeeList()
19 {
21
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]
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.
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;
11 {
14
16 setWithoutDups.forEach((i)->System.out.print(" "+i));
17 }
18 }
19
5 listWithoutDups.forEach((i)->System.out.print(" "+i));
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;
10 {
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
Answer:
Java 8 optional can be used to avoid NullPointerException.You can read about the detailed tutorial.
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.
Answer:
Supplier is function interface which does not take any parameter but returns the value using get method.
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.
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.
Java is called platform independent because of its byte codes which can run on any system irrespective of its underlying operating system.
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.
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.
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 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.
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?
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.
Lifetime Exists until the end of execution of the thread. Heap memory lives from the start till the end of application execution.
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:
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.
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.
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
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 {
3 methods}
An object is a real-world entity that has a state and behavior. An object has three characteristics:
1. State
2. Behavior
3. Identity
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 {
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 }
Methods Constructors
1. Used to represent the behavior of an object 1. Used to initialize the state of an object
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.
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
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:
2 {
3 if(i == 2)
4 {
5 continue;
}
6
System.out.println(i);
7
}
8
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 {
4 for(;;)
5 System.out.println("Welcome to Edureka!");
}
7
}
8
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
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.
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
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:
If you think this article on Java Interview Questions is helpful, you can check out Edureka’s Java Online Training as well.
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
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.
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 can contain primitive data types as well as objects Arraylists can contain only objects, no primitive data types are allowed
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:
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
Compile time polymorphism is method overloading whereas Runtime time polymorphism is done using inheritance and interface.
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 }
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
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:
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
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:
A class which inherits the properties is known as Child Class whereas a class whose properties are inherited is known as Parent class.
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.
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.
1 class Adder {
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.
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 {
9 }
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() {
}
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 }
}
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
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.
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:
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.
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.
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.
2 }
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.
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 }
{
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.
@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.
In case you are facing any challenges with these java interview questions, please comment on your problems in the section below.
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?
2) Doesn’t override the setter property Overrides the constructor property if both are defined.
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.
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.
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.
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?
@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.
@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.
AspectJ annotations for configuring aspects and advices , @Aspect, @Before, @After, @Around, @Pointcut, etc.
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.
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!
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.
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.
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.
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.
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
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 {
3 {
}
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 {
try {
3
int x=100;
4
}
5
catch(Exception e) {
6
System.out.println(e);
7
}
8 finally {
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 {
f1= NULL;
9
f2=NULL;
10
System.gc();
11
}
12
}
13
Throw is used within the method. Throws is used with the method signature.
In case you are facing any challenges with these java interview questions, please comment on your problems in the section below.
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.
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.
Process Thread
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.
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.
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.
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
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.
OutOfMemoryError is the subclass of java.lang.Error which generally occurs when our JVM runs out of memory.
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.
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
--------------------------------------------------------------------------------------------------------------------------------
— 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
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;
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:
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.
Java platform
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”);
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 $ 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;
6 }
7}
Step 2: The source code can be compiled into byte code i.e. Pet.class file as shown below:
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:\
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
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.
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.
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();
}
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.
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.
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.
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.
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.
Below are the two significant features of the methods that are defined as the lambda expressions:
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.
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.:
It is a static method reference to method Valueof() of class String. It will return the string representation of the argument passed.
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.
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.
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
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.
Intermediate Operations:
Terminal 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.
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.
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.
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
LocalDate
LocalTime
LocalDateTime
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:
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.
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.
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.
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.
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.
for (;;)
{
// Statements to execute
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.
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.
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.
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:
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".
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
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.
Q14. What's the base class in Java from which all classes are derived?
Ans: java.lang.object
Ans: In java, main() method can't return any data and hence, it's always declared with a void return type.
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.
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.*
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.
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);
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.
const_example() {
system.out.println("Inside constructor");
}
public static void main(String args[]) {
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.
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.
super.displayResult();
obj.displayResult();
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?
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".
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";
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.
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.
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.
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.
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.
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 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:
obj1.print();
obj1.print("xx");
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.
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.
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.
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.
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
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.
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:
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.
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.
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.
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
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.
Ans: In Java, there is not goto keyword and java doesn't support this feature of going to a particular labeled line.
Ans: In java, a thread which is in dead state can't be started again. There is no way to restart a dead thread.
Ans:
Ans: The above class declaration is incorrect as an abstract class can't be declared as Final.
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:
if (str1.equals(str2))
if (str1 == str2) {
} else
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.
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.
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.
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.
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.
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.
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?
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.
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().
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:
@Override
return false;
@Override
public Object nextElement()
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.
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.
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.
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.
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.
----------------------------------------------------------------------------------------------------------------------------- -----------------------------------------