0% found this document useful (0 votes)
2 views29 pages

Java Interview Questions

Uploaded by

sundarmatsa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views29 pages

Java Interview Questions

Uploaded by

sundarmatsa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

Basic Questions

1. What is java?
Answer: Java is high-level, Robust, Object-oriented, secure programming language. It was
developed by James Gosling in the year 1995.
2. What are the key features of java?
Answer:
- Simple.
- Robust.
- Secure.
- Multithreading.
- Object-oriented
- Platform independent
- High performance
3. Why java is platform independent?
Answer: Because the java compiler converts the java programs into a byte code that can be run
on any device which means you can write java programs on one platform and run it on any
platform without making any changes.
4. Explain each keyword in main() method?
Answer:
Class: Class is a keyword that can be used to declare a class in java.
Public: it is an access specifier that represents the visibility that means the main method is
accessible everywhere.
Static: static is a keyword. If you declare a method as static, it is known as static method. We don’t
need to create an object to call static method.
Void: void is return type of the method that means it doesn’t return anything.
Main: main is the name of the method.
String args[]: this is an array of strings passed as command line arguments.
5. What is JVM?
Answer: java virtual machine is a runtime environment that can executes java bytecode.
6. What are the applications of java?
Answer:
- web applications like irctc.in etc.
- mobile applications.
- Desktop applications like media player, antivirus etc.
- Embedded systems.
- Robotics
- Games (Minecraft).
7. What is the difference between JDK and JRE?
Answer:
JDK: Java development kit is a software development kit which is used to develop java applications
and applets including JRE, the compilers and tools like debuggers etc.
jRE: JRE is the implementation of JVM where the java programs are being executed.
8. What is variable? Types and explain its types?
Answer: A variable is a container which holds the value while java program is executed. There are
three types of variables in java:
Local variable: A variable which is declared inside the body of the method is called local variable.
You can use only within the method.
Instance variable: A variable which is declared inside the class but outside the body of the method
is called instance variable.
Static variable: A variable which is declared as static is called static variable.
9. What is datatype in java & what are the datatypes are supported by java?
Answer: Datatype in java is a classification that specifies what type of data a variable can hold.
There are two types of datatypes: primitive and non-primitive datatypes.
Primitive datatypes (8): boolean, byte, short, int, long, float, double, char
Non-primitives: string, arrays etc.
10. What is autoboxing and Unboxing?
Answer: autoboxing is the automatic conversion made by the compiler between the primitives
and their corresponding object wrapper classes. For example, the compiler converts an int to an
Integer, a double to a Double.
Unboxing is the conversion of the object wrapper classes to their corresponding primitive types.
11. What is pass by reference and pass by value?
Answer:
12. What are operators in java?
Answer: Operators in java is a symbol which can be used to perform operations.
13. What is “null” keyword in java?
Answer: null keyword is used to represents the absence of a value.
14. What is type casting in java?
Answer: type casting is the process of converting one data type to another data type either
implicitly or explicitly.
Implicit type casting: is the conversion of smaller data type to longer data type. Ex, int to long.
Explicit type casting: conversion of larger data type to smaller. Ex, long to int.
15. What is Java keyword?
Answer: java keywords are also known as reserve words that can act as a key to code. Ex, abstract,
final, static etc.
16. What is the “stack” and “heap” in memory management in java?
Answer:
17. What is “constant pool” in java?
Answer: The constant pool is a special area in memory which can be used to store string literals
and constants.
18. What are the differences between C++ and Java?
Answer:
- C++ is a platform dependent, while java is platform independent.
- C++ is mainly used for system applications, while java used for application programming.it is
widely used in windows, web and mobile applications.
- C++ supports multiple inheritance, while java does not support multiple inheritance.
19. What is platform?
Answer: A platform is the hardware or software environment in which a piece of software is
executed. There are two types of platforms, such as hardware-based and software-based. Java
provides software-based platform.
20. What is classloader?
Answer: A classloader is a subsystem in JVM which is used to load the class files.
21. What are the various access specifiers in java?
Answer: The access specifiers are the keywords which are used to define the scope of the
methods, classes, or variables. In java there are four types of access specifiers.
- Public: it can be accessed everywhere. It can be accessed within the package, outside the
package, within the class and outside the class.
- Protected: it can be accessed within the package and outside the package through child class.
If you do not make a child class, it cannot be accessed from outside the package.
- Default: it can be accessed from only within the package. It cannot be accessed outside the
package.
- Private: it can be accessed from within the class and it cannot be accessed outside the class
22. What is the purpose of static methods and variables?
Answer: A methods or variables is defined as static are shared among the all the objects in the
class. The static is the class and not of the object. The static variable is stored in class area, we do
not need to create an object to access such variables.
23. What are the advantages of Packages in Java?
Answer:
- The packages avoid the name clashes.
- Packages provides easier access control.
- It is easier to locate related classes.
24. What is call by value and call by reference?
Answer:
Call by value: is a method of passing arguments to a function where a copy of the actual
parameters. value is passed. Changes made to the parameter inside the function do not affect the
original arguments.
Call by reference: is a method of passing the arguments to a function where a reference of the
actual parameters is passed. Changes made to the parameter inside the function affect the original
arguments.
25. Why java is not pure object oriented?
Answer: Because java supports primitive data types such as byte, Boolean, int, long, double.
26. What happens if the main() method is written without String args[]?
Answer: The program will compile but not run. Because, the JVM will always looks for the main
method with a string type array as a parameter.
27. What is JIT compiler?
Answer: JIT (just-in-time) compiler which is used to improve the performance by compiling
bytecodes into native machine code at runtime.
Control flow Statements
1. What is control flow in Java, and why is it important in programming?

Answer: Control flow refers to the order in which statements in a program are executed. It’s essential for
defining the logic and sequence of operations in a program.

2. What are the primary categories of control flow in Java?

Answer: The primary categories of control flow in Java are conditional statements, loops, and method
calls.

3. Explain the ‘if’ statement in Java and its syntax.

Answer: The ‘if’ statement is used for conditional execution. Syntax:


if (condition) {
// Code to execute if condition is true
}
4.explain ‘if-else’ statement in java and its syntax?
Answer: if-else Statement is an extension of the if statement, which uses another block of code i.e., else
block. If the condition inside if statement is true, code executed inside if statement. Otherwise, else block
is executed.
Syntax:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }

5. explain ‘if-else-if’ ladder statement in java and its syntax?


Answer: The if-else-if statement contains the if-statement followed by multiple else-if statements.
Syntax:
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
7. Explain the nested ‘if’ statement in Java and its syntax?

Answer: The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.
Syntax:
1. if(condition){
2. //code to be executed
3. if(condition){
4. //code to be executed
5. }
6. }

8. Explain the ‘switch’ statement in Java and its syntax?


Answer: The Java switch statement executes one statement from multiple conditions. It is like if-else-
if ladder statement. If all cases in switch statement are not matched, then the default case to be executed.
Syntax:
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }

9. What is the purpose of the ‘break’ statement in a ‘switch’ statement?

Answer: The ‘break’ statement is used to exit the ‘switch’ statement after a case is executed.

10. What is the ‘for’ loop in Java, and how is it used?


Answer: The Java for loop is used to iterate a part of the program several times. If the number of iterations
is fixed, then for loop is best to use.
1. for(initialization; condition; increment/decrement){
2. //statement or code to be executed
3. }

11. What is the ‘nested-for’ loop in Java?


Answer: If we have a for loop inside the another for loop, it is known as nested for loop.
12.What is the ‘for-each’ loop in Java?
Answer: The for-each loop is used to traverse array or collection in Java.
Syntax:
1. For (datatype variable : array_name){
2. //code to be executed
3. }

13. What is the infinite for loop in Java?


Answer: If you use only two semicolons ; in the for loop, it will be infinitive for loop.
14. Explain the ‘while’ loop in Java and its syntax?
Answer: The Java while loop is used to iterate a part of the program repeatedly until the specified Boolean
condition is true. The loop is exit if the condition is false.
Syntax:
1. while (condition){
2. //code to be executed
3. Increment / decrement statement
4. }

15. Explain the ‘do-while’ loop in Java and its syntax?

Answer: The Java do-while loop is used to iterate a part of the program repeatedly, until the specified
condition is true. But The Java do-while loop is executed at least once because condition is checked after
loop body.

Syntax:

1. do{
2. //code to be executed / loop body
3. //update statement
4. }while (condition);

16. Explain the ‘break’ statement in Java and its role in control flow?

Answer: The Java break statement is used to break loop or switch statement. It breaks the current flow
of the program at specified condition. In case of inner loop, it breaks only inner loop.

17. What is the ‘continue’ statement in Java, and how does it affect loop execution?

Answer: The ‘continue’ statement is used to skip the current iteration of a loop and proceed to the next
iteration without executing the remaining code in the current iteration.
18. What is a return statement in Java?

Answer: the return statement is used for returning a value when the execution of the block is completed.

19.what is java comments?

Answer: The Java comments are the statements in a program that are not executed by the compiler and
interpreter.

20. Why do we use comments in a code?


Answer: Comments are used to make the program more readable by adding the details of the code. It
makes easy to maintain the code and to find the errors easily.

21. What are the types of comments?

Answer: There are three types of comments in Java.

1. Single Line Comment – these comments are used to comment only one line. Single line comments
starts with two forward slashes (//).
2. Multi Line Comment -are used to comment multiple line of code. Multi-line comments are placed
between /* and */.
3. Documentation Comment – is used to create documentation API. To create documentation API, You
need to use Javadoc tool. The documentation comments are placed between /** and */.
ARRAYS
1. What is an array in Java?
Answer: An array in java is an object which contains elements of similar datatype. The elements of an
array are stored in contiguous memory location. Array is index-based, the first element is stored in 0th
index and second element is stored in 1st index and so on.

2. How do you declare and initialize an array in Java?

Answer:

Declaration: int[] arr; or int arr[];

Initialization: arr = new int[10]; or int[] arr = {1, 2, 3, 4};

3. How do you access elements of an array in Java?


Answer: By using index, arr[0] to access the first element, arr[1] to access the second element and so
on.
4. What is Anonymous Array in java?
Answer: if you are creating an Array without any name is called anonymous array. It is an array just for
creating and using instantly.
5. What are the advantages and disadvantages of an array?
Answer: Advantages: Code Optimization, Random access, easy to use
Disadvantages: Size Limit, Insertion and deletion operations are costly. (O(n) time complexity)
6. What is single dimensional array?
Answer: A single dimensional array in Java is an array that holds a sequence of elements, all of the
same type, accessed through an index.
7. What is two-Dimensional array?
Answer: A Two-Dimensional array is a simplest form of the multi-dimensional array. A two-
Dimensional array is an array of single-Dimensional array.
8. What is multi-dimensional array?
Answer: A multi-dimensional array is an array of arrays. Data in multi-dimensional arrays are stored in
tabular form i.e., rows and columns.
9. What are the differences between 1D array and 2D array?
Answer:
1D Array:
- 1D Array is a sequence of elements all of same type.
- It represents multiple data items in a list form
2D array:
- 2D array is an array of arrays.
- It represents multiple data items in a tabular form.
10. How do you find the length of an array in Java?
Answer: By using length property.
11. How do you iterate over an array in Java?
Answer: using for loop and enhanced for loop.

12. How do you copy an array in Java?

Answer: Using Arrays.copyOf(Object src, int srcPos, Object dest, int destPos, int length)
13. How do you sort an element in java?
Answer: By Using ‘Arrays.sort()’ method.
14. What is an ArrayIndexOutOfBound Exception?
Answer: The virtual machine throws an ArrayIndexOutOfBound Exception if the length of an array in
negative, equal to array size or greater than array size while traversing an array.
15. How do you handle the ArrayIndexOutOfBoundsException in java?
Answer: By using a ‘try-catch’ block
Example:
try {
int element = arr[index];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds: " + e.getMessage());
}
16. What is jagged array in java?
Answer: If we are creating an odd number of columns in a 2D Array, is called as jagged array.
Strings
1. What is String in java?
Answer: In generally String is a sequence of characters. In java, String is an object that represents
the sequence of characters. The java.lang.String class is used to create a string object.
2. How to create a string object?
Answer: There are two ways to create a string object:
- String literals.
- By new keyword.
3. Why java uses the concept of String literals?
Answer: To make java more memory efficient.
4. What is immutable String in java?
Answer: Immutable means unmodifiable or unchangeable. Immutable string means once String
is created, its data or state cannot be changed but a new string object is created.
5. Why string objects are immutable?
Answer: Because of Security, Synchronization, Concurrency, Cache, Class loader.
6. What is String constant pool?
Answer: String constant pool is a special memory area which is used to store string literals.
7. Why String class is final in java?
Answer: because no one can override the methods of the String class.
8. How do you compare java Strings?
Answer: There are three ways to compare Strings in java.
- By using equals() method: compares the original content of the string.
- By == operator: compares the reference of the string not values.
- By using compareTo() method: compares the string lexicographically and returns the integer
value. If s1 == s2 - returns 0, if s1>s2 - returns positive value, if s1<s2 - returns negative
value.
9. What is substring in java?
Answer: substring is a subset of another String.
10. What is StringBuffer class?
Answer: StringBuffer class is a thread-safe (Synchronized) which is used to create mutable strings.
11. What is String Builder class?
Answer: StringBuilder class is not thread-safe(non-Synchronized) which is used to create mutable
Strings in java.
12. What are the differences between String & StringBuffer?
Answer:
- Strings are immutable whereas stringBuffer or StringBuilder is mutable.
- String is slow and consumes more memory when we concatenate too many strings.
Whereas StringBuffer is fast and consumes less memory.
- String uses String constant pool whereas StringBuilder uses heap memory
13. What are the differences between StringBuffer & StringBuilder?
Answer:
StringBuffer:
- StringBuffer is Synchronized i.e., thread safe.
- StringBuffer is less efficient than stingBuilder.
StringBuilder:
- StringBuffer is non-Synchronized i.e., not thread safe.
- StringBuilder is more efficient than stringBuffer.
OOPS Concepts
-Basic Ques:
1.What is Coupling and Types?

Answer: when two classes (or) objects collaborate and work with each other to complete predefined
task. Types – loose coupling and Tight coupling.

2.What is Association?

Answer: Association refers to the relationship between the objects.

3. What are the differences between Object Oriented and Object-based programming language?

Answer: Object Oriented programming language –

1. Object-Oriented programming language supports all the features of Oops including inheritance
and Polymorphism.
2. Oops language don’t have built-in objects.
3. Examples: java, C++, etc.
Object-based programming language –
1. Object based programming language supports the usage of Object and encapsulation.
2. Object based programming language have built-in objects, for example JavaScript has window
object.
3. Examples: JavaScript, VB, etc.

4. What are the advantages and disadvantages of OOPs?

Answer: Advantages:

1. Oops language allows you to break the program into the small problems that can be easily
solved.
2. Code reusability.
3. Easy to maintain.
4. Flexibility and scalability.

Disadvantages:

1. Increased complexity.
2. Overuse of inheritance.
3. Steeper learning curve which means it is difficult to learn for beginners.

5. What is an Object in java?

Answer: An entity that has state and behavior is called as Object. It is a real-world entity. For examples,
car, chair, pen, table, etc...
6. What is class in java?

Answer: A class is template (or) blueprint form which objects are created. And class is group of objects.

7. What is method?

Answer: A method is a block of code or collection of statements are grouped together to perform a
certain task or operation.

8. What is abstract method?

Answer: A method does not have method body is called as abstract method. It is always declared inside
the abstract class only. If you declare a method as abstract, we can use abstract keyword.

9. What is constructor in java?

Answer: A constructor is a special type of method which is used to initialize the objects.

10. What is constructor overloading?

Answer: A class having more than one constructor with different parameter list, it is known as
constructor overloading.

11. What are the differences between constructor and method?

Answer: constructor:

- A constructor is used to initialize the objects.


- Doesn’t have any return type.
- A constructor name must be same as class name.
- Java compiler provides default constructor, when there is no constructor is available in a class.

Method:

- A method is used to expose the behavior of the object.


- A method must have return type.
- A method name may or may not be same as class name.
- A method doesn’t have any default method.

12. Why is java main () method being static?

Answer: java main () method is static. Because of the Object is not required to call a static method.

13. Can we execute a program without main method?

Answer: no, we cannot execute a program without main () method. Because when we run a program,
the JVM looks for the main method. If JVM could not find main method, it will show you run-time error
exception.

14.What is this keyword in java?

Answer: this keyword in java is a reference variable that refers to the current object.

15. What are the differences between Object and Class?


Answer: Object:

- Object is an instance of class.


- Object is a real-world entity.
- Object is created by using new keyword.
- Ex, pen, table, car, etc.

Class:

- Class is a group of similar objects.


- Class is a logical entity.
- Class is created by using class keyword.

-Inheritance:
1. what is inheritance?

Answer: Inheritance in java is a mechanism in which one object acquires all the properties and behavior
of a parent object. Also known as parent-child relationship.

2. Why use inheritance in java?

Answer: for method overloading, for code reusability.

3.what is subclass/child class?

Answer: The newly formed class which will created by taking the properties of an existing class/parent
class, it is known as sub class/child class. Also called as derived class.

4.what is superclass/base class?

Answer: A Super class is the class from where a subclass is inherits the features. Also called as base class.

5.what are the types of inheritance?

Answer: There are mainly three types of inheritance which are supported by java – 1) single inheritance,
2) multi-level inheritance, 3) hierarchical inheritance.

6.What is single inheritance in java?

Answer: when one class is derived from a single parent class is called as single inheritance.

7. What is multi-level inheritance?

Answer: When there is a chain of inheritance i.e., one class is derived from another class which is again
derived from another parent class, such type of inheritance is called multi-level inheritance.
8. What is hierarchical inheritance?

Answer: When one or more classes is derived from the single parent class. Such type of inheritance is
called as hierarchical inheritance.

9. what is Multiple inheritance?

Answer: When one class is derived from the two or more parent classes. Such type of inheritance is
called as multiple inheritance. Multiple inheritance is not supported by java.

10. Why multiple inheritance is not supported by java?

Answer: Because of ambiguity.

-Polymorphism:
11. What is method overloading?

Answer: if a class having multiple methods with same name and different parameters. It is known as
method overloading.

12. Why method overloading is not Possible by changing the return type of method only?

Answer: Because of ambiguity.

13. can we overload java main () method?

Answer: Yes, we can overload main method in java by method overloading. You can have any no. of main
methods in java program. But JVM calls main method which receives string array as arguments.

14. What is method overriding?

Answer: If a subclass has same method as declared in the parent class, it is known as method overriding.
Method overriding is used for run-time polymorphism.

15. Can we override Static method?

Answer: No, a static method cannot be overridden. It can be provided by the run-time polymorphism.

16. What are the differences between method overloading and method overriding?

Answer:

- method overloading is used to increase the readability of the program, while method overriding
is used to provide the specific implementation of the method.
- Method overloading performs within the class only, while method overriding occurs two classes.
- In case of method overloading, return type must be different. Whereas method overriding,
return type is same.
- Method overloading is the example of compile-time polymorphism, while method overriding is
the example of run-time polymorphism.

17. What is super keyword?

Answer: Super keyword is a reference variable which is used to refer the immediate parent class object.

18. What is final keyword and its usage?

Answer: Final keyword in java is a non-access modifier which is used to restrict the user. If you declare
any variable as final, you cannot change the value of final variable.

Usage: Stops value change, stop method overriding, Stop inheritance.

19. Is final method is inherited?

Answer: Yes, final method is inherited but you cannot override it.

20. Can we declare a constructor as final?

Answer: No, because constructed never be inherited.

21. What is polymorphism?

Answer: Polymorphism in java is a concept by which we can perform single action in different ways.

There are two types of polymorphism in java: runtime polymorphism, and compile-time polymorphism.

22. What is Run-time Polymorphism?

Answer: Run-time polymorphism is also known as dynamic method dispatch, is a process in which a
method call to an overridden method is resolved at run-time rather than compile-time.

23. What is Static binding and Dynamic binding?

Answer: Static binding: When type of the object is determined at compiled time (by the compiler), it is
known as static binding.

Dynamic binding: When type of the object is determined at run-time, it is known as dynamic binding.

24. What is Upcasting and down casting?

Answer: If a reference variable of the parent class is refers to the object of the child class, is called as
upcasting.

If a reference variable of the child class refers to the parent class object, is called as downcasting.

-Abstraction:
25. What is Abstraction?

Answer: Abstraction in java is a process of hiding all implementation details and showing only
functionality to the user.
For example, sending SMS, you type text and send it, you don’t know the internal process about the
message delivery.

26. What is abstract keyword, abstract class & abstract method?

Answer: abstract keyword is a non-access modifier which is used for classes and methods to achieve
abstraction.

A class which is declared with abstract keyword is known as abstract class. It can have abstract and non-
abstract methods.

A method which is declared as abstract and does not have implementation is known as an abstract
method.

27. What is interfaces in java?

Answer: Interface in java is a blue print of a class which is used to achieve abstraction and multiple
inheritance.

28. What are differences between the abstract class and Interface?

Answer:

- An abstract class can have abstract and non-abstract methods, while interface can have abstract
methods only.
- An abstract class can have static, non-static, final, non-final variables, while interfaces can have
final and abstract variables only.
- An abstract class does not supports multiple inheritance, while interfaces supports multiple
inheritance.

29. Multiple inheritance is not supported through class in java, but it is possible by an interface, why?

Answer: multiple inheritance is not supported in the case of class because of ambiguity. However, it is
supported in case of an interface because there is no ambiguity. It is because its implementation is
provided by the implementation class.

30. What is marker or tagged interface?

Answer: An interface which has no member is known as a marker or tagged interface, for
example, Serializable, Cloneable, Remote, etc.

31. What is nested interfaces?

Answer: An interface is declared within another interface is called nested interface.


-Encapsulation:
32. What is package?

Answer: A package is a folder which is collection of classes, methods, interfaces, abstract classes. There
are two types of packages – user-defined package and pre-defined or built-in package (the package
which is previously defined in java package API. For ex, java, awt, javax, swing etc.).

33. What is access modifier? And its types?

Answer: Access modifier in java specifies the accessibility or scope of a field, method, constructor or
class. There are 4 types of access modifiers in java.

- Private: can accessible only within the class. It cannot be accessed outside the class.
- Default: can accessible only within the package. Cannot be accessible outside the package.
- Protected: can accessible within the package and outside the package through the child class.
- Public: can be accessible everywhere i.e., inside and outside the package and inside and outside
the class.

34. What is encapsulation?

Answer: Encapsulation in java is a process of wrapper code and data together into a single unit. For
example, a capsule is mixed with several medicines.

35: What are the Advantages of encapsulation?

Answer:

- provides control over the data.


- Hide all implementation details.
- You can make a class read-only or write-only by providing setter and getter methods.

36. What is object cloning?

Answer: Object cloning in java is a way to create an exact copy of an object.

37. What is Java wrapper class?

Answer: The wrapper class in java is used to convert primitive data types into objects and vice versa.

38. What is compile-time polymorphism?

Answer: The compile-time polymorphism is a polymorphism that is resolved during the compilation
process.

39. what is subpackage in java?

Answer: A package inside another package is called subpackage.

40. What is java commend-line arguments?

Answer: The java command-line argument is an argument i.e. passed at the time of running the java
program.
41. What is blank or uninitialized final variable?

Answer: A final variable that is not initialized at the time of declaration is known as blank final variable.

42. What is recursion in java?

Answer: Recursion in java is a process in which a method calls itself continuously. It makes the code
compact but complex to understand.

43. Define Destructor?

Answer: A destructor is a special method which is automatically called when the object is made of scope
or destroyed.

45. What is ternary operator?

Answer: ternary operator is the only conditional statement that takes three arguments. Arguments and
results are of different data types, and it depends on the function.
Java Collection Framework
1. What is the Java Collections Framework, and why is it essential in Java programming?

Answer: The java collection framework provides a set of classes and interfaces for working with collection
of objects. It provides fundamental data structures and algorithms for organizing and manipulating data.

2. Name some core interfaces in the Java Collections Framework.

Answer: List, Queue, Map, Set and their respective Sub interfaces.

3. What is Iterable Interface?

Answer: Iterable interface is the root interface for all collection classes.

4. What is java ArrayList?

Answer: The java ArrayList class uses a Dynamic Array for storing elements. It is like an array, but there is
no size limit. We can add or remove elements at any time. ArrayList maintains insertion order internally
and can have duplicate elements also. ArrayList is a non-Synchronized.

5. Explain the difference between a List and a Set in the Collections Framework.

Answer: A List can have duplicate elements and maintains insertion order. A set does not allow duplicate
elements and it may or may not maintain insertion order.

6. What is the purpose of the ‘Collection’ interface, and what methods does it define?

Answer: The collection interface is the root interface in the collection frameworks. It defines methods for
basic collection operations like adding, removing, and iterating over elements.

7. Name a class that implements the ‘Set’ interface in the Collections Framework.

Answer: HashSet, TreeSet, and LinkedHashSet are classes that implement the Set interface.

Syntax for creating a HashSet:

Set<Type> set = new HashSet<> ();


8. Explain the ‘Map’ interface and its key-value association.

Answer: The Map interface defines a collection that holds key-value pairs. Each key value pair is known
as entry. Each key is associated with a value. A map doesn’t allow duplicate keys, but you can have
duplicate elements.

9. What is the difference between ‘HashMap’ and ‘Hashtable’ in the Collections Framework?
Answer: HashMap is not synchronized and allows duplicate keys and values whereas Hashtable is
synchronized and does not allow duplicate keys or values.
10. Explain the ‘List’ interface and name a few classes that implement it.
Answer: The List interface extends collection interface that represents ordered collection of elements. It
allows duplicate elements and maintains insertion order. Classes that implement ArrayList, LinkedList and
Vector
11. What is the ‘Queue’ interface in the Collections Framework, and how is it different from a List?
Answer: The queue interface extends collection interface that represents a collection that ordered
elements for processing. Typically using ‘First-in first-out’ order.
12. What is the ‘Deque’ interface, and how does it differ from a Queue?
Answer: The deque is the double ended queue extends queue interface and allows elements to be added
or removed from both ends.
13. Explain the ‘Iterator’ interface and its role in traversing collections.
Answer: The iterator interface is used to iterating collection, providing methods like next() and Hashnext()
to access the elements sequentially.
Syntax:
Iterator<type> iterator = collections.iterator();
While (iterator.Hashnext()) {
Type element = iterator.next();
}
14. What is an “unmodifiable” or “immutable” collection, and why is it useful?
Answer: The immutable collection means it cannot be changed after creation and it useful for read-only
views of collections, ensuring data integrity.
Syntax:
List<type> unmodifablelist = Collections.unmodifiableList(list);
15. Explain the ‘Comparable’ interface and its role in sorting elements.
Answer: The comparable interface is used to order the objects of the user-defined class. This interface is
found in java.lang package and contains only one method named compareTo() method. It provides single
sorting sequence i.e., you can sort the elements on the basis of single data member only.
16. What is the purpose of the ‘Comparator’ interface in the Collections Framework?
Answer: The comparator interface is used to order the objects of the user-defined class. This interface is
found in java.util package and provides 2 methods i.e., compare(object obj1, object obj2) and
equals(object element). It provides multiple sorting sequence i.e., you can sort the elements on the basis
of multiple data member.
17. What is the ‘Collections’ class in Java, and what utility methods does it offer for collections?
Answer: The collection class is the utility class that provides various methods for working with collection,
such as sorting, searching, synchronization.
18. Explain the ‘hashCode’ and ‘equals’ methods in the context of using objects as keys in a Map.
Answer: The Hashcode method provides hash code for an object while equals method is used to compare
the objects for equality.
19. What is the ‘HashSet’ class in the Collections Framework, and how does it store elements?
Answer: The hashSet is the implementation of the set interface that uses hash table for storing elements.
It does not allow duplicate elements and does not maintain insertion order, allows null values. HashSet is
non synchronized.
20. Explain the ‘TreeSet’ class in the Collections Framework and its characteristics.
Answer: TreeSet is the implementation of the set interface that stores the elements in the sorted order
i.e., ascending order by default. It can contain unique values and doesn’t allow null values. TreeSet class is
non-synchronized.
21. What is the ‘LinkedList’ class in the Collections Framework, and how does it differ from an ArrayList?
Answer: LinkedList is the doubly LinkedList implementation that can be used to store the elements. It
implements the list and deque interface. It maintains insertion order and allows duplicate elements.
22. What are the differences between single and doubly linked list?
Answer: Singly linked list consists of 2 fields – data field, link to the next node. DLL consists of three fields
– previous node link, data field, next node link.
SLL uses less memory and DLL uses more memory.
23. Explain the ‘HashMap’ class in the Collections Framework, and how does it store key-value pairs?
Answer: HashMap is the implementation of the map interface that uses hash table for storing key-value
pairs. It can have unique elements. It may have one null key and multiple null values. HashMap is non-
synchronized.
24. What is the ‘Hashtable’ class, and what are its main characteristics?
Answer: Hashtable is the synchronized implementation of the map interface. It ensures thread-safety but
slower than HashMap.
25. What is the ‘Vector’ class, and how does it differ from an ArrayList?
Answer: vector is the synchronized version of the ArrayList. It ensures thread-safety but slower due to
synchronization.
26. Explain the ‘PriorityQueue’ class in the Collections Framework, and what ordering does it use?
Answer: PriorityQueue is the implementation of the Queue interface that orders elements based on
priority. The high priority element appears at front and low priority element appears at last.
27. What is the ‘ConcurrentHashMap’ class, and why is it useful for multithreaded applications?
Answer: ConcurrentHashMap is the concurrent implementation of the Map interface that allows multiple
threads to access and modify it concurrently, with high-performance and safety.
28. Explain the ‘Arrays’ class in Java and its utility methods for working with arrays.
Answer: Arrays class provides various static methods for working with arrays, including sorting, searching
and converting arrays to collections.
29. What is the purpose of the ‘CopyOnWriteArrayList’ class, and how does it work in multithreaded
environments?
Answer: CopyOnWriteArrayList is the list implementation that ensures thread-safety by providing a new
copy of a list whenever an element is modified. It is useful when reads are much more frequent than
writes.
30. Explain the ‘WeakHashMap’ class, and how does it handle weak references to keys?
Answer: WeakHashMap is the implementation of map interface which uses weak references for keys. Keys
can be collected by garbage collector if there are no strong keys are held.
31. What is the ‘EnumSet’ class in the Collections Framework, and how is it used with enums?
Answer: EnumSet is specialized set implementation for use with Enum types. It is highly efficient and takes
advantages of Enum characteristics.
32. Explain the ‘NavigableSet’ interface in the Java Collections Framework and its key features.
Answer: The NavigableSet interface extends the set interface that provides navigation methods for
traversing elements in a sorted order. It offers methods for floor, ceiling, lower and higher elements.
33. What is the ‘LinkedBlockingQueue’ class, and how does it differ from other blocking queue
implementations?
Answer: LinkedBlockingQueue is the implementation of the blocking queue interface that uses linked
node structure. It is unbounded, which means it can hold unlimited number of elements.
34. What is the ‘ConcurrentLinkedQueue’ class, and how does it handle concurrent access in a queue?
Answer: ConcurrentLinkedQueue is the concurrent implementation of the Queue interface that provides
high performance, non-blocking, and thread-safe for managing the elements in a queue
35. What is the ‘ConcurrentSkipListSet’ class, and how does it provide concurrent access to a sorted set?
Answer: ConcurrentSkipListSet is the concurrent implementation of the navigableset interface that allows
multiple threads to access and modify it concurrently while maintaining the sorted order.
36. What is the ‘EnumMap’ class, and how is it used to associate keys with enums in a Map?
Answer: EnumMap class is the specialized implementation of the Map interface. It is highly efficient and
each key is associated with specific enums.
37. Explain the ‘BlockingQueue’ interface in the context of concurrent programming.
Answer: BlockingQueue interface represents the thread safe Queue that provides blocking operations for
managing concurrent access to elements.
Answer:
38. What is the ‘ArrayDeque’ class, and how does it implement a double-ended queue (deque)?
Answer: ArrayDeque is the resizable array-based implementation of the deque interface. We can add or
remove elements from both ends and it can contain null values. ArrayDeque is faster than LinkedList and
Stack.
39. Explain the ‘LinkedHashSet’ class and its characteristics in maintaining a predictable order?
Answer: LinkedHashSet is the implementation of the set interface which maintains insertion order and it
allows null values. It combines the features from both HashMap and LinkedList.
40. What is the ‘IdentityHashMap’ class?
Answer: IdentityHashMap is the specialized map implementation that uses reference equality for keys.
41. What is the ‘TreeMap’ class in the Java Collections Framework, and how does it provide sorted key-
value mappings?
Answer: TreeMap is an implementation of the map interface that stores key-value pairs in sorted order
based on the keys. It uses red-black tree for efficient maintenance. It contains only unique elements.
42. What is the ‘Properties’ class?
Answer: The properties class is a subclass of Hashtable. It can be used to maintain list of values in which
the key is a string and the value is also a string. The properties class provides methods to get data from
properties file and store the data into properties file.
43. What differences exist between Iterator and ListIterator?
Answer:
- An Iterator can be used to traverse the set and list collections, while the ListIterator can be used
to iterate over only lists.
- An iterator can traverse the collection only in forward direction, while the ListIterator can traverse
the list in both directions.
44. What differences exist between HashMap and Hashtable?
Answer:
- HashMap is non-Synchronized, while HashTable is synchronized.
- HashMap allows one null key and multiple null values, while Hashtable doesn’t allow null values
and keys.
45. What is difference between Array and ArrayList? When will you use Array over ArrayList?
Answer:
- An Array can contain primitive Or Objects, while ArrayList can contain Objects only.
- An Array can have fixed/static size, while ArrayList is Dynamic in size.
- An Array is multi-dimensional, while ArrayList is single-dimensional.
- We can use for and for-each loop to iterate over the Array, while iterator can be used to iterate
over the ArrayLists.
46. What is difference between ArrayList and LinkedList?
Answer:
- ArrayList internally uses Dynamic Array to store elements, while LinkedList internally uses Doubly
LinkedList to store elements.
- Manipulation with ArrayList is slow because it internally uses an array, manipulation with
LinkedList is faster than ArrayList.
- ArrayList is better for storing and accessing data, while LinkedList is better for manipulating data.
47. What are the differences between Comparable and Comparator interface?
Answer:
- Comparable interface provides the single sorting sequence i.e., you can sort the elements on the
basis of single data member only such as id, name. while Comparator interface provides the
multiple sorting sequence i.e., you can sort the elements on the basis of multiple data members.
- Comparable interface provides compareTo() method to sort the elements, while Comparator
interface provides compare() method to sort the elements
- Comparable is present in java.lang package, while Comparator is present in java.util package.
48. What is the difference between HashSet and TreeSet?
Answer:
- Elements in HashSet is not ordered, while TreeSet is sorted order.
- HashSet allows null objects, while TreeSet doesn’t allow null objects.
- HashSet internally uses HashMap to store elements, while TreeSet internally uses TreeMap.
- HashSet uses equals() and Hashcode() methods for comparison, while TreeSet provides Compare()
and compareTo() methods.
49. What is difference between ArrayList and Vector?
Answer:
- ArrayList is non-Synchronized, while Vector is synchronized.
- ArrayList is faster, While Vector is slower.
- ArrayList allows multiple threads, while Vector allow single thread only.
50. What is Stack?
Answer: Stack is a linear DS that can be used to store the collection of objects. It is based on Last-in-first-
out (LIFO). It can have two important operations such as push and pop. The push operation inserts an
element into the stack and pop operation removes an element from the top of the stack.
Thread and Concurrency
1. What is Multithreading in java?
Answer: Multithreading is a process of executing multiple threads simultaneously. It is used to
obtain the multitasking. It consumes less memory and gives the fast and efficient performance.
2. What is thread?
Answer: A Thread in java is a lightweight, executable unit of the program. Threads can be created
by extending thread class and implementing the runnable interface.
3. Differentiate between thread and process?
Answer:
- A process is an execution of the program, while a thread is a subset of the process.
- Process have different address space in memory, while thread have shared address space.
- Inter-process communication is slower and expensive than inter-thread communication.
4. What are the advantages of multithreading?
Answer:
- Threads are independent.
- The cost of Communication between the processors is low.
- You can perform many operations together. So, it saves time.
5. How you can create a Thread in java?
Answer: 1. By extending thread class.
2. By implementing runnable interface.
3. By using executors from the java.util.concurrent package.
The Runnable interface is preferred, as it does not require an object to inherit the thread class.
6. What is thread class in java?
Answer: A Thread class is a fundamental class in java is for creating and managing threads. This
class provides methods for creation, start and control.
7. What is start method in java?
Answer: A start method in java is used to start the newly formed threads.
8. What is the ‘Runnable’ interface, and how does it relate to multithreading in Java?
Answer: The runnable interface is an interface used to execute code on concurrent threads. It
defines a single method run(). It is used to represent a task that can be executed on concurrently
within a thread.
9. Explain the lifecycle of a thread in java?
Answer: A thread life cycle consists of the states:
- New: in this state, a thread class object is created using new operator, but it is not alive.
- Runnable: in this state, a thread is ready to run after calling a start() method.
- Running: in this state, a thread schedular picks a thread from the ready state and the thread
is running.
- Blocked/waiting: in this state, the thread is not running, but still alive and waiting for another
thread to finish.
- Dead/terminated: a thread is in terminated or dead state when a run() method exits.
10. What is the ‘start’ method in the ‘Thread’ class, and why is it used to begin thread execution?
Answer: The start() method in a thread class helps us to start the thread’s execution. It schedules
the thread to run its run() method concurrently.
11. What is thread priority, and how is it set in Java?
Answer: A thread priority is value indicating relative importance of the thread. It can be set by
using setPriority() method with values ranging from 1 to 10.
12. Explain the concept of thread synchronization?
Answer: One thread is executed at a time and the remaining threads are in waiting state. This
process is known as thread synchronization. It is essential for thread interference and
inconsistency problems.
13. What are the differences between ‘synchronized’ methods and ‘synchronized’ blocks in Java?
Answer:
14. What is a race condition, and how does it occur in multithreaded programs?
Answer:
15. Explain the ‘wait’ and ‘notify’ methods in Java and their role in thread communication.
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:

You might also like