Basics of JAVA based Interview Questions
Q1). What do you understand by Class in Java?
Ans: A class is a blueprint or template for creating objects in object-oriented programming. It defines a group of objects that share common properties (attributes) and behaviors (methods). The class itself does not represent any specific object; instead, it provides the structure and behavior that will be shared by all instances (objects) created from that class. Each object created from the class has its own unique set of properties, though the class specifies their general form and initial values.
Class declaration have component mentioned below:
- Class name
- Modifiers
- Interface
- Super Clas
Class can Contains
- Methods
- Members
- Constructor
- Blocks
- Nested Class
- Nested Interface
Declaration of Class
class {
field;
method;
}
Q2). What do you understand by Object?
Ans : An object is a fundamental unit in object-oriented programming (OOP). It is an instance of a class, meaning it is created based on the structure defined by the class. In OOP, objects represent real-world entities and encapsulate both states (attributes or properties) and behaviors (methods or functions).
Each object has its own unique set of attributes, though it may share the same behaviors defined in the class. Objects make up the building blocks of OOP, enabling the modeling of complex systems by representing various entities in a program.
Objects have some characteristics :
1). State : State Reflects the properties of Objects. Just like Cat can be white, black or may be combination of both is its properties. State can be denoted by attributes.
2). Behaviour : Behaviours shows that how object is responding to other objects. Behaviour can be denoted by Methods.
3). Identity: Every objects should have unique identity. Like if we say cat then it may be a group of cat but If we talk about a particular cat then we need a identity for that particular cat.
Example using a Car class and an object created from it
Define a Class (Blueprint)
class Car {
// Properties (states) of the car
String color;
String model;
int year;
// Method (behavior) of the car
void drive() {
System.out.println("The car is driving.");
}
}
Create an Object (Instance of the Class)
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car();
// Setting properties of the object
myCar.color = "Red";
myCar.model = "Toyota Corolla";
myCar.year = 2021;
// Accessing the object's properties
System.out.println("Car Model: " + myCar.model);
System.out.println("Car Color: " + myCar.color);
System.out.println("Car Year: " + myCar.year);
// Calling the object's method
myCar.drive();
}
}
Explanation:
When we call myCar.drive()
, it outputs “The car is driving.”
Here, Car
is the class that defines properties like color
, model
, and year
, and a method drive()
.
myCar
is an object (or instance) of the Car
class. It has its own values for color
, model
, and year
.
Q3). Explain JDK, JVM and JRE.
JDK: JDK stands for Java Development Kit. It includes the JRE (Java Runtime Environment) and additional tools needed for developing Java applications, such as the compiler (javac) and debugger. It provides the development environment for Java, enabling developers to write, compile, and run Java programs.
JRE: JRE stands for Java Runtime Environment. It contains essential components to run Java applications, such as class libraries, the class loader, and the JVM (Java Virtual Machine). The main role of JRE is to provide the libraries and environment necessary to run Java applications. If you only want to run Java programs without developing them, you only need the JRE. The JRE is included in the JDK bundle, so you don’t need to download it separately if you have the JDK.
JVM: JVM stands for Java Virtual Machine, which provides the runtime environment to execute Java bytecode. The JVM is part of the JRE and plays a crucial role in converting Java bytecode into machine code specific to the host system. When you compile Java code, the Java compiler generates bytecode for the JVM, allowing Java to be platform-independent.
Q4). Explain Public Static void Main(String args[]) in Java.
Ans: public static void main(String args[])
is the entry point of any Java program. This method is where execution begins when the program runs.
String args[]: This is an array of String
type, representing the command-line arguments passed to the program. The args
array holds any arguments provided when the program starts.
public: This is an access modifier that allows the method to be accessible from any other class. Making main
public ensures that the JVM can access and run it.
static: This keyword makes the main
method a class-level method, meaning it can be called without creating an instance of the class. The JVM needs to call main
without creating an object, so it must be static.
void: This is the return type of the main
method. Declaring main
as void means it does not return any value to the calling function.
main: This is the name of the method that the JVM searches for as the entry point to start execution. The method signature must be public static void main
for the JVM to recognize it.
Q5). What is the different between Final, finally and finilize?
Ans:
Final: final is a modifier that can be applied to classes, methods, and variables. If the class is declared as final then the class is not extended by other class. If the method is declared as final then we cannot override that method in the child class. i.e. final method is not overridden by child class. If the variable is declared as final then it behave as a constant and we cannot re-assingment for that variable.
finally: finally is a block that always executes after a try-catch block, regardless of whether an exception was handled. This block is often used to perform important cleanup actions, like closing a file or releasing a database connection, ensuring that these actions are completed even if an exception occurs.
finalize(); :finalize()
is a method that performs cleanup operations before an object is destroyed by the garbage collector. The garbage collector calls finalize()
on an object before reclaiming its memory, allowing the object to release resources, if necessary. However, the finalize()
method is rarely used today due to better alternatives like try-with-resources
for resource management.
Q6). What is the difference between “==” and “equals()” method.
Ans:
==
Operator
The == operator is used for reference (or address) comparison in Java. When used with objects, it checks if both references point to the same memory location.
Example:
String str1=new String("prakash");
String str2=new String("prakash");
System.out.println(str1==str2);
output: false
equals() Method
The equals() method is used for content comparison. In the String class, equals() has been overridden to check if two strings contain the same sequence of characters, rather than comparing memory addresses.
Example:
String str1=new String("prakash");
String Str2=new String("prakash");
System.out.println(str1.equals(str2));
output: true
Q7). Why Java is called as platform independent ?
Ans: After the compilation of Java code, it is converted into bytecode by the Java compiler (javac
). This bytecode is an intermediate form of code, which is not specific to any one machine’s hardware. Instead, it can be run on any system that has a Java Virtual Machine (JVM). Since JVMs are available for many operating systems (such as Windows, Linux, and macOS), Java bytecode can be executed on different systems and environments without modification.
This ability to run the same bytecode on different platforms makes Java platform-independent. The slogan “write once, run anywhere” captures this idea, as Java code needs to be written and compiled only once to run on any device with a compatible JVM.
Q8). What is meant by Local variable and Instance variable?
Ans:
Local variables : Local variables are defined inside a method, constructor, or block, and their scope is limited to that specific method or block. They are created when the method or block is entered and are destroyed when it exits. Local variables cannot be accessed outside the method or block in which they are defined.
Instance variable : Instance variables are defined inside a class but outside any method, constructor, or block. They are associated with an instance of the class, meaning each object created from the class has its own copy of the instance variables. The scope of instance variables is throughout the class, and they can be accessed by any method in the class.
Oops Concept Interview Questions
Q1). Define Constructor.
Ans: In Java, A constructor is a method or block which is use to initialize the objects. Constructor should have same name as a name of class which have no return type. It is automatically called by java at the time of object creation.
There are 3 types of constructor
1). Default constructor: This constructor is automatically provided by Java when no constructors are explicitly declared in the class. It has no parameters and is not visible in the source code but allows object creation with default values.
2). Parameterised constructor : A constructor that accepts parameters is known as a parameterized constructor. This allows you to initialize objects with specific values at the time of creation.
3). No-arg Constructor : It is very similar to default constructor. We declare it when we want to perform some operation at a time of object creation or when we want to include specific initialization logic in your code, then we write that code in no-args constructor.
Q2). Explain access modifiers in Java.
Ans: Access modifiers is a keywords in Java that define the visibility and accessibility of classes, methods, and member variables.
There are four main access modifiers in Java:
- Public: The class, method, or variable is accessible from any other class in any package. There are no restrictions on visibility.
- Private: The method or variable is accessible only within the class it is defined in. It cannot be accessed from outside the class, even by subclasses.
- Protected: The method or variable is accessible within its own package and by subclasses, even if they are in different packages.
- Default (Package-Private): If no access modifier is specified, the method or variable has package-private access. It is accessible only within its own package.
Modifier | Default | Private | Protected | Public |
Same class | YES | YES | YES | YES |
Same Package subclass | YES | NO | YES | YES |
Same Package non-subclass | YES | NO | YES | YES |
Different package subclass | NO | NO | YES | YES |
Different package non-subclass | NO | NO | NO | YES |
Q3). Explain some features of oops.
Ans:
Inheritance: Inheritance is a process in which a child class (or subclass) acquires all the properties (fields) and behaviors (methods) of its parent class (or superclass). This relationship allows for code reusability and can simplify code management by enabling a hierarchical classification of classes. For example, if you have a class Animal with common properties, a subclass Dog can inherit these properties and behaviors from Animal.
Abstraction: Abstraction means hide the complexity and show the functionality. For examples in education portal you just sign up and then login by giving credential and then access your dashboard but you won’t aware of how its happening in backend. It is known as abstraction.
Encapsulation: Encapsulation is a process of binding the data and methods together in a single entity known as class for data safety.
Polymorphism: Polymorphism defines to perform single actions in multiple form. The term is derived from the Greek words “poly” (meaning many) and “morphs” (meaning forms) that means many forms.
Two types of Polymorphism:
- Method Overloading: This allows a class to have more than one method with the same name, differentiated by the method’s parameter list (number or type of parameters). For example, a method add(int a, int b) and add(double a, double b) can coexist in the same class.
- Method Overriding: This occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. This allows the subclass to customize or extend the behavior of that method.
Q4). What is this and super keyword in Java?
Ans:
This
The keyword this
is a reference variable in Java that refers to the current instance of the class. It is used to access the class’s member variables and methods, especially when there is a naming conflict between class attributes and method parameters or local variables. Using this helps to distinguish between instance variables and local variables.
Super
The keyword super
is used in Java to refer to the immediate parent class. It is commonly used to access the parent class’s members (variables and methods) that may be hidden by the child class. super is also used to call the parent class’s constructor when creating an instance of a subclass.
Q5). What is the different between static and non-static method of java?
Ans:
Static method
A static method is a method that belongs to the class rather than any specific instance of the class. You can access static methods directly using the class name, without needing to create an instance of the class. Static methods can only directly access static variables and other static methods. They cannot access instance (non-static) variables or methods directly.
Non-Static Method
A non-static method (also known as an instance method) belongs to instances (objects) of the class. It can access both instance variables (non-static variables) and static variables. Non-static methods can be called on instances of the class, and you can also call them from static methods, but you must first create an instance of the class.
class Example {
int instanceVariable = 20;
void nonStaticMethod() {
System.out.println("Non-Static Method Called. Instance Variable: " + instanceVariable);
}
static void staticMethod() {
Example obj = new Example(); // Creating an instance to access non-static method
obj.nonStaticMethod(); // Calling non-static method using the instance
}
}
public class Test {
public static void main(String[] args) {
Example.staticMethod(); // Calls the static method, which in turn calls the non-static method
}
}
Q6). What do you mean by Polymorphism?
Polymorphism is derived from two Greek words: “poly” (meaning many) and “morphs” (meaning forms). In the context of Java (and object-oriented programming), polymorphism allows a single task to be performed in multiple forms. This is achieved through the ability to have multiple methods with the same name but different functionalities.
Polymorphism in Java can be categorized into two main types:
The method to be called is determined at compile time based on the method signature (name and parameter types).
1). Compile-Time Polymorphism (also known as Method Overloading):
- This occurs when two or more methods in the same class have the same name but different parameter lists (different type, number, or both).
- The method to be called is determined at compile time based on the method signature (name and parameter types).
2). Runtime Polymorphism (also known as Method Overriding)
- The method that gets executed is determined at runtime based on the object’s actual class (the one that is being referenced).
- This occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
Q7). Explain Method Overloading and Method Overriding.
Ans:
Method Overloading
Method Overloading occurs when a class has multiple methods with the same name but different parameter lists (different number of parameters, types of parameters, or both). The methods must have different signatures, which includes the method name and the parameter list. Method overloading is a form of compile-time polymorphism since the method to be executed is determined during compilation based on the method signature.
Key Points:
- Return type alone is not sufficient to distinguish overloaded methods.
- Methods can have the same name but must differ in parameter type, number, or order.
Method Overriding
Method Overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The overridden method in the subclass must have the same name, return type, and parameter list as the method in the parent class. This is a form of runtime polymorphism since the method to be executed is determined at runtime based on the object type.
Key Points:
- Overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass.
- Both methods must have the same name, return type, and parameters.
- The method in the subclass is said to override the method in the parent class.
Q8). How many ways you can overload method?
Ans: There are various way to overload a method :
1) By Number of Parameters: You can overload a method by changing the number of parameters in the method signature.
add(int,int)
add(int,int,int)
2) By Changing the Data Type of Parameters: Overloading can also occur by changing the data types of the parameters.
add(int,int)
add(float,int)
3) By Changing the Sequence of Data Types: You can also overload a method by changing the order of the parameter types.
add(int, float)
add(float,int)
Q9). What is the some invalid cases of method overloading in java?
Ans: Some Invalid Cases are
1). If two methods have the same name, same number of parameters, and the same parameter types, it will lead to a compilation error because the compiler cannot distinguish between them.
2). If two methods have same name with different return types are not valid method overloading.
3). Changing only the access modifiers (e.g., public, private, protected) does not count as overloading since the method signature remains the same.
4). If one method uses varargs and another has fixed parameters of the same type, it can lead to ambiguity in method calls.
Q10). What do you mean by abstract class?
Ans: An abstract class is a class that is declared with the abstract
keyword. It serves as a blueprint for other classes and cannot be instantiated directly.
- An abstract class can contain both abstract methods (methods without a body) and non-abstract methods (methods with a body).
- Abstract methods must be implemented by any subclass that extends the abstract class.
- You cannot create an instance of an abstract class. This means you cannot use the
new
keyword to instantiate an abstract class directly.
Q11). What do you mean by Interface?
Ans: Interface is a blueprint of class that have abstract and public methods without body. Class that implements interface should implement all methods of interface.
public interface Man {
public void eat();
public void sleep();
public void walk();
}
Java String Interview Questions
Q1). Difference between String and StringBuffer.
Ans:
String: String object is immutable but the StringBuffer objects are mutable. Immutable means once we create a String object we cannot perform any changes on object.
Example of String:
String str=new String("prakash");
str.concat("kumar");
System.out.println(str);
output:- prakash
Example of StringBuffer:
StringBuffer strbfr=new StringBuffer("prakash");
strbfr.append("kumar");
System.out.println(strbfr);
output:- prakash kumar
Q2). Difference between StringBuffer and StringBuilder.
Ans: Both StringBuffer and StringBuilder are mutable.
StringBuffer:
All method of StringBuffer is synchronized. As it is synchronized, it is also thread-safe. Thread-Safe means two threads can’t call the StringBuffer method simultaneously. Its performance is low because every task is dependent on the other.
Example:
StringBuffer strbuffer=new StringBuffer("java");
strbuffer.append("developer");
System.out.println(strbuffer);
StringBuilder:
Methods are not synchronized so it is not thread-safe. It means two threads can call the string builder method simultaneously. Its performance is high because more than one thread can be allowed.
Example:
StringBuilder strBuilder=new StringBuilder("java");
strBuilder.append("developer");
System.out.println(strBuilder);
Q3). Difference between String, StringBuilder, and StringBuffer.
Factor |
String |
StringBuilder |
StringBuffer |
Storage Area |
Constant String Pool |
Heap Area |
Heap Area |
Mutability |
Immutable |
Mutable |
Mutable |
Thread Safety |
Yes |
No |
Yes |
Performance |
Fast |
More efficient |
Less efficient |
Java Array & Collection Interview Questions
Q1). Difference between Array and Array List.
Ans:
Array
- Definition: An array is a fixed-size data structure that holds elements of the same type. The size of the array is determined at the time of declaration and cannot be changed thereafter.
- Data Types: Arrays can store both primitive data types (like int, char, float, etc.) and objects (like String, ArrayList, etc.).
Example
int arr[] = new int[3];
arr[0]=10;
arr[1]=20;
arr[2]=70;
Arrays.stream(arr).forEach(e->System.out.print(e + " "));
ArrayList
- Definition: An ArrayList is a part of the Java Collections Framework. It is a resizable array that can grow and shrink dynamically, unlike a standard array.
- Data Types: ArrayList can only contain objects. However, with the introduction of autoboxing in Java 5, primitive types can be automatically converted into their corresponding wrapper classes (e.g., int to Integer).
ArrayList<Integer> arrList = new ArrayList<Integer>(3);
for (int i = 1; i <= 3; i++)
arrList.add(i);
arrList.stream().forEach(e->System.out.print(e + " "));
Q2). What do you mean by Collections in Java.
Ans: The Java Collections Framework is a unified architecture for representing and manipulating collections of objects. It provides a set of classes and interfaces that enable developers to store, retrieve, manipulate, and communicate aggregate data in a standard way.
Interfaces comes with Collection framework:
- Collection: The root interface in the collection hierarchy, which represents a group of objects.
- List: An ordered collection that can contain duplicate elements. Common implementations include
ArrayList
andLinkedList
. - Set: A collection that does not allow duplicate elements. Implementations include
HashSet
andTreeSet
. - Map: An object that maps keys to values, where each key is unique. Implementations include
HashMap
andTreeMap
.
Classes comes with Collection framework:
- ArrayList
- LinkedList
- HashSet
- TreeSet
- LinkedHashSet etc.
Q3). Explain the lists that are present in Java Collection.
Ans:
Types of Lists are:
1). ArrayList
- Fast iteration and fast Random Access
- It is an ordered collection.
- It is not sorted collection.
2). Linked List
- Performance is slow than ArrayList.
- Maintain the Insertion Order.
- It can have duplicate values
3). Vector
- Similar as ArrayList.
- Maintain the Insertion Order.
- It can have duplicate values.
- Its Methods are Synchronized.
Q4). Explain the Set and their types in a Java Collection.
Ans: Set cares of uniqueness, It means that it does not allow duplicate value.
Types of Set in Java Collection are:
1). Hash Set
- HashSet is unordered and unsorted.
- It uses the hash code of the object to insert the values.
- We can use Hash Set when order is not concerned and we want no duplicate value.
2). Linked Hash set
- It maintains the insertion order.
- Does not allows duplicate value.
- It can be used when iteration order is required.
3). Tree Set
- It sorts the elements in ascending order.
- It does not allow duplicate values.
Q5). Difference between HashMap and HashTable
Ans:
HashMap | HashTable |
---|---|
1. HashMap is non synchronized | 1. HashTable is synchronized |
2. HashMap allows NULL Key and Value. | 2. HashTable does not allows any NULL Key and Value. |
3. Performance of HashMap is fast. | 3. HashTable is slow. |
4. HashMap inherits class AbstractMap. | 4. HashTable inherits class Dictionary. |
5. We can traverse HashMap using Iterator. | 5. We can traverse HashTable using Iterator and Enumerator. |
Q6). Difference between HashSet and TreeSet.
Ans:
HashSet | TreeSet |
---|---|
1. HashSet is faster and gives better performace. | 1. TreeSet is little bit slower than HashSet. |
2. HashSet performs operation in constant time | 2. TreeSet performs operation in Log(n) time. |
3. HashSet does not follow any order | 3. TreeSet elements are arranged in ascending order. |
4. HashSet does not hold duplicate value. | 4. TreeSet also does not hold duplicate value. |
Q7). Difference between Collection and Collections in Java.
Ans:
Collection:
The Collection is an interface in the Java Collections Framework that represents a group of objects (elements). It is the root of the collection hierarchy. It provides a way to store, retrieve, manipulate, and communicate with groups of objects. It defines the basic operations that all collection classes (like List, Set, and Queue) should implement.
After Java 8, Collection can contain a static method and abstract and default method.
Collections:
Collections is a utility class in the Java Collections Framework that provides static methods to operate on or return collections. It is part of the java.util
package.
It contains methods for sorting, searching, reversing, shuffling, and performing other operations on collections. It does not store elements itself but provides helpful methods to manipulate existing collections. It contains static methods like sort()
, shuffle()
, reverse()
, max()
, min()
, etc.