Core Java Interview Questions

What is a JVM?

JVM is Java Virtual Machine which is a run time environment for the compiled java class files.

Are JVM’s platform independent?

JVM’s are not platform independent. JVM’s are platform specific run time implementation provided by the vendor.

What is the difference between a JDK and a JVM?

JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM.

What is a pointer and does Java support pointers?

Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn’t support the usage of pointers.

What is the most important feature of Java?

Java is a platform independent language.

What do you mean by platform independence?

Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc).

What is the base class of all classes?

java.lang.Object

What is difference between Path and Classpath?

Path and Classpath are operating system level environment variales. Path is used define where the system can find the executables(.exe) files and classpath is used to specify the location .class files.

What are local variables?

Local varaiables are those which are declared within a block of code like methods. Local variables should be initialised before accessing them.

Does Java support multiple inheritance?

Java doesn’t support multiple inheritance.

Is Java a pure object oriented language?

Java uses primitive data types and hence is not a pure object oriented language.

Are arrays primitive data types?

In Java, Arrays are objects.

What is the return type of the main() method?

Main() method doesn’t return anything hence declared void.

Why is the main() method declared static?

main() method is called by the JVM even before the instantiation of the class hence it is declared as static.

What is the arguement of main() method?

main() method accepts an array of String object as arguement.

What are instance variables?

Instance variables are those which are defined at the class level. Instance variables need not be initialized before using them as they are automatically initialized to their default values.

How to define a constant variable in Java?

The variable should be declared as static and final. So only one copy of the variable exists for all instances of the class and the value can’t be changed also.

static final int PI = 2.14; is an example for constant.

Should a main() method be compulsorily declared in all java classes?

No not required. main() method should be defined only if the source class is a java application.

Can a source file contain more than one class declaration?

Yes a single source file can contain any number of Class declarations but only one of the class can be declared as public.

What is a package?

Package is a collection of related classes and interfaces. package declaration should be first statement in a java class.

Which package is imported by default?

java.lang package is imported by default even without a package declaration.

Can a main() method be overloaded?

Yes. You can have any number of main() methods with different method signature and implementation in the class.

Can a main() method be declared final?

Yes. Any inheriting class will not be able to have it’s own default main() method.

Does the order of public and static declaration matter in main() method?

No. It doesn’t matter but void should always come before main().

What is the purpose of declaring a variable as final?

A final variable’s value can’t be changed. final variables should be initialized before using them.

What is the impact of declaring a method as final?

A method declared as final can’t be overridden. A sub-class can’t have the same method signature with a different implementation.

I don’t want my class to be inherited by any other class. What should i do?

You should declared your class as final. But you can’t define your class as final, if it is an abstract class. A class declared as final can’t be extended by any other class.

Can a class declared as private be accessed outside it’s package?

Not possible.

Can a class be declared as protected?

The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.

What is the access scope of a protected method?

A protected method can be accessed by the classes within the same package or by the subclasses of the class in any package.

When will you define a method as static?

When a method needs to be accessed even before the creation of the object of the class then we should declare the method as static.

What are the restriction imposed on a static method or a static block of code?

A static method should not refer to instance variables without creating an instance and cannot use “this” operator to refer the instance.

I want to print “Hello” even before main() is executed. How will you acheive that?

Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main() method. And it will be executed only once.

Can you give few examples of final classes defined in Java API?

java.lang.String, java.lang.Math are final classes.

How is final different from finally and finalize()?

Final is a modifier which can be applied to a class or a method or a variable. final class can’t be inherited, final method can’t be overridden and final variable can’t be changed.

finally is an exception handling code section which gets executed whether an exception is raised or not by the try block code segment.

finalize() is a method of Object class which will be executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.

Can a class be declared as static?

We can not declare top level class as static, but only inner class can be declared static.

public class Test

{

static class InnerClass

{

public static void InnerMethod()

{ System.out.println(“Static Inner Class!”); }

}

public static void main(String args[])

{

Test.InnerClass.InnerMethod();

}

}

//output: Static Inner Class!

Can a abstract class be declared final?

Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.

What is use of a abstract variable?

Variables can’t be declared as abstract. only classes and methods can be declared as abstract.

Can you create an object of an abstract class?

Not possible. Abstract classes can’t be instantiated.

What is the importance of static variable?

Static variables are class level variables where all objects of the class refer to the same variable. If one object changes the value then the change gets reflected in all the objects.

Can we declare a static variable inside a method?

Static varaibles are class level variables and they can’t be declared inside a method. If declared, the class will not compile.

What is an Abstract Class and what is it’s purpose?

A Class which doesn’t provide complete implementation is defined as an abstract class. Abstract classes enforce abstraction.

Can an Interface implement another Interface?

Intefaces doesn’t provide implementation hence a interface cannot implement another interface.

Can an Interface extend another Interface?

Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.

Can a Class extend more than one Class?

Not possible. A Class can extend only one class but can implement any number of Interfaces.

Can a abstract class be defined without any abstract methods?

Yes it’s possible. This is basically to avoid instance creation of the class.

Class C implements Interface I containing method m1 and m2 declarations. Class C has provided implementation for method m2.

Can i create an object of Class C?

No not possible. Class C should provide implementation for all the methods in the Interface I. Since Class C didn’t provide implementation for m1 method, it has to be declared as abstract. Abstract classes can’t be instantiated.

Can a method inside a Interface be declared as final? Can a abstract class be defined without any abstract methods?

Yes it’s possible. This is basically to avoid instance creation of the class.

Class C implements Interface I containing method m1 and m2 declarations. Class C has provided implementation for method m2.

Can I create an object of Class C?

No not possible. Class C should provide implementation for all the methods in the Interface I. Since Class C didn’t provide implementation for m1 method, it has to be declared as abstract. Abstract classes can’t be instantiated.

Can a method inside a Interface be declared as final?

No not possible. Doing so will result in compilation error. public and abstract are the only applicable modifiers for method declaration in an interface.

Can an Interface be defined inside a class?

Yes it’s possible.

What is a Marker Interface?

An Interface which doesn’t have any declaration inside but still enforces a mechanism.

Which object oriented concept is achieved by using overloading and overriding?

Polymorphism.

Why is an Interface be able to extend more than one Interface but a Class can’t extend more than one Class?

Basically Java doesn’t allow multiple inheritance, so a Class is restricted to extend only one Class. But an Interface is a pure abstraction model and doesn’t have inheritance hierarchy like classes(do remember that the base class of all classes is Object). So an Interface is allowed to extend more than one Interface.

Can an Interface be final?

Not possible. Doing so so will result in compilation error.

Can a class be defined inside an Interface?

Yes it’s possible.

What modifiers are allowed for methods in an Interface?

Only public and abstract modifiers are allowed for methods in interfaces.

What is a local, member and a class variable?

Variables declared within a method are “local” variables. Variables declared within the class i.e not within any methods are “member” variables (global variables). Variables declared within the class i.e not within any methods and are defined as “static” are class variables.

What is an abstract method?

An abstract method is a method whose implementation is deferred to a subclass.

Why does Java not support operator overloading?

Operator overloading makes the code very difficult to read and maintain. To maintain code simplicity, Java doesn’t support operator overloading.

What is the difference between a static and a non-static inner class?

A non-static inner class may have object instances that are associated with instances of the class’s outer class. A static inner class does not have any object instances.

What is an object’s lock and which object’s have locks?

An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is acquired on the class’s Class object.

What is the % operator?

It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.

When can an object reference be cast to an interface reference?

An object reference be cast to an interface reference when the object implements the referenced interface.

Can we define private and protected modifiers for variables in interfaces?

No.

What is Externalizable?

Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

What value does read() return when it has reached the end of a file?

The read() method returns -1 when it has reached the end of a file.

How to convert String to byte array and vice versa?

We can use String getBytes() method to convert String to byte array and we can use String constructor new String(byte[] arr) to convert byte array to String.

Can we use String in switch case?

This is a tricky question used to check your knowledge of current Java developments. Java 7 extended the capability of switch case to use Strings also, earlier java versions doesn’t support this.

If you are implementing conditional flow for Strings, you can use if-else conditions and you can use switch case if you are using Java 7 or higher versions.

Write a program to print all permutations of String.

This is a tricky question and we need to use recursion to find all the permutations of a String, for example “AAB” permutations will be “AAB”, “ABA” and “BAA”.

We also need to use Set to make sure there are no duplicate values.

Write a function to find out longest palindrome in a given string.

A String can contain palindrome strings in it and to find longest palindrome in given String is a programming question.

What are the difference among String, StringBuffer and StringBuilder?

String is immutable and final in java, so whenever we do String manipulation, it creates a new String. String manipulations are resource consuming, so java provides two utility classes for String manipulations – StringBuffer and StringBuilder.

StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized where StringBuilder operations are not thread-safe. So when multiple threads are working on same String, we should use StringBuffer but in single threaded environment we should use StringBuilder.

StringBuilder performance is fast than StringBuffer because of no overhead of synchronization.

Why String is immutable or final in Java?

There are several benefits of String because it’s immutable and final.

String Pool is possible because String is immutable in java.

It increases security because any hacker can’t change its value and it’s used for storing sensitive information such as database username, password etc.

Since String is immutable, it’s safe to use in multi-threading and we don’t need any synchronization.

Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader.

How to Split String in java?

We can use split(String regex) to split the String into String array based on the provided regular expression.

Why Char array is preferred over String for storing password?

String is immutable in java and stored in String pool. Once it’s created it stays in the pool until unless garbage collected, so even though we are done with password it’s available in memory for longer duration and there is no way to avoid it. It’s a security risk because anyone having access to memory dump can find the password as clear text.

If we use char array to store password, we can set it to blank once we are done with it. So we can control for how long it’s available in memory that avoids the security threat with String.

How do you check if two Strings are equal in Java?

There are two ways to check if two Strings are equal or not – using “==” operator or using equals method. When we use “==” operator, it checks for value of String as well as reference but in our programming, most of the time we are checking equality of String for value only. So we should use equals method to check if two Strings are equal or not.

There is another function equalsIgnoreCase that we can use to ignore case.

String s1 = “abc”;

String s2 = “abc”;

String s3= new String(“abc”);

System.out.println(“s1 == s2 ? “+(s1==s2)); //true

System.out.println(“s1 == s3 ? “+(s1==s3)); //false

System.out.println(“s1 equals s3 ? “+(s1.equals(s3))); //true

What is String Pool?

As the name suggests, String Pool is a pool of Strings stored in Java heap memory. We know that String is special class in java and we can create String object using new operator as well as providing values in double quotes.

What does String intern() method do?

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

This method always return a String that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

Does String is thread-safe in Java?

Strings are immutable, so we can’t change it’s value in program. Hence it’s thread-safe and can be safely used in multi-threaded environment.

Why String is popular HashMap key in Java?

Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.

What is String in Java? String is a data type?

String is a Class in java and defined in java.lang package. It’s not a primitive data type like int and long. String class represents character Strings. String is used in almost all the Java applications and there are some interesting facts we should know about String. String in immutable and final in Java and JVM uses String Pool to store all the String objects.

Some other interesting things about String is the way we can instantiate a String object using double quotes and overloading of “+” operator for concatenation.

What are different ways to create String Object?

We can create String object using new operator like any normal java class or we can use double quotes to create a String object. There are several constructors available in String class to get String from char array, byte array, StringBuffer and StringBuilder.

String str = new String(“abc”);

String str1 = “abc”;

When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.

When we use new operator, JVM creates the String object but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool.

Write a method to check if input String is Palindrome?

A String is said to be Palindrome if it’s value is same when reversed. For example “aba” is a Palindrome String.

String class doesn’t provide any method to reverse the String but StringBuffer and StringBuilder class has reverse method that we can use to check if String is palindrome or not.

private static boolean isPalindrome(String str) {

if (str == null)

return false;

StringBuilder strBuilder = new StringBuilder(str);

strBuilder.reverse();

return strBuilder.toString().equals(str);

}

Sometimes interviewer asks not to use any other class to check this, in that case we can compare characters in the String from both ends to find out if it’s palindrome or not.

private static boolean isPalindromeString(String str) {

if (str == null)

return false;

int length = str.length();

System.out.println(length / 2);

for (int i = 0; i < length / 2; i++) {

if (str.charAt(i) != str.charAt(length – i – 1))

return false;

}

return true;

}

Write a method that will remove given character from the String?

We can use replaceAll method to replace all the occurance of a String with another String. The important point to note is that it accepts String as argument, so we will use Character class to create String and use it to replace all the characters with empty String.

private static String removeChar(String str, char c) {

if (str == null)

return null;

return str.replaceAll(Character.toString(c), “”);

}

How can we make String upper case or lower case?

We can use String class toUpperCase and toLowerCase methods to get the String in all upper case or lower case. These methods have a variant that accepts Locale argument and use that locale rules to convert String to upper or lower case.

What is String subSequence method?

Java 1.4 introduced CharSequence interface and String implements this interface, this is the only reason for the implementation of subSequence method in String class. Internally it invokes the String substring method.

How to compare two Strings in java program?

Java String implements Comparable interface and it has two variants of compareTo() methods.

compareTo(String anotherString) method compares the String object with the String argument passed lexicographically. If String object precedes the argument passed, it returns negative integer and if String object follows the argument String passed, it returns positive integer. It returns zero when both the String have same value, in this case equals(String str) method will also return true.

compareToIgnoreCase(String str): This method is similar to the first one, except that it ignores the case. It uses String CASE_INSENSITIVE_ORDER Comparator for case insensitive comparison. If the value is zero then equalsIgnoreCase(String str) will also return true.

How to convert String to char and vice versa?

This is a tricky question because String is a sequence of characters, so we can’t convert it to a single character. We can use use charAt method to get the character at given index or we can use toCharArray() method to convert String to character array.

What is atomic operation? What are atomic classes in Java Concurrency API?

Atomic operations are performed in a single unit of task without interference from other operations. Atomic operations are necessity in multi-threaded environment to avoid data inconsistency.

int++ is not an atomic operation. So by the time one threads read it’s value and increment it by one, other thread has read the older value leading to wrong result.

To solve this issue, we will have to make sure that increment operation on count is atomic, we can do that using Synchronization but Java 5 java.util.concurrent.atomic provides wrapper classes for int and long that can be used to achieve this atomically without usage of Synchronization.

What is Lock interface in Java Concurrency API? What are it’s benefits over synchronization?

Lock interface provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects.

The advantages of a lock are-

it’s possible to make them fair

it’s possible to make a thread responsive to interruption while waiting on a Lock object.

it’s possible to try to acquire the lock, but return immediately or after a timeout if the lock can’t be acquired.

it’s possible to acquire and release locks in different scopes, and in different orders.

What is Executors Framework?

In Java 5, Executor framework was introduced with the java.util.concurrent.Executor interface.

The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies.

What is BlockingQueue? How can we implement Producer-Consumer problem using Blocking Queue?

java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store null value in the queue.

BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control.

BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem.

What is Callable and Future?

Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.

Callable interface use Generic to define the return type of Object. Executors class provide useful methods to execute Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object. Callable tasks return java.util.concurrent.Future object. Using Future we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.

What is FutureTask Class?

FutureTask is the base implementation class of Future interface and we can use it with Executors for asynchronous processing. Most of the time we don’t need to use FutureTask class but it comes real handy if we want to override some of the methods of Future interface and want to keep most of the base implementation. We can just extend this class and override the methods according to our requirements.

What are Concurrent Collection Classes?

Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw ConcurrentModificationException.

Concurrent Collection classes support full concurrency of retrievals and adjustable expected concurrency for updates.

Major classes are ConcurrentHashMap, CopyOnWriteArrayList and CopyOnWriteArraySet.

What is Executors Class?

Executors class provide utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes.

Executors class can be used to easily create Thread Pool in java, also this is the only class supporting execution of Callable implementations.

What are some of the improvements in Concurrency API in Java 8?

Some important concurrent API enhancements are:

ConcurrentHashMap compute(), forEach(), forEachEntry(), forEachKey(), forEachValue(), merge(), reduce() and search() methods.

CompletableFuture that may be explicitly completed (setting its value and status).

Executors newWorkStealingPool() method to create a work-stealing thread pool using all available processors as its target parallelism level.

What is the difference between Process and Thread?

A process is a self contained execution environment and it can be seen as a program or application whereas Thread is a single task of execution within the process. Java runtime environment runs as a single process which contains different classes and programs as processes. Thread can be called lightweight process. Thread requires less resources to create and exists in the process, thread shares the process resources.

What are the benefits of multi-threaded programming?

In Multi-Threaded programming, multiple threads are executing concurrently that improves the performance because CPU is not idle incase some thread is waiting to get some resources. Multiple threads share the heap memory, so it’s good to create multiple threads to execute some task rather than creating multiple processes. For example, Servlets are better in performance than CGI because Servlet support multi-threading but CGI doesn’t.

What is difference between user Thread and daemon Thread?

When we create a Thread in java program, it’s known as user thread. A daemon thread runs in background and doesn’t prevent JVM from terminating. When there are no user threads running, JVM shutdown the program and quits. A child thread created from daemon thread is also a daemon thread.

How can we create a Thread in Java?

There are two ways to create Thread in Java – first by implementing Runnable interface and then creating a Thread object from it and second is to extend the Thread Class.

What are different states in lifecycle of Thread?

When we create a Thread in java program, its state is New. Then we start the thread that change it’s state to Runnable. Thread Scheduler is responsible to allocate CPU to threads in Runnable thread pool and change their state to Running. Other Thread states are Waiting, Blocked and Dead.

What are different Collection views provided by Map interface?

Map interface provides three collection views:

Set keySet(): Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

Collection values(): Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

Set<Map.Entry<K, V>> entrySet(): Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

What are Collection related features in Java 8?

Java 8 has brought major changes in the Collection API. Some of the changes are:

Java Stream API for collection classes for supporting sequential as well as parallel processing

Iterable interface is extended with forEach() default method that we can use to iterate over a collection. It is very helpful when used with lambda expressions because it’s argument Consumer is a function interface.

Miscellaneous Collection API improvements such as forEachRemaining(Consumer action) method in Iterator interface, Map replaceAll(), compute(), merge() methods.

What is Java Collections Framework? List out some benefits of Collections framework?

Collections are used in every programming language and initial java release contained few classes for collections: Vector, Stack, Hashtable, Array. But looking at the larger scope and usage, Java 1.2 came up with Collections Framework that group all the collections interfaces, implementations and algorithms.

Java Collections have come through a long way with usage of Generics and Concurrent Collection classes for thread-safe operations. It also includes blocking interfaces and their implementations in java concurrent package.

Some of the benefits of collections framework are;

Reduced development effort by using core collection classes rather than implementing our own collection classes.

Code quality is enhanced with the use of well tested collections framework classes.

Reduced effort for code maintenance by using collection classes shipped with JDK.

Reusability and Interoperability

What is the benefit of Generics in Collections Framework?

Java 1.5 came with Generics and all collection interfaces and implementations use it heavily. Generics allow us to provide the type of Object that a collection can contain, so if you try to add any element of other type it throws compile time error.

This avoids ClassCastException at Runtime because you will get the error at compilation. Also Generics make code clean since we don’t need to use casting and instanceof operator.

What are the basic interfaces of Java Collections Framework?

Collection is the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Java platform doesn’t provide any direct implementations of this interface.

Set is a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the deck of cards.

List is an ordered collection and can contain duplicate elements. You can access any element from it’s index. List is more like array with dynamic length.

A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.

Some other interfaces are Queue, Dequeue, Iterator, SortedSet, SortedMap and ListIterator.

Why Collection doesn’t extend Cloneable and Serializable interfaces?

Collection interface specifies group of Objects known as elements. How the elements are maintained is left up to the concrete implementations of Collection. For example, some Collection implementations like List allow duplicate elements whereas other implementations like Set don’t.

A lot of the Collection implementations have a public clone method. However, it does’t really make sense to include it in all implementations of Collection. This is because Collection is an abstract representation. What matters is the implementation.

The semantics and the implications of either cloning or serializing come into play when dealing with the actual implementation; so concrete implementation should decide how it should be cloned or serialized, or even if it can be cloned or serialized.

So mandating cloning and serialization in all implementations is actually less flexible and more restrictive. The specific implementation should make the decision as to whether it can be cloned or serialized.

Why Map interface doesn’t extend Collection interface?

Although Map interface and it’s implementations are part of Collections Framework, Map are not collections and collections are not Map. Hence it doesn’t make sense for Map to extend Collection or vice versa.

If Map extends Collection interface, then where are the elements?

Map contains key-value pairs and it provides methods to retrieve list of Keys or values as Collection but it doesn’t fit into the “group of elements” paradigm.

What is an Iterator?

Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using iterator() method. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for traversal through the elements of a collection and implements Iterator Design Pattern.

What is difference between Enumeration and Iterator interface?

Enumeration is twice as fast as Iterator and uses very less memory. Enumeration is very basic and fits to basic needs. But Iterator is much safer as compared to Enumeration because it always denies other threads to modify the collection object which is being iterated by it.

Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection that is not possible with Enumeration. Iterator method names have been improved to make it’s functionality clear.

Why there is not method like Iterator.add() to add elements to the collection?

The semantics are unclear, given that the contract for Iterator makes no guarantees about the order of iteration. Note, however, that ListIterator does provide an add operation, as it does guarantee the order of the iteration.

Why Iterator don’t have a method to get next element directly without moving the cursor?

It can be implemented on top of current Iterator interface but since it’s use will be rare, it doesn’t make sense to include it in the interface that everyone has to implement.

What is different between Iterator and ListIterator?

We can use Iterator to traverse Set and List collections whereas ListIterator can be used with Lists only.

Iterator can traverse in forward direction only whereas ListIterator can be used to traverse in both the directions.

ListIterator inherits from Iterator interface and comes with extra functionalities like adding an element, replacing an element, getting index position for previous and next elements.

What are different ways to iterate over a list?

We can iterate over a list in two different ways – using iterator and using for-each loop.

List<String> strList = new ArrayList<>();

//using for-each loop

for(String obj : strList){

System.out.println(obj);

}

//using iterator

Iterator<String> it = strList.iterator();

while(it.hasNext()){

String obj = it.next();

System.out.println(obj);

}

Using iterator is more thread-safe because it makes sure that if underlying list elements are modified, it will throw ConcurrentModificationException.

What do you understand by iterator fail-fast property?

Iterator fail-fast property checks for any modification in the structure of the underlying collection everytime we try to get the next element. If there are any modifications found, it throws ConcurrentModificationException. All the implementations of Iterator in Collection classes are fail-fast by design except the concurrent collection classes like ConcurrentHashMap and CopyOnWriteArrayList.

What is difference between fail-fast and fail-safe?

Iterator fail-safe property work with the clone of underlying collection, hence it’s not affected by any modification in the collection. By design, all the collection classes in java.util package are fail-fast whereas collection classes in java.util.concurrent are fail-safe.

Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws ConcurrentModificationException.

What are important methods of Java Exception Class?

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

String getMessage() – This method returns the message String of Throwable and the message can be provided while creating the exception through it’s constructor.

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.

synchronized Throwable getCause() – This method returns the cause of the exception or null id the cause is unknown.

String toString() – This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message.

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 argument to write the stack trace information to the file or stream.

Explain Java 7 ARM Feature and multi-catch block?

If you are catching a lot of exceptions in a single try block, you will notice that catch block code looks very ugly and mostly consists of redundant code to log the error, keeping this in mind Java 7 one of the feature was multi-catch block where we can catch multiple exceptions in a single catch block. The catch block with this feature looks like below:

catch(IOException | SQLException | Exception ex){

logger.error(ex);

throw new MyException(ex.getMessage());

}

Most of the time, we use finally block just to close the resources and sometimes we forget to close them and get runtime exceptions when the resources are exhausted. These exceptions are hard to debug and we might need to look into each place where we are using that type of resource to make sure we are closing it. So java 7 one of the improvement was try-with-resources where we can create a resource in the try statement itself and use it inside the try-catch block. When the execution comes out of try-catch block, runtime environment automatically close these resources. Sample of try-catch block with this improvement is:

try (MyResource mr = new MyResource()) {

System.out.println(“MyResource created in try-with-resources”);

} catch (Exception e) {

e.printStackTrace();

}

What is difference between Checked and Unchecked Exception in Java?

Checked Exceptions should be handled in the code using try-catch block or else main() method should use throws keyword to let JRE know about these exception that might be thrown from the program. Unchecked Exceptions are not required to be handled in the program or to mention them in throws clause.

Exception is the super class of all checked exceptions whereas RuntimeException is the super class of all unchecked exceptions.

Checked exceptions are error scenarios that are not caused by program, for example FileNotFoundException in reading a file that is not present, whereas Unchecked exceptions are mostly caused by poor programming, for example NullPointerException when invoking a method on an object reference without making sure that it’s not null.

What is difference between throw and throws keyword in Java?

The throws keyword is used with method signature to declare the exceptions that the method might throw whereas throw keyword is used to disrupt the flow of program and handing over the exception object to runtime to handle it.

How to write custom exception in Java?

We can extend Exception class or any of it’s subclasses to create our custom exception class. The custom exception class can have it’s own variables and methods that we can use to pass error codes or other exception related information to the exception handler.

A simple example of custom exception is shown below.

MyException.java

package com.journaldev.exceptions;

import java.io.IOException;

public class MyException extends IOException {

private static final long serialVersionUID = 4664456874499611218L;

private String errorCode=”Unknown_Exception”;

public MyException(String message, String errorCode){

super(message);

this.errorCode=errorCode;

}

public String getErrorCode(){

return this.errorCode;

}

}

What is OutOfMemoryError in Java?

OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and it’s thrown by JVM when it ran out of heap memory. We can fix this error by providing more memory to run the java application through java options.

$>java MyProgram -Xms1024m -Xmx1024m -XX:PermSize=64M -XX:MaxPermSize=256m

What are different scenarios causing “Exception in thread main”?

Some of the common main thread exception scenarios are:

Exception in thread main java.lang.UnsupportedClassVersionError: This exception comes when your java class is compiled from another JDK version and you are trying to run it from another java version.

Exception in thread main java.lang.NoClassDefFoundError: There are two variants of this exception. The first one is where you provide the class full name with .class extension. The second scenario is when Class is not found.

Exception in thread main java.lang.NoSuchMethodError: main: This exception comes when you are trying to run a class that doesn’t have main method.

Exception in thread “main” java.lang.ArithmeticException: Whenever any exception is thrown from main method, it prints the exception is console. The first part explains that exception is thrown from main method, second part prints the exception class name and then after a colon, it prints the exception message.

What is difference between final, finally and finalize in Java?

final and finally are keywords in java whereas finalize is a method.

final keyword can be used with class variables to make them immutable, with class to avoid extending by classes and with methods to avoid overriding by subclasses, finally keyword is used with try-catch block to provide statements that will always gets executed even if some exception arises, usually finally is used to close resources. finalize() method is executed by Garbage Collector before the object is destroyed, it’s great way to make sure all the global resources are closed.

Out of the three, only finally is related to java exception handling.

What happens when exception is thrown by main method?

When exception is thrown by main() method, Java Runtime terminates the program and print the exception message and stack trace in system console.

Can we have an empty catch block?

We can have an empty catch block but it’s the example of worst programming. We should never have empty catch block because if the exception is caught by that block, we will have no information about the exception and it will be a nightmare to debug it. There should be at least a logging statement to log the exception details in console or log files.

Provide some Java Exception Handling Best Practices?

Some of the best practices related to Java Exception Handling are:

Use Specific Exceptions for ease of debugging.

Throw Exceptions Early (Fail-Fast) in the program.

Catch Exceptions late in the program, let the caller handle the exception.

Use Java 7 ARM feature to make sure resources are closed or use finally block to close them properly.

Always log exception messages for debugging purposes.

Use multi-catch block for cleaner close.

Use custom exceptions to throw single type of exception from your application API.

Follow naming convention, always end with Exception.

Document the Exceptions Thrown by a method using @throws in javadoc.

Exceptions are costly, so throw it only when it makes sense. Else you can catch them and provide null or empty response.

What is the problem with below programs and how do we fix it?

In this section, we will look into some programming questions related to java exceptions.

What is the problem with below program?

package com.journaldev.exceptions;

import java.io.FileNotFoundException;

import java.io.IOException;

public class TestException {

public static void main(String[] args) {

try {

testExceptions();

} catch (FileNotFoundException | IOException e) {

e.printStackTrace();

}

}

public static void testExceptions() throws IOException, FileNotFoundException{

}

}

Above program won’t compile and you will get error message as “The exception FileNotFoundException is already caught by the alternative IOException”. This is because FileNotFoundException is subclass of IOException, there are two ways to solve this problem.

First way is to use single catch block for both the exceptions.

try {

testExceptions();

}catch(FileNotFoundException e){

e.printStackTrace();

}catch (IOException e) {

e.printStackTrace();

}

Another way is to remove the FileNotFoundException from multi-catch block.

try {

testExceptions();

}catch (IOException e) {

e.printStackTrace();

}

You can chose any of these approach based on your catch block code.

What is the problem with below program?

package com.journaldev.exceptions;

import java.io.FileNotFoundException;

import java.io.IOException;

import javax.xml.bind.JAXBException;

public class TestException1 {

public static void main(String[] args) {

try {

go();

} catch (IOException e) {

e.printStackTrace();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (JAXBException e) {

e.printStackTrace();

}

}

public static void go() throws IOException, JAXBException, FileNotFoundException{

}

}

The program won’t compile because FileNotFoundException is subclass of IOException, so the catch block of FileNotFoundException is unreachable and you will get error message as “Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException”.

You need to fix the catch block order to solve this issue.

try {

go();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} catch (JAXBException e) {

e.printStackTrace();

}

Notice that JAXBException is not related to IOException or FileNotFoundException and can be put anywhere in above catch block hierarchy.

What is the problem with below program?

package com.journaldev.exceptions;

import java.io.IOException;

import javax.xml.bind.JAXBException;

public class TestException2 {

public static void main(String[] args) {

try {

foo();

} catch (IOException e) {

e.printStackTrace();

}catch(JAXBException e){

e.printStackTrace();

}catch(NullPointerException e){

e.printStackTrace();

}catch(Exception e){

e.printStackTrace();

}

}

public static void foo() throws IOException{

}

}

The program won’t compile because JAXBException is a checked exception and foo() method should throw this exception to catch in the calling method. You will get error message as “Unreachable catch block for JAXBException. This exception is never thrown from the try statement body”.

To solve this issue, you will have to remove the catch block of JAXBException.

Notice that catching NullPointerException is valid because it’s an unchecked exception.

What is the problem with below program?

package com.journaldev.exceptions;

public class TestException3 {

public static void main(String[] args) {

try{

bar();

}catch(NullPointerException e){

e.printStackTrace();

}catch(Exception e){

e.printStackTrace();

}

foo();

}

public static void bar(){

}

public static void foo() throws NullPointerException{

}

}

This is a trick question, there is no problem with the code and it will compile successfully. We can always catch Exception or any unchecked exception even if it’s not in the throws clause of the method.

Similarly if a method (foo) declares unchecked exception in throws clause, it is not mandatory to handle that in the program.

What is the problem with below program?

package com.journaldev.exceptions;

import java.io.IOException;

public class TestException4 {

public void start() throws IOException{

}

public void foo() throws NullPointerException{

}

}

class TestException5 extends TestException4{

public void start() throws Exception{

}

public void foo() throws RuntimeException{

}

}

The above program won’t compile because start() method signature is not same in subclass. To fix this issue, we can either change the method singnature in subclass to be exact same as superclass or we can remove throws clause from subclass method as shown below.

@Override

public void start(){

}

What is the problem with below program?

package com.journaldev.exceptions;

import java.io.IOException;

import javax.xml.bind.JAXBException;

public class TestException6 {

public static void main(String[] args) {

try {

foo();

} catch (IOException | JAXBException e) {

e = new Exception(“”);

e.printStackTrace();

}catch(Exception e){

e = new Exception(“”);

e.printStackTrace();

}

}

public static void foo() throws IOException, JAXBException{

}

}

The above program won’t compile because exception object in multi-catch block is final and we can’t change it’s value. You will get compile time error as “The parameter e of a multi-catch block cannot be assigned”.

We have to remove the assignment of “e” to new exception object to solve this error.

How to avoid ConcurrentModificationException while iterating a collection?

We can use concurrent collection classes to avoid ConcurrentModificationException while iterating over a collection, for example CopyOnWriteArrayList instead of ArrayList.

Why there are no concrete implementations of Iterator interface?

Iterator interface declare methods for iterating a collection but it’s implementation is responsibility of the Collection implementation classes. Every collection class that returns an iterator for traversing has it’s own Iterator implementation nested class.

This allows collection classes to chose whether iterator is fail-fast or fail-safe. For example ArrayList iterator is fail-fast whereas CopyOnWriteArrayList iterator is fail-safe.

What is UnsupportedOperationException?

UnsupportedOperationException is the exception used to indicate that the operation is not supported. It’s used extensively in JDK classes, in collections framework java.util.Collections.UnmodifiableCollection throws this exception for all add and remove operations.

What is Exception in Java?

Exception is an error event that can happen during the execution of a program and disrupts it’s normal flow. Exception can arise from different kind of situations such as wrong data entered by user, hardware failure, network connection failure etc.

Whenever any error occurs while executing a java statement, an exception object is created and then JRE tries to find exception handler to handle the exception. If suitable exception handler is found then the exception object is passed to the handler code to process the exception, known as catching the exception. If no handler is found then application throws the exception to runtime environment and JRE terminates the program.

Java Exception handling framework is used to handle runtime errors only, compile time errors are not handled by exception handling framework.

What are the Exception Handling Keywords in Java?

There are four keywords used in java exception handling.

throw: Sometimes we explicitly want to create exception object and then throw it to halt the normal processing of the program. throw keyword is used to throw exception to the runtime to handle it.

throws: When we are throwing any checked exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.

try-catch: We use try-catch block for exception handling in our code. try is the start of the block and catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also. catch block requires a parameter that should be of type Exception.

finally: finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurrs or not.

 

Leave a Reply

*

  • RSS
  • Newsletter
  • Facebook
  • LinkedIn
  • Twitter
  • Pinterest