Java Interview Questions

What is Encapsulation?
Answer Encapsulation provides objects with the ability to hide their internal characteristics and behavior. Each object provides a number
of methods, which can be accessed by other objects and change its internal data. In Java, there are three access modifiers: public, private and protected. Each modifier imposes different access rights to other classes, either in the same or in external packages.
Some of the advantages of using encapsulation are listed below:
• The internal state of every objected is protected by hiding its attributes.
• It increases usability and maintenance of code, because the behavior of an object can be independently changed or extended.
• It improves modularity by preventing objects to interact with each other, in an undesired way.
You can refer to our tutorial here for more details and examples on encapsulation.

What is Polymorphism?
Answer Polymorphism is the ability of programming languages to present the same interface for differing underlying data types. A polymorphic type is a type whose operations can also be applied to values of some other type.

What is Inheritance?
Answer Inheritance provides an object with the ability to acquire the fields and methods of another class, called base class. Inheritance provides re-usability of code and can be used to add additional features to an existing class, without modifying it.

What is Abstraction?
Answer Abstraction is the process of separating ideas from specific instances and thus, develop classes in terms of their own functionality, instead of their implementation details. Java supports the creation and existence of abstract classes that expose interfaces, without including the actual implementation of all methods. The abstraction technique aims to separate the implementation details of a class from its behavior.

Differences between Abstraction and Encapsulation
Answer Abstraction and encapsulation are complementary concepts. On the one hand, abstraction focuses on the behavior of an object. On the other hand, encapsulation focuses on the implementation of an object’s behavior. Encapsulation is usually achieved by hiding information about the internal state of an object and thus, can be seen as a strategy used in order to provide abstraction.

Can there be an abstract class with no abstract methods in it?
Answer Yes

Can an Interface be final?
Answer No

Can an Interface have an inner class?
Answer Yes.

Can there be an abstract class with no abstract methods in it?
Answer Yes

Can an Interface be final?
Answer No


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

What is the query used to display all tables names in SQL Server (Query analyzer)?
Answer select * from information_schema.tables

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

What modifiers are allowed for methods in an Interface?
Answer Only public and abstract modifiers are allowed for methods in interfaces.

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

How many types of JDBC Drivers are present and what are they?
Answer There are 4 types of JDBC Drivers
Type 1: JDBC-ODBC Bridge Driver
Type 2: Native API Partly Java Driver
Type 3: Network protocol Driver
Type 4: JDBC Net pure Java Driver

Can we implement an interface in a JSP?
Answer No

What is the difference between ServletContext and PageContext?
Answer
ServletContext: Gives the information about the container
PageContext: Gives the information about the Request

What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
Answer request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.

How to pass information from JSP to included JSP?
Answer Using <%jsp:param> tag.

What is the difference between directive include and jsp include?
Answer <%@ include> : Used to include static resources during translation time.
: Used to include dynamic content or static content during runtime.

What is the difference between RequestDispatcher and sendRedirect?
Answer RequestDispatcher: server-side redirect with request and response objects.
sendRedirect : Client-side redirect with new request and response objects.

How does JSP handle runtime exceptions?
Answer Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.

How do you delete a Cookie within a JSP?

What is Function Overriding and Overloading in Java ?
Answer Method overloading in Java occurs when two or more methods in the same class have the exact same name, but different parameters. On the other hand, method overriding is defined as the case when a child class redefines the same method as a parent class. Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides.

What is a Constructor, Constructor Overloading in Java and Copy-Constructor
Answer A constructor gets invoked when a new object is created. Every class has a constructor. In case the programmer does not provide a constructor for a class, the Java compiler (Javac) creates a default constructor for that class. The constructor overloading is similar to method overloading in Java. Different constructors can be created for a single class. Each constructor must have its own unique parameter list. Finally, Java does support copy constructors like C++, but the difference lies in the fact that Java doesn’t create a default copy constructor if you don’t write your own.

Does Java support multiple inheritance ?
Answer No, Java does not support multiple inheritance. Each class is able to extend only on one class, but is able to implement more than one interfaces. That means Multiple inheritance can be achieved using interface.

What is the difference between an Interface and an Abstract class ?
Answer Java provides and supports the creation both of abstract classes and interfaces. Both implementations share some common
characteristics, but they differ in the following features:
• All methods in an interface are implicitly abstract. On the other hand, an abstract class may contain both abstract and nonabstract methods.
• A class may implement a number of Interfaces, but can extend only one abstract class.
• In order for a class to implement an interface, it must implement all its declared methods. However, a class may not implement all declared methods of an abstract class. Though, in this case, the sub-class must also be declared as abstract.
• Abstract classes can implement interfaces without even providing the implementation of interface methods.
• Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
• Members of a Java interface are public by default. A member of an abstract class can either be private, protected or public.
• An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated, but can be invoked if it contains a main method.

What are pass by reference and pass by value ?
Answer When an object is passed by value, this means that a copy of the object is passed. Thus, even if changes are made to that object, it doesn’t affect the original value. When an object is passed by reference, this means that the actual object is not passed, rather a reference of the object is passed. Thus, any changes made by the external method, are also reflected in all places.

Basic Java Interview Questions

Q) Is Java platform independent?

Yes. Java is a platform independent language. We can write java code on one platform and run it on another platform. For e.g. we can write and compile the code on windows and can run the generated bytecode on Linux or any other supported platform. This is one of the main features of java.

Q) What all memory areas are allocated by JVM?

Classloader, Class area, Heap, Stack, Program Counter Register and Native Method Stack

Q) Java vs. C ++?

Here are the few differences between Java and C++:

  • Platform dependency – C++ is platform dependent while java is platform independent
  • No goto support – Java doesn’t support goto statement while C++ does.
  • Multiple inheritance – C++ supports multiple inheritance while java does not.
  • Multithreading – C++ does not have in-build thread support, on the other hand java supports multithreading
  • Virtual keyword – C++ has virtual keyword, it determines if a member function of a class can be overridden in its child class. In java there is no concept of virtual keyword.

Q) Explain public static void main(String args[])

Here public is an access modifier, which means that this method is accessible by any class.

static – static keyword tells that this method can be accessed without creating the instance of the class. 

void – this main method returns no value.

main – It is the name of the method.

String args[] – The args is an array of String type. This contains the command line arguments that we can pass while running the program.

Q) What is javac ?

The javac is a compiler that compiles the source code of your program and generates bytecode. In simple words javac produces the java byte code from the source code written *.java file. JVM executes the bytecode to run the program.

Q) What is class?

A class is a blueprint or template or prototype from which you can create the object of that class. A class has set of properties and methods that are common to its objects.

Q) What is the base class of all classes?

java.lang.Object is the base class (super class) of all classes in java.

Q) What is a wrapper class in Java?

A wrapper class converts the primitive data type such as int, byte, char, boolean etc. to the objects of their respective classes such as Integer, Byte, Character, Boolean etc. 

Q) What is a path and classPath in Java?

Path specifies the location of .exe files. Classpath specifies the location of bytecode (.class files).

Q) Different Data types in Java.

  • byte – 8 bit
  • short – 16 bit
  • char – 16 bit Unicode
  • int – 32 bit (whole number)
  • float – 32 bit (real number)
  • long – 64 bit (Single precision)
  • double – 64 bit (double precision)

Q) What is Unicode?

Java uses Unicode to represent the characters. Unicode defines a fully international character set that can represent all of the characters found in human languages.

Q) What are Literals?

Any constant value that is assigned to a variable is called literal in Java. For example –

// Here 101 is a literal
int num = 101

Q) Dynamic Initialization?

Dynamic initialization is process in which initialization value of a variable isn’t known at compile-time. It’s computed at runtime to initialize the variable.

Q) What is Type casting in Java?

When we assign a value of one data type to the different data type then these two data types may not be compatible and needs a conversion. If the data types are compatible (for example assigning int value to long) then java does automatic conversion and does not require casting. However if the data types are not compatible then they need to be casted for conversion.

For example:

//here in the brackets we have mentioned long keyword, this is casting
double num = 10001.99;
long num2 = (long)num;

Q) What is an Array?

An array is a collection (group) of fixed number of items. Array is a homogeneous data structure which means we can store multiple values of same type in an array but it can’t contain multiple values of different types. For example an array of int type can only hold integer values.

Q) What is BREAK statement in java?

The break statement is used to break the flow sequence in Java.

  • break statement is generally used with switch case data structure to come out of the statement once a case is executed.
  • It can be used to come out of the loop in Java

Q) Arrays can be defined in different ways. Write them down.

int arr[];
int[] arr;

OOPs Interview Questions

Q) Four main principles of OOPS Concepts?

  • Inheritance
  • Polymorphism
  • Data Encapsulation
  • Abstraction

Q) What is inheritance?

The process by which one class acquires the properties and functionalities of another class is called inheritance. Inheritance brings reusability of code in a java application.

Q) Does Java support Multiple Inheritance?

When a class extends more than one classes then it is called multiple inheritance. Java doesn’t support multiple inheritance whereas C++ supports it, this is one of the difference between java and C++.  

Q) What is Polymorphism and what are the types of it?

Polymorphism is the ability of an object to take many forms. The most common use of polymorphism in OOPs is to have more than one method with the same name in a single class. There are two types of polymorphism: static polymorphism and dynamic polymorphism. Refer these guides to understand the polymorphism concept in detail: 1) Java Polymorphism 2) Types of Polymorphism

Q) What is method overriding in Java?

When a sub class (child class) overrides the method of super class(parent class) then it is called overriding. To override a method, the signature of method in child class must match with the method signature in parent class. 

Q) Can we override a static method?

No, we cannot override a static method in Java.

Q) What is method overloading?

When a class has more than one methods with the same name but different number, sequence or types of arguments then it is known as method overloading. 

Q) Does Java support operator overloading?

Operator overloading is not supported in Java.

Q) Can we overload a method by just changing the return type and without changing the signature of method?

No, We cannot do this. To overload a method, the method signature must be different, return type doesn’t play any role in method overloading.

Q) Is it possible to overload main() method of a class?

Yes, we can overload main() method in Java.

Q) What is static and dynamic binding in Java?

Binding refers to the linking of method call to its body. A binding that happens at compile time is known as static binding while binding at runtime is known as dynamic binding. 

Q) What is Encapsulation?

Wrapping of the data and code together is known as encapsulation.

Q) What is an abstract class in Java?

An abstract class is a class which can’t be instantiated (we cannot create the object of abstract class), we can only extend such classes. It provides the generalised form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. We can achieve partial abstraction using abstract classes, to achieve full abstraction we use interfaces.

Q) What is Interface in java?

An interface is used for achieving full abstraction. A class implements an interface, thereby inheriting the abstract methods of the interface. 

Q) What is the difference between abstract class and interface?

1) abstract class can have abstract and non-abstract methods. An interface can only have abstract methods.
2) An abstract class can have static methods but an interface cannot have static methods.
3) abstract class can have constructors but an interface cannot have constructors.

Q) Name the access modifiers that can be applied to the inner classes?

public ,private , abstract, final, protected.

Q) What is a constructor in Java?

Constructor is used for creating an instance of a class, they are invoked when an instance of class gets created. Constructor name and class name should be same and it doesn’t have a return type. 

Q) Can we inherit the constructors?

No, we cannot inherit constructors.

Q) Can we mark constructors final?

No, Constructor cannot be declared final.

Q) What is default and parameterized constructors?

Default: Constructors with no arguments are known as default constructors, when you don’t declare any constructor in a class, compiler creates a default one automatically.

Parameterized: Constructor with arguments are known as parameterized constructors.

Q) Can a constructor call another constructor?

Yes. A constructor can call the another constructor of same class using this keyword. For e.g. this() calls the default constructor.
Note: this() must be the first statement in the calling constructor.

Q) Can a constructor call the constructor of parent class?

Yes. In fact it happens by default. A child class constructor always calls the parent class constructor. However we can still call it using super keyword. For e.g. super() can be used for calling super class default constructor.

Note: super() must be the first statement in a constructor.

Q)THIS keyword?

The this keyword is a reference to the current object.

Q) Can this keyword be assigned null value?

No, this keyword cannot have null values assigned to it.

Q) Explain ways to pass the arguments in Java?

In java, arguments can be passed as call by value – Java only supports call by value, there is no concept of call by reference in Java.

Q) What is static variable in java?

Static variables are also known as class level variables. A static variable is same for all the objects of that particular class in which it is declared.

Q) What is static block?

A static block gets executed at the time of class loading. They are used for initializing static variables.

Q) What is a static method?

Static methods can be called directly without creating the instance (Object) of the class. A static method can access all the static variables of a class directly but it cannot access non-static variables without creating instance of class.

Q) Explain super keyword in Java?

super keyword references to the parent class. There are several uses of super keyword:

  • It can be used to call the superclass(Parent class) constructor.
  • It can be used to access a method of the superclass that has been hidden by subclass (Calling parent class version, In case of method overriding).
  • To call the constructor of parent class.

Q) Use of final keyword in Java?

Final methods – These methods cannot be overridden by any other method.
Final variable – Constants, the value of these variable can’t be changed, its fixed.
Final class – Such classes cannot be inherited by other classes. These type of classes will be used when application required security or someone don’t want that particular class. 

Q) What is a Object class?

This is a special class defined by java; all other classes are subclasses of object class. Object class is superclass of all other classes. Object class has the following methods

  • objectClone () – to creates a new object that is same as the object being cloned.
  • boolean equals(Object obj) – determines whether one object is equal to another.
  • finalize() – Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
  • toString () – Returns a string representation of the object.

Q) What are Packages in Java?

A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations). 

Q)What is the difference between import java.util.Date and java.util.* ?

The star form (java.util.* ) includes all the classes of that package and that may increase the compilation time – especially if you import several packages. However it doesn’t have any effect run-time performance.

Q) Garbage collection in java?

Since objects are dynamically allocated by using the new operator, java handles the de-allocation of the memory automatically, when no references to an object exist for a long time. This whole process is called garbage collection. The whole purpose of Garbage collection is efficient memory management.

Q) Use of finalize() method in java?

finalize() method is used to free the allocated resource.

Q) How many times does the garbage collector calls the finalize() method for an object?

The garbage collector calls the finalize() method only once for an object.

Q) What are two different ways to call garbage collector?

System.gc() OR Runtime.getRuntime().gc().

Q) Can the Garbage Collection be forced by any means?

No, its not possible. you cannot force garbage collection. you can call system.gc() methods for garbage collection but it does not guarantee that garbage collection would be done.

 

Exception handling Interview Questions


Q) What is an exception?

Exceptions are abnormal conditions that arise during execution of the program. It may occur due to wrong user input or wrong logic written by programmer.

Q) Exceptions are defined in which java package? OR which package has definitions for all the exception classes?

Java.lang.Exception
This package contains definitions for Exceptions.

Q) What are the types of exceptions?

There are two types of exceptions: checked and unchecked exceptions.
Checked exceptions: These exceptions must be handled by programmer otherwise the program would throw a compilation error.
Unchecked exceptions: It is up to the programmer to write the code in such a way to avoid unchecked exceptions. You would n