1. What is JVM?

The Java interpreter along with the runtime environment required to run the Java application in called as Java virtual machine(JVM)


  1. What is the most important feature of Java?

Java is a platform independent language.


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


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


  1. What is the base class of all classes?



  1. What are the access modifiers in Java?

There are 3 access modifiers. Public, protected and private, and the default one if no identifier is specified is called friendly, but programmer cannot specify the friendly identifier explicitly.


  1. What is are packages?

A package is a collection of related classes and interfaces providing access protection and namespace management.


  1. What is meant by Inheritance and what are its advantages?

Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.


  1. What is the difference between superclass and subclass?

A super class is a class that is inherited whereas sub class is a class that does the inheriting.


  1. What is an abstract class?

An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.


  1. What are the states associated in the thread?

Thread contains ready, running, waiting and dead states.


  1. What is synchronization?

Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time.


  1. What is deadlock?

When two threads are waiting each other and can’t precede the program is said to be deadlock.


  1. What is an applet?

Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser


  1. What is the lifecycle of an applet?

init() method – Can be called when an applet is first loaded

start() method – Can be called each time an applet is started.

paint() method – Can be called when the applet is minimized or maximized.

stop() method – Can be used when the browser moves off the applet’s page.

destroy() method – Can be called when the browser is finished with the applet.


  1. How do you set security in applets?

using setSecurityManager() method


  1. What is a layout manager and what are different types of layout managers available in java AWT?

A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout


  1. What is JDBC?

JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications.


  1. What are drivers available?

-a) JDBC-ODBC Bridge driver b) Native API Partly-Java driver

  1. c) JDBC-Net Pure Java driver d) Native-Protocol Pure Java driver


  1. What is stored procedure?

Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.


  1. What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.


  1. Why there are no global variables in Java?

Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:

1)The global variables breaks the referential transparency

2)Global variables creates collisions in namespace.


  1. What are Encapsulation, Inheritance and Polymorphism?

Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions.


  1. What is the use of bin and lib in JDK?

Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.


  1. What is method overloading and method overriding?

Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.


  1. What is the difference between this() and super()?

this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.


  1. What is Domain Naming Service(DNS)?

It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters. For example, www. mascom. com implies com is the domain name reserved for US commercial sites, moscom is the name of the company and www is the name of the specific computer, which is mascom’s server.


  1. What is URL?

URL stands for Uniform Resource Locator and it points to resource files on the Internet. URL has four components: http://www. address. com:80/index.html, where http – protocol name, address – IP address or host name, 80 – port number and index.html – file path.


  1. What is RMI and steps involved in developing an RMI object?

Remote Method Invocation (RMI) allows java object that executes on one machine and to invoke the method of a Java object to execute on another machine. The steps involved in developing an RMI object are: a) Define the interfaces b) Implementing these interfaces c) Compile the interfaces and their implementations with the java compiler d) Compile the server implementation with RMI compiler e) Run the RMI registry f) Run the application.


  1. What is RMI architecture?

RMI architecture consists of four layers and each layer performs specific functions: a) Application layer – contains the actual object definition. b) Proxy layer – consists of stub and skeleton. c) Remote Reference layer – gets the stream of bytes from the transport layer and sends it to the proxy layer. d) Transportation layer – responsible for handling the actual machine-to-machine communication.


  1. What is a Java Bean?

A Java Bean is a software component that has been designed to be reusable in a variety of different environments.


  1. What are checked exceptions?

Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.


  1. What are runtime exceptions?

Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.


  1. What is the difference between error and an exception?

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).


  1. What is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. For example, closing a opened file, closing a opened database Connection.


  1. What is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.


  1. What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.


  1. What is mutable object and immutable object?

If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …)


  1. What is the purpose of Void class?

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.


  1. What is JIT and its use?

Really, just a very fast compiler… In this incarnation, pretty much a one-pass compiler — no offline computations. So you can’t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, it’s an on-line problem.


  1. What is nested class?

If all the methods of a inner class is static then it is a nested class.


  1. What is HashMap and Map?

Map is Interface and Hashmap is class that implements that.


  1. What are different types of access modifiers?

public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private can’t be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package.


  1. What is the difference between Reader/Writer and InputStream/Output Stream?

The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented.


  1. What is servlet?

Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database.


  1. What is Constructor?

A constructor is a special method whose task is to initialize the object of its class.

It is special because its name is the same as the class name.

They do not have return types, not even void and therefore they cannot return values.

They cannot be inherited, though a derived class can call the base class constructor.

Constructor is invoked whenever an object of its associated class is created.


  1. What is an Iterator ?

The Iterator interface is used to step through the elements of a Collection.

Iterators let you process each element of a Collection.

Iterators are a generic way to go through all the elements of a Collection no matter how it is organized.

Iterator is an Interface implemented a different way for every Collection.


  1. What is the List interface?

The List interface provides support for ordered collections of objects.

Lists may contain duplicate elements.


  1. What is memory leak?

A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesnt get garbage collected.


  1. What is the difference between the prefix and postfix forms of the ++ operator?

The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value.


  1. What is the difference between a constructor and a method?

A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.

A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.


  1. What will happen to the Exception object after exception handling?

Exception object will be garbage collected.


  1. Difference between static and dynamic class loading.

Static class loading: The process of loading a class using new operator is called static class loading. Dynamic class loading: The process of loading a class at runtime is called dynamic class loading.

Dynamic class loading can be done by using Class.forName(….).newInstance().


  1. Explain the Common use of EJB

The EJBs can be used to incorporate business logic in a web-centric application.

The EJBs can be used to integrate business processes in Business-to-business (B2B) e-commerce applications.In Enterprise Application Integration applications, EJBs can be used to house processing and mapping between different applications.


  1. What is JSP?

JSP is a technology that returns dynamic content to the Web client using HTML, XML and JAVA elements. JSP page looks like a HTML page but is a servlet. It contains Presentation logic and business logic of a web application.


  1. What is the purpose of apache tomcat?

Apache server is a standalone server that is used to test servlets and create JSP pages. It is free and open source that is integrated in the Apache web server. It is fast, reliable server to configure the applications but it is hard to install. It is a servlet container that includes tools to configure and manage the server to run the applications. It can also be configured by editing XML configuration files.


  1. Where pragma is used?

Pragma is used inside the servlets in the header with a certain value. The value is of no-cache that tells that a servlets is acting as a proxy and it has to forward request. Pragma directives allow the compiler to use machine and operating system features while keeping the overall functionality with the Java language. These are different for different compilers.


  1. Briefly explain daemon thread.

Daemon thread is a low priority thread which runs in the background performs garbage collection operation for the java runtime system.


  1. What is a native method?

A native method is a method that is implemented in a language other than Java.


  1. Explain different way of using thread?

A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous, when you are going for multiple inheritance.


  1. What are the two major components of JDBC?

One implementation interface for database manufacturers, the other implementation interface for application and applet writers.


  1. What kind of thread is the Garbage collector thread?

It is a daemon thread.


  1. What are the different ways to handle exceptions?

There are two ways to handle exceptions,

  1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
  2. List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.


  1. How many objects are created in the following piece of code?

MyClass c1, c2, c3;

c1 = new MyClass ();

c3 = new MyClass ();

Answer: Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialized.


  1. What is UNICODE?

Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.


  1. What do you mean by platform independence of Java?

Platform independence means that you can run the same Java Program in any Operating System. For example, you can write java program in Windows and run it in Mac OS.


  1. What are the important features of Java 8 release?

Java 8 has been released in March 2014, so it’s one of the hot topic in java interview questions. If you answer this question clearly, it will show that you like to keep yourself up-to-date with the latest technologies.

Java 8 has been one of the biggest release after Java 5 annotations and generics. Some of the important features of Java 8 are:

  1. Interface changes with default and static methods
  2. Functional interfaces and Lambda Expressions
  3. Java Stream API for collection classes
  4. Java Date Time API

I strongly recommend to go through above links to get proper understanding of each one of them, also read Java 8 Features.


  1. What is JVM and is it platform independent?

Java Virtual Machine (JVM) is the heart of java programming language. JVM is responsible for converting byte code into machine readable code. JVM is not platform independent, thats why you have different JVM for different operating systems. We can customize JVM with Java Options, such as allocating minimum and maximum memory to JVM. It’s called virtual because it provides an interface that doesn’t depend on the underlying OS.


  1. What is the difference between JDK and JVM?

Java Development Kit (JDK) is for development purpose and JVM is a part of it to execute the java programs.

JDK provides all the tools, executables and binaries required to compile, debug and execute a Java Program. The execution part is handled by JVM to provide machine independence.


  1. What is the difference between JVM and JRE?

Java Runtime Environment (JRE) is the implementation of JVM. JRE consists of JVM and java binaries and other classes to execute any program successfully. JRE doesn’t contain any development tools like java compiler, debugger etc. If you want to execute any java program, you should have JRE installed.


  1. Which class is the superclass of all classes?

java.lang.Object is the root class for all the java classes and we don’t need to extend it.


  1. Why Java doesn’t support multiple inheritance?

Java doesn’t support multiple inheritance in classes because of “Diamond Problem”. To know more about diamond problem with example, read Multiple Inheritance in Java.

However multiple inheritance is supported in interfaces. An interface can extend multiple interfaces because they just declare the methods and implementation will be present in the implementing class. So there is no issue of diamond problem with interfaces.


  1. Why Java is not pure Object Oriented language?

Java is not said to be pure object oriented because it support primitive types such as int, byte, short, long etc. I believe it brings simplicity to the language while writing our code. Obviously java could have wrapper objects for the primitive types but just for the representation, they would not have provided any benefit.

As we know, for all the primitive types we have wrapper classes such as Integer, Long etc that provides some additional methods.

  1. What is difference between path and classpath variables?

PATH is an environment variable used by operating system to locate the executables. That’s why when we install Java or want any executable to be found by OS, we need to add the directory location in the PATH variable. If you work on Windows OS, read this post to learn how to setup PATH variable on Windows.

Classpath is specific to java and used by java executables to locate class files. We can provide the classpath location while running java application and it can be a directory, ZIP files, JAR files etc.


  1. What is the importance of main method in Java?

main() method is the entry point of any standalone java application. The syntax of main method is public static void main(String args[]).

main method is public and static so that java can access it without initializing the class. The input parameter is an array of String through which we can pass runtime arguments to the java program. Check this post to learn how to compile and run java program.


  1. What is overloading and overriding in java?

When we have more than one method with same name in a single class but the arguments are different, then it is called as method overloading.

Overriding concept comes in picture with inheritance when we have two methods with same signature, one in parent class and another in child class. We can use @Override annotation in the child class overridden method to make sure if parent class method is changed, so as child class.


  1. Can we overload main method?

Yes, we can have multiple methods with name “main” in a single class. However if we run the class, java runtime environment will look for main method with syntax as public static void main(String args[]).


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

We can’t have more than one public class in a single java source file. A single source file can have multiple classes that are not public.


  1. What is Java Package and which package is imported by default?

Java package is the mechanism to organize the java classes by grouping them. The grouping logic can be based on functionality or modules based. A java class fully classified name contains package and class name. For example, java.lang.Object is the fully classified name of Object class that is part of java.lang package.

java.lang package is imported by default and we don’t need to import any class from this package explicitly.


  1. What are access modifiers?

Java provides access control through public, private and protected access modifier keywords. When none of these are used, it’s called default access modifier.

A java class can only have public or default access modifier. Read Java Access Modifiers to learn more about these in detail.


  1. What is final keyword?

final keyword is used with Class to make sure no other class can extend it, for example String class is final and we can’t extend it.

We can use final keyword with methods to make sure child classes can’t override it.

final keyword can be used with variables to make sure that it can be assigned only once. However the state of the variable can be changed, for example we can assign a final variable to an object only once but the object variables can change later on.

Java interface variables are by default final and static.


  1. What is static keyword?

static keyword can be used with class level variables to make it global i.e all the objects will share the same variable.

static keyword can be used with methods also. A static method can access only static variables of class and invoke only static methods of the class.

Read more in detail at java static keyword.


  1. What is finally and finalize in java?

finally block is used with try-catch to put the code that you want to get executed always, even if any exception is thrown by the try-catch block. finally block is mostly used to release resources created in the try block.

finalize() is a special method in Object class that we can override in our classes. This method get’s called by garbage collector when the object is getting garbage collected. This method is usually overridden to release system resources when object is garbage collected.


  1. Can we declare a class as static?

We can’t declare a top-level class as static however an inner class can be declared as static. If inner class is declared as static, it’s called static nested class.

Static nested class is same as any other top-level class and is nested for only packaging convenience.

Read more about inner classes at java inner class.


  1. What is static import?

If we have to use any static variable or method from other class, usually we import the class and then use the method/variable with class name.

import java.lang.Math;


//inside class

double test = Math.PI * 5;

We can do the same thing by importing the static method or variable only and then use it in the class as if it belongs to it.

import static java.lang.Math.PI;


//no need to refer class now

double test = PI * 5;

Use of static import can cause confusion, so it’s better to avoid it. Overuse of static import can make your program unreadable and unmaintainable.


  1. What is try-with-resources in java?

One of the Java 7 features is try-with-resources statement for automatic resource management. Before Java 7, there was no auto resource management and we should explicitly close the resource. Usually, it was done in the finally block of a try-catch statement. This approach used to cause memory leaks when we forgot to close the resource.

From Java 7, we can create resources inside try block and use it. Java takes care of closing it as soon as try-catch block gets finished. Read more at Java Automatic Resource Management.


  1. What is multi-catch block in java?

Java 7 one of the improvement was multi-catch block where we can catch multiple exceptions in a single catch block. This makes are code shorter and cleaner when every catch block has similar code.

If a catch block handles multiple exception, you can separate them using a pipe (|) and in this case exception parameter (ex) is final, so you can’t change it.

Read more at Java multi catch block.


  1. What is static block?

Java static block is the group of statements that gets executed when the class is loaded into memory by Java ClassLoader. It is used to initialize static variables of the class. Mostly it’s used to create static resources when class is loaded.


  1. What is an interface?

Interfaces are core part of java programming language and used a lot not only in JDK but also java design patterns, most of the frameworks and tools. Interfaces provide a way to achieve abstraction in java and used to define the contract for the subclasses to implement.

Interfaces are good for starting point to define Type and create top level hierarchy in our code. Since a java class can implements multiple interfaces, it’s better to use interfaces as super class in most of the cases. Read more at java interface.


  1. What is an abstract class?

Abstract classes are used in java to create a class with some default method implementation for subclasses. An abstract class can have abstract method without body and it can have methods with implementation also.

abstract keyword is used to create a abstract class. Abstract classes can’t be instantiated and mostly used to provide base for sub-classes to extend and implement the abstract methods and override or use the implemented methods in abstract class. Read important points about abstract classes at java abstract class.


  1. What is the difference between abstract class and interface?

abstract keyword is used to create abstract class whereas interface is the keyword for interfaces.

Abstract classes can have method implementations whereas interfaces can’t.

A class can extend only one abstract class but it can implement multiple interfaces.

We can run abstract class if it has main() method whereas we can’t run an interface.

Some more differences in detail are at Difference between Abstract Class and Interface.


  1. Can an interface implement or extend another interface?

Interfaces don’t implement another interface, they extend it. Since interfaces can’t have method implementations, there is no issue of diamond problem. That’s why we have multiple inheritance in interfaces i.e an interface can extend multiple interfaces.


  1. What is Marker interface?

A marker interface is an empty interface without any method but used to force some functionality in implementing classes by Java. Some of the well known marker interfaces are Serializable and Cloneable.


  1. What are Wrapper classes?

Java wrapper classes are the Object representation of eight primitive types in java. All the wrapper classes in java are immutable and final. Java 5 autoboxing and unboxing allows easy conversion between primitive types and their corresponding wrapper classes.


  1. What is Enum in Java?

Enum was introduced in Java 1.5 as a new type whose fields consists of fixed set of constants. For example, in Java we can create Direction as enum with fixed fields as EAST, WEST, NORTH, SOUTH.

Enum is the keyword to create an enum type and similar to class. Enum constants are implicitly static and final. Read more in detail at java enum.


  1. What is Java Annotations?

Java Annotations provide information about the code and they have no direct effect on the code they annotate. Annotations are introduced in Java 5. Annotation is metadata about the program embedded in the program itself. It can be parsed by the annotation parsing tool or by compiler. We can also specify annotation availability to either compile time only or till runtime also. Java Built-in annotations are @Override, @Deprecated and @SuppressWarnings. Read more at java annotations.


  1. What is Java Reflection API? Why it’s so important to have?

Java Reflection API provides ability to inspect and modify the runtime behavior of java application. We can inspect a java class, interface, enum and get their methods and field details. Reflection API is an advanced topic and we should avoid it in normal programming. Reflection API usage can break the design pattern such as Singleton pattern by invoking the private constructor i.e violating the rules of access modifiers.

Even though we don’t use Reflection API in normal programming, it’s very important to have. We can’t have any frameworks such as Spring, Hibernate or servers such as Tomcat, JBoss without Reflection API. They invoke the appropriate methods and instantiate classes through reflection API and use it a lot for other processing.

Read Java Reflection Tutorial to get in-depth knowledge of reflection api.

  1. What is composition in java?

Composition is the design technique to implement has-a relationship in classes. We can use Object composition for code reuse.

Java composition is achieved by using instance variables that refers to other objects. Benefit of using composition is that we can control the visibility of other object to client classes and reuse only what we need. Read more with example at Java Composition example.


  1. What is the benefit of Composition over Inheritance?

One of the best practices of java programming is to “favor composition over inheritance”. Some of the possible reasons are:

  • Any change in the superclass might affect subclass even though we might not be using the superclass methods. For example, if we have a method test() in subclass and suddenly somebody introduces a method test() in superclass, we will get compilation errors in subclass. Composition will never face this issue because we are using only what methods we need.
  • Inheritance exposes all the super class methods and variables to client and if we have no control in designing superclass, it can lead to security holes. Composition allows us to provide restricted access to the methods and hence more secure.
  • We can get runtime binding in composition where inheritance binds the classes at compile time. So composition provides flexibility in invocation of methods.

You can read more about above benefits of composition over inheritance at java composition vs inheritance.


  1. How to sort a collection of custom Objects in Java?

We need to implement Comparable interface to support sorting of custom objects in a collection. Comparable interface has compareTo(T obj) method which is used by sorting methods and by providing this method implementation, we can provide default way to sort custom objects collection.

However, if you want to sort based on different criteria, such as sorting an Employees collection based on salary or age, then we can create Comparator instances and pass it as sorting methodology. For more details read Java Comparable and Comparator.


  1. What is inner class in java?

We can define a class inside a class and they are called nested classes. Any non-static nested class is known as inner class. Inner classes are associated with the object of the class and they can access all the variables and methods of the outer class. Since inner classes are associated with instance, we can’t have any static variables in them.

We can have local inner class or anonymous inner class inside a class. For more details read java inner class.


  1. What is anonymous inner class?

A local inner class without name is known as anonymous inner class. An anonymous class is defined and instantiated in a single statement. Anonymous inner class always extend a class or implement an interface.

Since an anonymous class has no name, it is not possible to define a constructor for an anonymous class. Anonymous inner classes are accessible only at the point where it is defined.


  1. What is Classloader in Java?

Java Classloader is the program that loads byte code program into memory when we want to access any class. We can create our own classloader by extending ClassLoader class and overriding loadClass(String name) method. Learn more at java classloader.


  1. What are different types of classloaders?

There are three types of built-in Class Loaders in Java:

  • Bootstrap Class Loader – It loads JDK internal classes, typically loads rt.jar and other core classes.
  • Extensions Class Loader – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
  • System Class Loader – It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command line options.


  1. What is ternary operator in java?

Java ternary operator is the only conditional operator that takes three operands. It’s a one liner replacement for if-then-else statement and used a lot in java programming. We can use ternary operator if-else conditions or even switch conditions using nested ternary operators. An example can be found at java ternary operator.


  1. What does super keyword do?

Super keyword can be used to access super class method when you have overridden the method in the child class.

We can use super keyword to invoke super class constructor in child class constructor but in this case it should be the first statement in the constructor method.

package com.journaldev.access;

public class SuperClass {

public SuperClass(){


public SuperClass(int i){}

public void test(){

System.out.println(“super class test method”);



Use of super keyword can be seen in below child class implementation.

package com.journaldev.access;

public class ChildClass extends SuperClass {

public ChildClass(String str){

//access super class constructor with super keyword


//access child class method


//use super to access super class method




public void test(){

System.out.println(“child class test method”);




  1. What is break and continue statement?

We can use break statement to terminate for, while, or do-while loop. We can use break statement in switch statement to exit the switch case. You can see the example of break statement at java break. We can use break with label to terminate the nested loops.

The continue statement skips the current iteration of a for, while or do-while loop. We can use continue statement with label to skip the current iteration of outermost loop.


  1. What is this keyword?

This keyword provides reference to the current object and it’s mostly used to make sure that object variables are used, not the local variables having same name.


public Point(int x, int y) {

this.x = x;

this.y = y;


We can also use this keyword to invoke other constructors from a constructor.

public Rectangle() {

this(0, 0, 0, 0);


public Rectangle(int width, int height) {

this(0, 0, width, height);


public Rectangle(int x, int y, int width, int height) {

this.x = x;

this.y = y;

this.width = width;

this.height = height;



  1. What is default constructor?

No argument constructor of a class is known as default constructor. When we don’t define any constructor for the class, java compiler automatically creates the default no-args constructor for the class. If there are other constructors defined, then compiler won’t create default constructor for us.


  1. Can we have try without catch block?

Yes, we can have try-finally statement and hence avoiding catch block.


  1. What is Garbage Collection?

Garbage Collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. In Java, process of deallocating memory is handled automatically by the garbage collector.

We can run the garbage collector with code Runtime.getRuntime().gc() or use utility method System.gc(). For a detailed analysis of Heap Memory and Garbage Collection, please read Java Garbage Collection.

  1. What is Serialization and Deserialization?

We can convert a Java object to an Stream that is called Serialization. Once an object is converted to Stream, it can be saved to file or send over the network or used in socket connections.

The object should implement Serializable interface and we can use to write object to file or to any OutputStream object. Read more at Java Serialization.

The process of converting stream data created through serialization to Object is called deserialization. Read more at Java Deserialization.


  1. How to run a JAR file through command prompt?

We can run a jar file using java command but it requires Main-Class entry in jar manifest file. Main-Class is the entry point of the jar and used by java command to execute the class. Learn more at java jar file.


  1. What is the use of System class?

Java System Class is one of the core classes. One of the easiest way to log information for debugging is System.out.print() method.

System class is final so that we can’t subclass and override it’s behavior through inheritance. System class doesn’t provide any public constructors, so we can’t instantiate this class and that’s why all of it’s methods are static.

Some of the utility methods of System class are for array copy, get current time, reading environment variables. Read more at Java System Class.


  1. What is instance of keyword?

We can use instanceof keyword to check if an object belongs to a class or not. We should avoid it’s usage as much as possible. Sample usage is:

public static void main(String args[]){

Object str = new String(“abc”);


if(str instanceof String){

System.out.println(“String value:”+str);


if(str instanceof Integer){

System.out.println(“Integer value:”+str);



Since str is of type String at runtime, first if statement evaluates to true and second one to false.


  1. Can we use String with switch case?

One of the Java 7 feature was improvement of switch case of allow Strings. So if you are using Java 7 or higher version, you can use String in switch-case statements. Read more at Java switch-case String example.


  1. Java is Pass by Value or Pass by Reference?

This is a very confusing question, we know that object variables contain reference to the Objects in heap space. When we invoke any method, a copy of these variables is passed and gets stored in the stack memory of the method. We can test any language whether it’s pass by reference or pass by value through a simple generic swap method, to learn more read Java is Pass by Value and Not Pass by Reference.


  1. What is difference between Heap and Stack Memory?

Major difference between Heap and Stack memory are as follows:

  • Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
  • Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
  • Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally.

For a detailed explanation with a sample program, read Java Heap vs Stack Memory.


  1. Java Compiler is stored in JDK, JRE or JVM?

The task of java compiler is to convert java program into bytecode, we have javac executable for that. So it must be stored in JDK, we don’t need it in JRE and JVM is just the specs.


  1. What will be the output of following programs?

static method in class

package com.journaldev.util;

public class Test {

public static String toString(){

System.out.println(“Test toString called”);

return “”;


public static void main(String args[]){




Answer: The code won’t compile because we can’t have an Object class method with static keyword. Note that Object class has toString() method. You will get compile time error as “This static method cannot hide the instance method from Object”. The reason is that static method belongs to class and since every class base is Object, we can’t have same method in instance as well as in class. You won’t get this error if you change the method name from toString() to something else that is not present in super class Object.


  1. What is the output of following program?

static method invocation

package com.journaldev.util;

public class Test {

public static String foo(){

System.out.println(“Test foo called”);

return “”;


public static void main(String args[]){

Test obj = null;




Answer: Well this is a strange situation. We all have seen NullPointerException when we invoke a method on object that is NULL. But here this program will work and prints “Test foo called”.

The reason for this is the java compiler code optimization. When the java code is compiled to produced byte code, it figures out that foo() is a static method and should be called using class. So it changes the method call to and hence no NullPointerException.

I must admit that it’s a very tricky question and if you are interviewing someone, this will blow his mind off.


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

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


  1. Explain Final keyword in java?

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

Variable: Value of Final variable is constant, you can not change it.

Method: you can’t override a Final method.

Class: you can’t inherit from Final class.

Refer this for details


  1. When is the super keyword used?

Super keyword is used to refer:

             immediate parent class constructor,

             immediate parent class variable,

             immediate parent class method.

Refer this for details.


  1. What is the difference between StringBuffer and String?

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

Refer this for details.


  1. Why multiple inheritance is not supported in java?

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


  1. Can a top level class be private or protected?

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


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

Following are the differences between two:

             throw keyword is used to throw Exception from any method or static block whereas throws is used to indicate that which Exception can possibly be thrown by this method

             If any method throws checked Exception, then caller can either handle this exception(using try catch block )or can re throw it by declaring another ‘throws’ clause in method declaration.

             throw clause can be used in any part of code where you feel a specific exception needs to be thrown to the calling method



throw new Exception(“You have some exception”)

throw new IOException(“Connection failed!!”)


throws IOException, NullPointerException, ArithmeticException


  1. What is finalize() method?

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


  1. Difference in Set and List interface?

Set and List both are child interface of Collection interface. There are following two main differences between them

             List can hold duplicate values but Set doesn’t allow this.

             In List interface data is present in the order you inserted but in the case of Set insertion order is not preserved.


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

By Calling System.exit(0) in try or catch block, we can skip the finally block. System.exit(int) method can throw a SecurityException. If Sysytem.exit(0) exits the JVM without throwing that exception then finally block will not execute. But, if System.exit(0) does throw security exception then finally block will be executed.