Java Programming Interview Questions


Resources > Java Interview Questions > {{currentSubTopic}}


Why main() in java is declared as public static void?

When you run java.exe (or javaw.exe on Windows), what is really happening is a couple of Java Native Interface (JNI) calls. These calls load the DLL that is really the JVM. JNI is the tool that we use when we have to bridge between the virtual machine world, and the world of C, C++, etc...

Basically, java.exe is a super simple C application that parses the command line, creates a new String array in the JVM to hold those arguments, parses out the class name that you specified as containing main(), uses JNI calls to find the main() method itself, then invokes the main() method, passing in the newly created string array as a parameter. This is very, very much like what you do when you use reflection from Java - it just uses confusingly named native function calls instead.

It would be perfectly legal for you to write your own version of java.exe (the source is distributed with the JDK), and have it do something entirely different. In fact, that's exactly what we do with all of our Java based apps.

Each of our Java apps has its own launcher. We primarily do this so we get our own icon and process name, but it has come in handy in other situations where we want to do something besides the regular main() call to get things going.

public - The main method is called by the JVM to run the method which is outside the scope of the project therefore the access specifier has to be public to permit a call from anywhere outside the application.

static - When the JVM makes a call to the main method there is no object that exists for the class being called therefore it has to have static method to allow invocation from class.

void - Java is a platform independent language, therefore if it returns some value, then the value may have a different meaning between different platforms so unlike C it can not assume a behavior of returning value to the operating system.

What do you mean by platform independence of Java?

Typically, the compiled code is the exact set of instructions the CPU requires to "execute" the program. In Java, the compiled code is an exact set of instructions for a "virtual CPU" which is required to work the same on every physical machine.

So, in a sense, the designers of the Java language decided that the language and the compiled code was going to be platform independent, but since the code eventually has to run on a physical platform, they opted to put all the platform dependent code in the JVM.

This requirement for a JVM is in contrast to Turbo C example. With Turbo C, the compiler will produce platform dependent code, and there is no need for a JVM work-alike because the compiled Turbo C program can be executed by the CPU directly.

With Java, the CPU executes the JVM, which is platform dependent. This running JVM then executes the Java bytecode which is platform independent, provided that you have a JVM available for it to execute upon. You might say that writing Java code, you don't program for the code to be executed on the physical machine, you write the code to be executed on the Java Virtual Machine.

The only way that all this Java bytecode works on all Java virtual machines is that a rather strict standard has been written for how Java virtual machines work. This means that no matter what physical platform you are using, the part where the Java bytecode interfaces with the JVM is guaranteed to work only one way. Since all the JVMs work exactly the same, the same code works exactly the same everywhere without recompiling. If you can't pass the tests to make sure it's the same, you're not allowed to call your virtual machine a "Java virtual machine".

What is JVM and is it platform independent?

Java Virtual Machine (JVM) is a specification that provides runtime environment in which java bytecode(.class files) can be executed. The JVM is the platform. As the name implies, the JVM acts as a "virtual" machine or processor. Java's platform independence consists mostly of its Java Virtual Machine (JVM) . JVM makes this possible because it is aware of the specific instruction lengths and other particularities of the platform (Operating System).

The JVM is not platform independent. Java Virtual Machine (JVM) provides the environment to execute the java file(. Class file). So at the end it's depends on your kernel , and kernel differs from OS (Operating System) to OS. The JVM is used to both translate the bytecode into the machine language for a particular computer, and actually execute the corresponding machine-language instructions as well. Without the JVM, you can’t run a Java application.

What is the difference between JRE, JDK and JVM?


The Java Virtual machine (JVM) is the virtual machine that runs the Java bytecodes. The JVM doesn't understand Java source code, that's why you compile your *.java files to obtain *.class files that contain the bytecodes understood by the JVM. It's also the entity that allows Java to be a "portable language" (write once, run anywhere). Indeed, there are specific implementations of the JVM for different systems (Windows, Linux, MacOS, see the Wikipedia list), the aim is that with the same bytecodes they all give the same results.


Java Developer Kit (JDK) contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc… Compiler converts java code into byte code. Java application launcher opens a JRE, loads the class, and invokes its main method. You need JDK, if at all you want to write your own programs, and to compile them. For running java programs, JRE is sufficient.

JRE is targeted for execution of Java files
i.e. JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries.
JDK is mainly targeted for java development. I.e. You can create a Java file (with the help of Java packages), compile a Java file and run a java file.


Java Runtime Environment (JRE) contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system.

The Java Virtual Machine provides a platform-independent way of executing code. That means compile once in any machine and run it anywhere( on any machine).

What is difference between path and classpath variables?

1)The main difference between PATH and CLASSPATH is that PATH is an environment variable which is used to locate JDK binaries like "java" or "javac" command used to run java program and compile java source file. On the other hand, CLASSPATH, an environment variable is used by System or Application ClassLoader to locate and load compiled Java bytecodes stored in the .class file.

2) In order to set PATH in Java, you need to include JDK_HOME/bin directory in PATH environment variable while in order to set CLASSPATH in Java you need to include all those directories where you have put either your .class file or JAR file which is required by your Java application.

3) Another significant difference between PATH and CLASSPATH is that PATH can not be overridden by any Java settings but CLASSPATH can be overridden by providing command line option -classpath or -cp to both "java" and "javac" commands or by using Class-Path attribute in Manifest file inside JAR archive.

4) PATH environment variable is used by operating system to find any binary or command typed in the shell, this is true for both Windows and Linux environment while CLASSPATH is only used by Java ClassLoaders to load class files.

What is the importance of main method in Java?

The main method in Java is a standard method which is used by JVM to start execution of any Java program. The main method is referred to as the entry point of Java application which is true in case of core java application but in case of container managed environment like Servlet, EJB or MIDlet this is not true as these Java programs have there own life-cycle methods like init(), service() or destory() for Servlet's which is used by container. main method in Java is run by main thread which is a non daemon thread and Java program runs until main method finishes or any other user thread is running. When we start JVM by running java command we also provide name of the class which contains the main method, which is later invoked by JVM to start Java program execution.

Can we have multiple public classes in a java source file?

No, there can only be one public class per .java file, as public classes must have the same name as the source file.

What is Classloader in Java?

The Java Classloader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. When the JVM is started, three class loaders are used:
1) Bootstrap class loader
2) Extensions class loader
3) System class loader

The bootstrap class loader loads the core Java libraries located in the <JAVA_HOME>/jre/lib directory. This class loader, which is part of the core JVM, is written in native code.

The extensions class loader loads the code in the extensions directories ( <JAVA_HOME>/jre/lib/ext or any other directory specified by the java.ext.dirs system property). It is implemented by the sun.misc.Launcher$ExtClassLoader class.

The system class loader loads code found on java.class.path, which maps to the CLASSPATH environment variable. This is implemented by the sun.misc.Launcher$AppClassLoader class.

What are different types of classloaders?

Java class loaders can be broadly classified into below categories:

Bootstrap Class Loader :

Bootstrap class loader loads java’s core classes like java.lang, java.util etc. These are classes that are part of java runtime environment. Bootstrap class loader is native implementation and so they may differ across different JVMs.

Extensions Class Loader :

JAVA_HOME/jre/lib/ext contains jar packages that are extensions of standard core java classes. Extensions class loader loads classes from this ext folder. Using the system environment property java.ext.dirs you can add ‘ext’ folders and jar files to be loaded using extensions class loader.

System Class Loader :

Java classes that are available in the java classpath are loaded using System class loader. You can see more class loaders like, etc. Those are all extended from java.lang.ClassLoader.

These class loaders have a hierarchical relationship among them. Class loader can load classes from one level above its hierarchy. First level is bootstrap class loader, second level is extensions class loader and third level is system class loader.

What is the use of System class?

The java.lang.System class contains several useful utilities for mostly used operation. System class cannot be instantiated.

Facilities provided by System:

standard output
error output streams
standard input and access to externally defined properties and environment variables.
A utility for quickly copying particular portion of an array.
used to loading files and libraries.

Standard Fields of System class are:

static PrintStream err -- "standard" error output stream.
static InputStream in -- "standard" input stream.
static PrintStream out -- "standard" output stream.

Java Compiler is stored in JDK, JRE or JVM?


Why main method is static? Can we execute a program without main() method? If yes, how?

Their is a way to run a JAVA program without the main method.

public class HelloWorld{

Now you can compile the program using "javac" and after that run it using "java HelloWorld". It will print the message as expected. But it will show a message "Exception in thread "main" java.lang.NoSuchMethodError: main" To avoid the above message add System.exit(0); after print statement The System.exit(0) lets the program exit before the JVM is looking for the main method.

In Java 6 or below it was possible to do this using the Static Initialization block but In Java 7, however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:

"The program compiled successfully, but main class was not found. Main class should contain method: public static void main (String[] args)."

What if the static modifier is removed from the signature of the main method?

Program compiles. But at runtime throws an error "NoSuchMethodError".

Can we have multiple classes in single file ?

Yes, it can. However, there can only be one public top-level class per .java file, and public top-level classes must have the same name as the source file.

The purpose of including multiple classes in one source file is to bundle related support functionality (internal data structures, support classes, etc) together with the main public class.

What is the maximum heap size of 32-bit and 64-bit JVM?

The maximum theoretical heap limit for the 32-bit JVM is 4G. Due to various additional constraints such as available swap, kernel address space usage, memory fragmentation, and VM overhead, in practice the limit can be much lower.

String and StringBuffer

What is the difference between creating String as new() and literal?

new String("hello"); explicitly creates a new and referentially distinct instance of a String object;
String s = "hello"; reuses an instance from the string constant pool if one is available

Why is String Immutable in Java?


Parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.

Synchronization and concurrency:

Making String immutable automatically makes them thread safe thereby solving the synchronization issues.


"When the compiler optimizes your String objects and sees that two objects have same value (a=""test"", and b=""test"") it will make only one String object with value ""test"" and both a and b will point to the same object".

Class loading:

"String is used as an argument for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state)."

Difference between String, StringBuilder and StringBuffer?


String is immutable object. The object created as a String is stored in the Constant String Pool. String is thread safe. String once assigned cannot be changed.


StringBuffer is mutable means one can change the value of the object. The object created through StringBuffer is stored in the heap. StringBuffer is thread safe.


StringBuilder is same as the StringBuffer, that is it stores the object in heap and it can also be modified. The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. StringBuilder is fast as it is not thread safe.

Can you explain what does substring method do?

The substring(int beginIndex, int endIndex) method returns a string that starts with beginIndex and ends with endIndex-1.

The implementation of the substring(int beginIndex, int endIndex) method in JDK 6 is different from JDK 7.

substring() in JDK 6

In JDK 6, the String class contains 3 fields: char value[], int offset, int count. They are used to store real character array, the first index of the array, the number of characters in the String. When the substring() method is called, it creates a new string, but the string's value still points to the same array in the heap. The difference between the two Strings is their count and offset values.

substring() in JDK 7

In JDK 7, the substring() method actually create a new array in the heap.

How do you avoid NullPointerException, while comparing two Strings in Java?

Keep 1st parameter as constant to avoid NullPointerException
E.g. : "Something".equals(Input);
In the above case even if Input is null it won't throw NullPointerException.

How to check if a String contains only numeric digits?

Use regular expression : text.matches("[0-9]+").

How to convert String to int in Java?

Use either Integer.parseInt() OR Integer.valueOf()

Can we use String in switch case?

Yes, From Java 7 onwards String can be used in switch case.

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. Its processing is faster than other HashMap key objects.

Which is the final class in these three classes – String, StringBuffer and StringBuilder?

All three are final.

Classes and Objects

Is Java Pass by Reference or Pass by Value?

The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java.

What will be the initial value of an object reference which is defined as an instance variable?

Any variable defined in Java which is not assigned a value, whether it is an instance variable or a static variable, will have a default value of null.

Can we declare a class as static?

Nested classes (a class within a class) are the only ones that can be declared static. This is so the parent class does not have to be instantiated to access the nested class.

What is this keyword?

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this .

What is default constructor?

A “default constructor" refers to a nullary constructor that is automatically generated by the compiler if no constructors have been defined for the class. The default constructor implicitly calls the superclass's nullary constructor, then executes an empty body.

What is Garbage Collection?

Sample s = new Sample(); //line#1
s = new Sample(); //line#2

At line#2, s starts referring to a new instance of Sample. This means that there is now no reference variable referring to the Sample instance created on line#1. So instance created on line#1 becomes eligible for garbage collection and the memory consumed by that object is freed when Java garbage collector runs.

What is instanceof keyword?

The instanceof operator compares an object to a specified type. It is used to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

What is difference between Heap and Stack Memory?

The stack memory is the space for a thread of execution. When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns, the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO (last in first out) order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.

The heap memory is for dynamic allocation. Unlike the stack, there's no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns.

Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM . Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is dealt with when the program is compiled.

What is inner class in java?

class OuterClass {
    class NestedClass {

Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes.

class OuterClass {
    static class StaticNestedClass {
    class InnerClass {

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private, public, protected, or package private.

What is Anonymous class?

Anonymous class are like local classes except that they do not have a name. Use them if you need to use a local class only once. They enable you to declare and instantiate a class at the same time.

The syntax of an anonymous class expression is like the invocation of a constructor, except that there is a class definition contained in a block of code. Consider the instantiation of the frenchGreeting object:

HelloWorld frenchGreeting = new HelloWorld() {
	String name = "tout le monde";
	public void greet() {
		greetSomeone("tout le monde");
	public void greetSomeone(String someone) {
		name = someone;
		System.out.println("Salut " + name);

The anonymous class expression consists of the following:
1) The new operator.
2) The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.
3) Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression.
Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
4) A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.

Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how?

Yes, It is possible.
To chain to a particular superclass constructor instead of one in the same class, use super instead of this. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.

Explain shallow copy and deep copy?

Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.

Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

Why should you make an Object Immutable?

1) Simplicity - each class is in one state only
2) Thread Safe - because the state cannot be changed, no synchronization is required.
3) Writing in an immutable style can lead to more robust code. Imagine if Strings weren't immutable,then any getter methods that returned a String would require the implementation to create a defensive copy before the String was returned - otherwise a client may accidentally or maliciously break that state of the object.

How to access the methods of an inner class?

class OuterClass {
    class InnerClass {

OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = InnerClass();

How do you create an Immutable object in Java?

1) Do not provide setter methods to modify values of any of the instance variables of the class.
2) Declare the class as 'final' . This would prevent any other class from extending it and hence from overriding any method from it which could modify instance variable values.
3) Declare the instance variables as private and final.
4) Declare the constructor of the class as private and add a factory method to create an instance of the class when required.

What is the difference between Serial and Parallel Garbage Collector?

A serial Garbage collector is a default copying collector which uses only one GC thread for the GC operation, while a parallel collector uses multiple GC threads for the GC operation.

What is a compile time constant in Java? What is the risk of using it?

Static final variables are known as compile time constants. They are replaced with actual values at compile time because compiler knows their value up-front and also knows that it cannot be changed during run-time. Risk with this is if you are using public static final variable from some in-house or third party library and their value changed later then your client will still be using old value even after you deploy new version of JARs.

Why are there two Date classes - one in java.util package and another in java.sql?

Java.util.Date is the generic all-purpose Date object. It stores a Date (as a long) and allows you to display it.

java.sql.Date extends java.util.Date. Main difference to note is that java.sql.Date does not have a time component. java.sql.Date is a thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT.

What is the difference between abstract class and interface?

Abstract classes can have constants, members, method stubs (methods without a body) and defined methods, whereas interfaces can only have constants and methods stubs.

Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default).

When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an abstract class can extend another abstract class and abstract methods from the parent class don't have to be defined.

Similarly, an interface extending another interface is not responsible for implementing methods from the parent interface. This is because interfaces cannot define any implementation.

A child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces.

A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility (public).

Can an interface implement or extend another interface?

An interface cannot implement another interface. However, an interface can extend another interface. A class implementing an interface has to provide implementation for the methods of that interface as well as all the interfaces it extends.

What is Marker interface?

Marker Interface in java is an interface with no fields or methods within it. It is used to convey to the JVM that the class implementing an interface of this category will have some special behavior. Hence, an empty interface in java is called a marker interface.

When do you favor abstract class over the interface?

An abstract class doesn't have to be completely abstract. You can define certain functions (and variables) that all subclasses will use as-is, and leave only certain methods to be implemented by the subclasses. An interface has the limitation that no functions can be defined.Abstract class can provide default behaviour where Interfaces cannot. This make sense when a part of the behaviour will be common across several subclasses.
E.g. ArrayList extends AbstractList implements List

Can an interface be defined inside a class just like we can have inner classes inside a class ?


Exception Handling

What is try-with-resources in java?

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

What is the difference between error and exception in java?

If exception occurs we can handle it by using try and catch block. If Error occurs we can not handle it , program execution will be terminated. Exceptions are related to application where as Error are related to environment in which application is running. It is impossible to recover from errors.You can recover from exceptions by handling them through try-catch blocks.

What are runtime exceptions in java. Give example?

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.

RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary. Following are some of the direct known subclasses of RuntimeException :


What is OutOfMemoryError in java?

One common indication of a memory leak is the java.lang.OutOfMemoryErrorexception. Usually, this error is thrown when there is insufficient space to allocate an object in the Java heap. In this case, the garbage collector cannot make space available to accommodate a new object, and the heap cannot be expanded further.

What is the difference between ClassNotFoundException and NoClassDefFoundError in java?

ClassNotFoundException is thrown when an application tries to load in a class through its string name using:

1) The forName method in class Class.
2) The findSystemClass method in class ClassLoader.
3) The loadClass method in class ClassLoader.
but no definition for the class with the specified name could be found.

For NoClassDefFoundError is thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found. The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

NoClassDefFoundError occurs when the source was successfully compiled, but at runtime, the required class files were not found. This may be something that can happen in the distribution or production of JAR files, where not all the required class files were included.

As for ClassNotFoundException, it tries to make reflective calls to classes at runtime, but the classes the program is trying to call does not exist.

The difference between the two is that one is an Error and the other is an Exception. With NoClassDefFoundError is an Error and it arises from the Java Virtual Machine having problems finding a class it expected to find. A program that was expected to work at compile-time can't run because of class files not being found, or is not the same as was produced or encountered at compile-time. This is a pretty critical error, as the program cannot be initiated by the JVM.

On the other hand, the ClassNotFoundException is an Exception, so it is somewhat expected, and is something that is recoverable. Using reflection can be error-prone (as there are some expectations that things may not go as expected). There is no compile-time check to see that all the required classes exist, so any problems with finding the desired classes will appear at runtime.

Does finally block get executed if either try or catch blocks are returning the control?

Yes, finally will be called. The only times finally won't be called are:

If you invoke System.exit();
If the JVM crashes first
If there is an infinite loop (or some other non-interruptable, non-terminating statement) in the try block
If the OS forcibly terminates the JVM process e.g. "kill -9 " on UNIX.
If the host system dies; e.g. power failure, hardware error, OS panic, etc.

What is the difference between final, finally and finalize in java?

final :

final can be used to mark a variable "unchangeable"
private final String name = "foo"; //the reference name can never change

final can also make a method not "overrideable"
public final String toString() { return "NULL"; }

final can also make a class not "inheritable". i.e. the class can not be subclassed.
public final class finalClass {...}
public class classNotAllowed extends finalClass {...} // Not allowed

finally :

finally is used in a try/catch statement to execute code "always".

try {
  //do stuff
} catch (SomeException se) {
  //handle se
} finally {
  lock.unlock(); //always executed, even if Exception or Error or se

Java 7 has a new try with resources statement that you can use to automatically close resources that explicitly or implicitly implement or java.lang.AutoCloseable.

finalize :

finalize is called when an object is garbage collected. You rarely need to override it. An example:

protected void finalize() {
  //free resources (e.g. unallocate memory)

What is the difference between throw, throws and throwable in java?

Throwable :

In Java, all error's and execption's class are derived from java.lang.Throwable class. It is the top of the hierarchy of classes of error and exceptions. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement.

Throws :

Throws is a post-method modifier and specifies which exceptions may be thrown by the method. If they are checked exceptions, the compiler will guarantee that the code invoking that method must catch these checked exceptions.

Throw :

The throw statement is used to throw an error or an exception.It requires a single argument: an instance of Throwable class or any of its subclasses. Executing throw statement triggers the JVM to throw this exception and causes an exception to occur.

What is StackOverflowError in java?

Usually there is one stack in the program that contains local-scope variables and addresses where to return when execution of a routine ends. The stack tends to be a fixed memory range, therefore it's limited in how many values it can contain.

If the stack is empty you can't pop, if you do you'll get stack underflow error.

If the stack is full you can't push, if you do you'll get stack overflow error.

So stack overflow appears where you allocate too much into the stack. The common cause for a stack overflow is a bad recursive call. Typically, it is caused when the recursive functions don't have the correct termination condition, so it ends up calling itself forever.
Example :

int foo()
    // more stuff

Give some examples to checked exceptions?


Give some examples to unchecked exceptions?


What is multi-catch block in java?

Multi-catch block in Java is used for handling more than one type of Exception. In Java SE 7 and later, a single catch block can also handle more than one type of exception. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers.

Can we have try without catch block?

It is possible to have try block without catch block by using 'finally' block. Java supports try with finally block.
'finally' block will always execute even if there is an exception in the try block. The only case when it does not execute is when System.exit() is called.

Collection Classes

How duplicate collision is resolved in HashMap?

Prior to Java 8, HashMap and all other hash table based Map implementation classes in Java handled collision by chaining.i.e. they used linked list to store map entries which ended in the same bucket due to a collision.
In JDK 8, if there are more than 8 elements in the same bucket, HashMap code uses a tree instead of linked list to hold them in the same bucket.

When do you override hashCode() and equals()?

In Java, every object has access to the equals() method because it is inherited from the Object class. However, this default implementation just simply compares the memory addresses of the objects. You can override the default implementation of the equals() method defined in java.lang.Object. If you override the equals(), you MUST also override hashCode(). Otherwise a violation of the general contract for Object.hashCode will occur, which can have unexpected repercussions when your class is in conjunction with all hash-based collections. Collections such as HashMap and HashSet use the hashcode value of an object to determine how the object should be stored in the collection, and the hashcode is used again to help locate the object in the collection.

Hashing retrieval is a two-step process:
1) Find the right bucket using hashCode().
2) Search the bucket for the right element using equals().

Why HashMap should not be used in multithreaded environment?

When two threads try to access HashMap simultaneously, then you may encounter infinite loop because of rehashing.

How to sort a collection of custom Objects in Java?

Collections.sort can be used along with a custom comparator and that comparator can be implemented to allow sorting in different sort orders.

When to use a linked list over an Arraylist?

Linked lists are preferable over ArrayList when:
a) There is a need of constant-time insertions/deletions from the list.
b) You don't know how many items will be in the list. With arrays, you may need to re-declare and copy memory if the array grows too big.
c) There is a need of random access to any elements.
d) You want to be able to insert items in the middle of the list.

When to use HashMap over LinkedList or ArrayList?

While you could use a map as a list, there are some definite downsides of doing so:

Maintaining order: - A list by definition is ordered. You add items and then you are able to iterate back through the list in the order that you inserted the items. When you add items to a HashMap, you are not guaranteed to retrieve the items in the same order you put them in. There are subclasses of HashMap like LinkedHashMap that will maintain the order, but in general order is not guaranteed with a Map.

Key/Value semantics: - The purpose of a map is to store items based on a key that can be used to retrieve the item at a later point. Similar functionality can only be achieved with a list in the limited case where the key happens to be the position in the list.

When you are writing equals() method, which other method or methods you need to override?

You need to override hashCode().

What will be the problem if you don’t override hashCode() method?

If hashCode() in not overridden then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.

Some collections, like HashSet, HashMap or HashTable use the hash code to store its data and to retrieve it. If hashCode() and equals() are not implemented in a consistent manner, then they will not function properly.

Is it possible for equals() to return false, even if contents of two Objects are same?

Yes, it is possible for equals to return false.
E.g. :

public class MyClass {
    private final String str = "HelloWorld";

public void test() {
    MyClass class1 = new MyClass();
    MyClass class2 = new MyClass();

What will happen if two different objects have the same hashcode?

They will be added to the same bucket and equals() will be used to distinguish them. Each bucket can contain a list of objects with the same hash code.

What happens On HashMap in Java if the size of the HashMap exceeds a given threshold defined by load factor ?

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

The difference between List, Set and Map in Java?

List :

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Set :

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

Map :

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

LinkedList in Java is doubly or singly linked list?

As per Javadoc, all of the operations perform as could be expected for a doubly-linked list.

Which kind of tree is used to implement TreeMap in Java?

Red-black trees.

What sorting Algorithm is used by java.util.Arrays.sort(Object[])?

InsertionSort and MergeSort.

What is the difference between Hashtable and HashMap?

Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.

HashMap does not guarantee that the order of the map will remain constant over time. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort.

What is the difference between Comparator and Comparable in Java?

Comparable :

A comparable object is capable of comparing itself with another object. The class itself must implement the java.lang.Comparable interface in order to be able to compare its instances.

Comparator :

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.


Why wait and notify is declared in Object class instead of Thread?

In Java, A Thread wait() for particular instance of an Object to be free. notify() wakes up a single thread that is waiting on this object's monitor. notifyAll() wakes up all threads that are waiting on this object's monitor.

If wait() and notify() were on the Thread instead then each thread would have to know the status of every other thread. How would thread1 know that thread2 was waiting for access to a particular resource? If thread1 needed to call thread2.notify() it would have to somehow find out that thread2 was waiting. There would need to be some mechanism for threads to register the resources or actions that they need so others could signal them when stuff was ready or available.

In Java, the object itself is the entity that is shared between threads which allows them to communicate with each other. The threads have no specific knowledge of each other and they can run asynchronously. They run and they lock, wait, and notify on the object that they want to get access to. They have no knowledge of other threads and don't need to know their status. They don't need to know that it is thread2 which is waiting for the resource – they just notify on the resource and whomever it is that is waiting (if anyone) will be notified.

What is ReadWrite Lock? Does ConcurrentHashMap uses ReadWrite Lock?

A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive. A read-write lock allows for a greater level of concurrency in accessing shared data than that permitted by a mutual exclusion lock. Multiple threads can concurrently read the data, but only one thread can write it, at a time.

ConcurrentHashMap doesn't use ReadWriteLock, instead it divides maps into several segments and lock them separately using different locks, which means any given time, only a portion of map is locked, instead of whole map.

What are some of the drawbacks of threading?

1) Difficulty of writing code - Multithreaded and multicontexted applications are not easy to write.
2) Difficulty of debugging - It is much harder to replicate an error in a multithreaded or multicontexted application than it is to do so in a single-threaded, single-contexted application. As a result, it is more difficult, in the former case, to identify and verify root causes when errors occur.
3) Difficulty of managing concurrency - The task of managing concurrency among threads is difficult and has the potential to introduce new problems into an application.
4) Difficulty of testing - Testing a multithreaded application is more difficult than testing a single-threaded application because defects are often timing-related and more difficult to reproduce.
5) Difficulty of porting existing code - Existing code often requires significant re-architecting to take advantage of multithreading and multicontexting.
6) Programmers need to:
a) Remove static variables
b) Replace any function calls that are not thread-safe
c) Replace any other code that is not thread-safe
d) Because the completed port must be tested and re-tested, the work required to port a multithreaded and/or multicontexted application is substantial.

Name some of the frameworks used to manage threading

Executor framework(Java 1.6)
Join/Fork framework(Java 1.7)

When InvalidMonitorStateException is thrown?

When a thread does not have a lock on an object and it tries to call wait()/notify()/notifyAll() on that object then InvalidMonitorStateException exception is thrown.

How to detect a Deadlock in Java?

Deadlock can be detected using ThreadMXBean.

What is busy spinning?

Busy-waiting or spinning is a technique in which a process repeatedly checks to see if a condition is true instead of calling wait or sleep method and releasing CPU.

What is the difference between CyclicBarrier and CountDownLatch in Java?

The main difference between CyclicBarrier and CountDownLatch is that CyclicBarrier is reusable and CountDownLatch is not. You can reuse CyclicBarrier by calling reset() method which resets the barrier to its initial state.

CountDownLatch is good for one time event like application/module start-up time and CyclicBarrier can be used to in case of recurrent event e.g. concurrently (re-)calculating each time when the input data changed.

Give us scenarios when you will use CyclicBarrier.

A Multithreaded download manager. The download manager will start multiple threads to download each part of the file simultaneously.
Now suppose that you want the integrity check for the downloaded pieces to be done after a particular time interval. Here cyclic barrier plays an important role. After each time interval, each thread will wait at the barrier so that thread associated with cyclibarrier can do the integrity check. This integrity check can be done multiple times thanks to CyclicBarrier .

Why isn’t Thread class final?

There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. The other way to create a thread is to declare a class that implements the Runnable interface. Hence, Thread class is not final as you need to subclass Thread to override its run() method.

Can we make array volatile in Java?

An array can be made volatile in Java but only the reference which is pointing to an array will be volatile not the array element.

What is the difference between sleep and wait in Java?

Though both are used to pause currently running thread, sleep() is actually meant for short pause because it doesn't release lock, while wait() is meant for conditional wait and that's why it releases the lock which can then be acquired by another thread to change the condition on which it is waiting.