Java Basics | OOPS | Inheritance | Static | Method Overloading and Overriding | Polymorphism | Abstraction | Final | Package | Internationalization | Serialization | Reflection | Garbage Collection | Inner Classes | String | Exception Handling | Java Collection | Multi-threading | Java 8 | Java 8 Stream Questions | Java Tricky Questions | Mixed Questions | JSP | Java Design Patterns | Spring | Hibernate | Maven | GIT | AWS | Cloud Computing | DOCKER | UNIX Shell | Microservices |

Java Basics

1. What is the difference between JDK and JRE?

JDK stands for Java Development Kit. It contains the tools and libraries for development of Java programs. JDK also contains compilers and debuggers required to compile a Java program,

JRE stands for Java Runtime Environment. This is included in JDK. JRE provides libraries and JVM that is required to run a Java program.

JDK is also considered as a super set of JRE.JDK contains everything that is in JRE and it also contains the tools, utilities and directories required to compile, debug and run Java code.

2. What is Java Virtual Machine (JVM)?

Java Virtual Machine (JVM) is an abstract machine that executes Java Bytecode. There are different JVM for different hardware and software platforms. Therefore, JVM is platform dependent. JVM is responsible for loading, verifying and executing the Bytecode on a specific platform. JVM is included in a JRE package.

One of the most popular JVMs is by Oracle. It is called HotSpot.

3. What are the different types of memory areas allocated by JVM?

In Java, JVM allocates memory to different processes, methods and objects. Some of the memory areas allocated by JVM are:

  • ClassLoader: It is a component of JVM used to load class files.
  • Class (Method) Area: It stores per-class structures such as the runtime constant pool, field and method data, and the code for methods.
  • Heap: Heap is created a runtime and it contains the runtime data area in which objects are allocated.
  • Stack: Stack stores local variables and partial results at runtime. It also helps in method invocation and return value. Each thread creates a private JVM stack at the time of thread creation.
  • Program Counter Register: This memory area contains the address of the Java virtual machine instruction that is currently being executed.
  • Native Method Stack: This area is reserved for all the native methods used in the application.

4. What is JIT compiler?

Just In Time compiler also known as JIT compiler is used for performance improvement in Java. It is enabled by default.It is compilation done at execution time rather earlier.

Java has popularized the use of JIT compiler by including it in JVM.

5. How Java platform is different from other platforms?

Java is a platform independent language. Java compiler converts Java code in to byte code that can be interpreted by JVM. There are JVM written for almost all the popular platforms in the world.

Java byte code can run on any supported platform in same way. Where as other languages require libraries compiled for a specific platform to run.

6. Why people say that Java is ‘write once and run anywhere’ language?

You can write Java code on Windows and compile it in Windows platform. The class and jar files that you get from Windows platform can run as it is on Unix environment. So it is a truly platform independent language.

Behind all this portability is Java byte code. Byte code generated by Java compiler can be interpreted by any JVM. So it becomes much easier to write programs in Java and expect those to run on any platform.

Java compiler javac compiles java code and JVM java runs that code.

7. How does ClassLoader work in Java?

In Java, ClassLoader is a class that is used to load files in JVM. ClassLoader loads files from their physical file locations e.g. Filesystem, Network location etc.

There are three main types of ClassLoaders in Java.

  • Bootstrap ClassLoader: This is the first ClassLoader. It loads classes from rt.jar file.
  • Extension ClassLoader: It loads class files from jre/lib/ext location.
  • Application ClassLoader: This ClassLoader depends on CLASSPATH to find the location of class files. If you specify your jars in CLASSPATH, then this ClassLoader will load them.

8. Do you think ‘main’ used for main method is a keyword in Java?

No, main is just a name of method. There can be multiple methods with same name main in a class file. It is not a keyword in Java.

9. Can we write main method as public void static instead of public static void?

No, you cannot write it like this.  Any method has to first specify the modifiers and then the return value. The order of modifiers can change.

We can write static public void main() instead of public static void main().

10. In Java, if we do not specify any value for local variables, then what will be the default value of the local variables?

Java does not initialize local variables with any default value. So these variables will be just null by default.

11. Let say, we run a java class without passing any arguments. What will be the value of String array of arguments in Main method?

By default, the value of String array of arguments is empty in Java. It is not null.

12. What is the difference between byte and char data types in Java?

Both byte and char are numeric data types in Java. They are used to represent numbers in a specific range.

Major difference between them is that a byte can store raw binary data where as a char stores characters or text data.

Usage of char is E.g. char ch = ‘x’;

Byte values range from -128 to 127.

A byte is made of 8 bits. But a char is made of 16 bits. So it is equivalent to 2 bytes.

OOPS

13. What are the main principles of Object Oriented Programming?

Main principles of Object Oriented Programming (OOPS) are:

  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism

14. What is the difference between Object Oriented Programming language and Object Based Programming language?

Object Oriented Programming languages like Java and C++ follow concepts of OOPS like- Encapsulation, Abstraction, Polymorphism and Inheritance etc.

Object Based Programming languages follow some features of OOPS but they do not provide support for Polymorphism and Inheritance. Egg. JavaScript, VBScript etc.

Object Based Programming languages provide support for Objects and you can build objects from constructor. They languages also support Encapsulation. These are also known as Prototype-oriented languages.

15. In Java what is the default value of an object reference defined as an instance variable in an Object?

All the instance variable object references in Java are null.

16. Why do we need constructor in Java?

Java is an object-oriented language, in which we create and use objects.

A constructor is a piece of code similar to a method. It is used to create an object and set the initial state of the object. A constructor is a special function that has same name as class name.

Without a constructor, there is no other way to create an object.

By default, Java provides a default constructor for every object. If we overload a constructor then we have to implement default constructor.

17. Why do we need default constructor in Java classes?

Default constructor is the no-argument constructor that is automatically generated by Java if no other constructor is defined.

Java specification says that it will provide a default constructor if there is no overloaded constructor in a class. But it does not say anything about the scenario in which we write an overloaded constructor in a class.

We need at least one constructor to create an object, that’s why Java provides a default constructor.

When we have overloaded constructor, then Java assumes that we want some custom treatment in our code. Due to which it does not provide default constructor. But it needs default constructor as per the specification. So it gives error.

18. What is the value returned by Constructor in Java?

When we call a constructor in Java, it returns the object created by it. That is how we create new objects in Java.

19. Can we inherit a Constructor?

No, Java does not support inheritance of constructor.

20. Why constructors cannot be final, static, or abstract in Java?

If we set a method as final it means we do not want any class to override it. But the constructor (as per Java Language Specification) cannot be overridden. So there is no use of marking it final.

If we set a method as abstract it means that it has no body and it should be implemented in a child class. But the constructor is called implicitly when the new keyword is used. Therefore it needs a body.

If we set a method as static it means that it belongs to the class, but not a particular object. The constructor is always called to initialize an object. Therefore, there is no use of marking constructor static.

Inheritance

21. What is the purpose of ‘this’ keyword in java?

In Java, ‘this’ keyword refers to current instance of the object.

It is useful for differentiating between instance variables and local variables.

It can be used to call constructors. Or it can be used to refer to the instance.

In case of method overriding, this is used for falling the method of current class.

22. Explain the concept of Inheritance?

Inheritance is an important concept in Object Oriented Programming. Some objects share certain characteristics and behavior. By using Inheritance, we can put the common behavior and characteristics in a base class which also known as super class. And then all the objects with common behavior inherit from this base class.

It is also represented by IS-A relationship.

Inheritance promotes, code reuse, method overriding and poly-morphism.

23. Which class in Java is superclass of every other class?

Java is an object oriented programming language. In Java, Object class is the superclass of every other class.

24. Why Java does not support multiple inheritance?

Multiple Inheritance means that a class can inherit behavior from two or more parent classes.

The issue with Multiple Inheritance is that both the parent classes may have different implementation for the same method. So they have different ways of doing the same thing. Now which implementation should the child class choose?

This leads to ambiguity in Multiple Inheritance. This is the main reason for Java not supporting Multiple Inheritance in implementation.

Lets say you have a class TV and another class AtomBomb. Both have method switchOn() but only TV has switchOff() method. If your class inherits from both these classes then you have an issue that you can switchOn() both parents, but switchOff will only switchOff() TV.

But you can implement multiple interfaces in Java.

25. In OOPS, what is meant by composition?

Composition is also known as “has-a” relationship. In composition, “has-a” relation relates two classes. E.g. Class Car has a steering wheel.

If a class holds the instance of another class, then it is called composition.

26. How aggregation and composition are different concepts?

In OOPS, Aggregation and Composition are the types of association relations. A composition is a strong relationship. If the composite object is destroyed, then all its parts are destroyed. E.g. A Car has a Steering Wheel. If Car object is destroyed, then there is no meaning of Steering Wheel.

In Aggregation, the relationship is weaker than Composition.

E.g. A Library has students. If a Library is destroyed, Students still exist. So Library and Student are related by Aggregation. A Library has Books. If Library is destroyed, the Books are also destroyed. Books of a Library cannot exist without the Library. So Book and Library are related by Composition.

27. Why there are no pointers in Java?

In Java there are references instead of pointers. These references point to objects in memory. But there is no direct access to these memory locations. JVM is free to move the objects within VM memory.

The absence of pointers helps Java in managing memory and garbage collection effectively. Also it provides developers with convenience of not getting worried about memory allocation and de-allocation.

28. If there are no pointers in Java, then why do we get NullPointerException?

In Java, the pointer equivalent is Object reference. When we use a . it points to object reference.  So JVM uses pointers but programmers only see object references.

In case an object reference points to null object, and we try to access a method or member variable on it, then we get NullPointerException.

29. What is the purpose of ‘super’ keyword in java?

‘super’ keyword is used in the methods or constructor of a child class. It refers to immediate parent class of an object.

By using ‘super’ we can call a method of parent class from the method of a child class.

We can also call the constructor of a parent class from the constructor of a child class by using ‘super’ keyword.

30. Is it possible to use this() and super() both in same constructor?

No, Java does not allow using both super() and this() in same constructor. As per Java specification, super() or this() must be the first statement in a constructor.

31. What is the meaning of object cloning in Java?

Object.clone() method is used for creating an exact copy of the object in Java. It acts like a copy constructor. It creates and returns a copy of the object, with the same class and with all the fields having same values as of the original object.

One disadvantage of cloning is that the return type is an Object. It has to be explicitly cast to actual type.

Static

32. In Java, why do we use static variable? Whenever we want to have a common property for all objects of a class, we use a class level variable i.e. a static variable.

This variable is loaded in memory only once at the time of class loading. So it saves memory, since it is not defined per object in Java.

33. Why it is not a good practice to create static variables in Java?

Static variables are common to all the objects of a class. If a new object is created, there is no need to test the value of static variable. Any code that uses static variable can be in any state. It can be within a new object or at a class level. So the scope of static variable is open ended in a Java class.

If we want tighter control on scope, then variables should be created at the object creation level.

Also defining static variables is not a good practice because they go against the principles of Object Oriented Programming.

34. What is the purpose of static method in Java?

Java provides the feature of static method to create behavior at the class level. The static method is common to all the objects of a class.  We do not need to create any object of a class to call a static method. So it provides convenience of not creating an object for calling it.

Also a static method can access and modify static data members. This also helps in keeping the behavior as well as state at the class level.

35. Why do we mark main method as static in Java?

The main method in Java is marked as static, so that JVM can call it to start the program. If main method is not static, then which constructor will be called by Java process?

As such it is a known as convention to mark main method static in Java. But if we remove the static, then there will be ambiguity. Java process may not know which method of a class to call to start the program.

So this convention helps in Java process to identify the starting code for a program in class that is passed as an argument to java process.

36. In what scenario do we use a static block?

At times, there is a class that has static member variables. These variables need some complicated initialization. At this time static block helps as a tool to initialize complex static member variable initialization.

The static block is executed even before the execution of main.

Sometimes, we can also replace static block with a static method of class.

37. Is it possible to execute a program without defining a main() method?

No, with Java 7 onwards, you need a main() method to execute a program. In earlier versions of Java, there was a workaround available to use static blocks for execution. But now this gap has been closed.

38. What happens when static modifier is not mentioned in the signature of main method?

As per Java specification, main method has to be marked as static. It needs only one argument that is an array of String.

A program can compile with a non-static method. But on execution it will give NoSuchMethodError.

39. What is the difference between static method and instance method in Java?

Often, there is a need to define a behavior for a class that is not dependent on member variables of an object. Such behavior is captured in a static method. If there is a behavior dependent upon the member variables of an object, then we do not mark it static, it remains as instance method.

To call as static method, we do not need to create an object. We just call it with class name. But to call an instance method, we need to create/get an object first.

Instance member variables cannot be accessed by a static method. But an instance method can call both instance variables and static variables.

Method Overloading and Overriding

40. What is the other name of Method Overloading?

Method Overloading is also known as Static Polymorphism.

41. How will you implement method overloading in Java?

In Java, a class can have multiple methods with same name but different arguments.  It is called Method Overloading. To implement method overloading we have to create two methods with same name in a class and do one/more of the following:

  • Different number of parameters
  • Different data type of parameters
  • Different sequence of data type of parameters

42. What kinds of argument variations are allowed in Method Overloading?

Method Overloading allows two methods with same name to differ in:

  • Number of parameters
  • Data type of parameters
  • Sequence of data type of parameters

43. Why it is not possible to do method overloading by changing return type of method in java?

If we change the return type of overloaded methods then it will lead to ambiguous behavior. How will clients know which method will return what type. Due to this different return type are not allowed in overloaded methods.

44. Is it allowed to overload main() method in Java?

Yes, Java allows users to create many methods with same name ‘main’. But only public static void main(String[] args) method is used for execution.

45. How do we implement method overriding in Java?

To override a method, we just provide a new implementation of a method with same name in subclass. So there will be at least two implementations of the method with same name. One implementation is in parent class. And another implementation is in child class.

46. Are we allowed to override a static method in Java?

No. Java does not allow overriding a static method. If you create a static method with same name in subclass, then it is a new method, not an overridden method.

47. Why Java does not allow overriding a static method?

To override a method, you need an instance of a class. Static method is not associated with any instance of the class. So the concept of overriding does not apply here.

Therefore, Java does not allow overriding a static method.

48. Is it allowed to override an overloaded method?

Yes. You can override an overloaded method in Java.

49. What is the difference between method overloading and method overriding in Java?

Differences between method overloading and overriding are:

  • Method overloading is static polymorphism.
  • Method overriding is runtime polymorphism.
  • Method overloading occurs within the same class.
  • Method overriding happens in two classes with hierarchy relationship.
  • Parameters must be different in method overloading. Parameters must be same in method overriding.
  • Method overloading is a compile time concept. Method overriding is a runtime concept.

50. Does Java allow virtual functions?

Yes. All instance methods in Java are virtual functions by default. Only class methods and private instance methods are not virtual methods in Java.

51. What is meant by covariant return type in Java?

A covariant return type of a method is one that can be replaced by a “narrower” type when the method is overridden in a subclass.

Let say class B is child of class A. There is a get() method in class A as well as class B. get() method of class A can return an instance of A, and get() method of class B return an instance of B.  Here class B overrides get() method, but the return type is different.

Before Java 5, any method that overrides the method of parent class would have same return type. From Java 5 onwards, a child class can override a method of parent class and the child class method can return an object that is child of object return by parent class method.

Polymorphism

52. What is Runtime Polymorphism?

Runtime Polymorphism or Dynamic Polymorphism is the polymorphism that exists at runtime. In case of method overriding it is not known which method will be called at runtime. Based on the type of object, JVM decides the exact method that should be called.

So at compile time it is not known which method will be called at run time.

53. Is it possible to achieve Runtime Polymorphism by data members in Java?

No. We need to create Runtime Polymorphism by implementing methods at two levels of inheritance in Java.

54. Explain the difference between static and dynamic binding?

In Static binding references are resolved at compile time. In Dynamic binding references are resolved at Run time.

E.g.

Person p = new Person();
p.walk();  // Java compiler resolves this binding at compile time.

public void walk(Object o){

((Person) o).walk(); // this is dynamic binding. }

Abstraction

55. What is Abstraction in Object Oriented programming?

Abstraction is the process of hiding certain implementation details of an object and showing only essential features of the object to outside world.

It is different from Abstract class in Java.

Abstraction process identifies commonalities and hides the complexity of implementation. It helps us in focusing on the interface that we share with the outside world.

56. How is Abstraction different from Encapsulation?

Abstraction happens at class level design. It results in hiding the implementation details. Encapsulation is also known as “Information Hiding”.  An example of encapsulation is marking the member variables private and providing getter and setter for these member variables.

57. What is an abstract class in Java?

An abstract class in Java has one or more abstract methods. An abstract method is just declared in the abstract class, but it is not implemented.

An abstract class has to be extended in Java and its abstract methods have to be implemented by a child class. Also Java does not allow new instance of Abstract class.

58. Is it allowed to mark a method abstract method without marking the class abstract?

No. Java specification says that if there is at least one abstract method in a class, the class has to be marked abstract.

59. Is it allowed to mark a method abstract as well as final?

No. It will be contradictory statement to mark a method abstract as well as final.

An abstract method has to be overridden by a child class. And a final method cannot be overridden.  Therefore a method can be either abstract or final in Java.

60. Can we instantiate an abstract class in Java?

No. We cannot create an instance of an abstract class in Java.

61. What is an interface in Java?

An Interface in Java is an abstract type blueprint of a class. It contains the methods that a class must implement. It is like a protocol.

It has method signatures and constant declarations.

62. Is it allowed to mark an interface method as static?

Yes, from Java 8 onwards, we can define static and default methods in an interface. Prior to Java 8, it was not allowed.

63. Why an Interface cannot be marked as final in Java?

A final method cannot be overridden. But an interface method has to be implemented by another class. So the interface method cannot be marked as final.

64. What is a marker interface?

There are interfaces that do not have any data member or methods. These interfaces are called Marker interface.

E.g. Serializable, Cloneable, Remote etc.

65. What can we use instead of Marker interface?

We can use annotations instead of Marker interface.

66. How Annotations are better than Marker Interfaces?

Annotations serve the purpose of conveying metadata about the class to its consumers without creating a separate type for it.

Annotations are more powerful than a Marker interface. They allow programmers to pass more sophisticated information to classes that “consume” it.

67. What is the difference between abstract class and interface in Java?

Differences between Abstract class and Interface are as follows:

  • An abstract class can have implemented methods with body (non-abstract methods). Interface has only abstract methods. From Java 8 onwards, interface can have static/default methods in implemented form.
  • An abstract class can have instance member variables. An interface cannot have instance variables. It can only have constants.
  • An abstract class can have a constructor. Interface cannot have constructor. It has to be implemented by another class.
  • A class can extend only one abstract class. A class can implement more than one interface.

68. Does Java allow us to use private and protected modifiers for variables in interfaces?

No. All the variables in an interface are implicitly public.

69. How can we cast to an object reference to an interface reference?

An Object that implements an Interface can be cast to the same Interface. Since An Object implementing an Interface already provides implementation for the methods of that Interface, it is allowed to do so as per the rules of Inheritance.

Final

70. How can you change the value of a final variable in Java?

Java does not allow changing the value of a final variable. Once the value is set, it cannot be changed.

71. Can a class be marked final in Java?

Yes a class can be marked final in Java. Once a class is marked final, it cannot be extended.

72. How can we create a final method in Java?

To mark a method, add modifier final to that method. A final method can not be overridden by a child class.

73. How can we prohibit inheritance in Java?

If you mark a class final, it cannot be extended. This will prohibit the inheritance of that class in Java.

74. Why Integer class in final in Java?

Integer class is a wrapper for int. If it is not marked final, then any other class can extend it and modify the behavior of Integer operations. To avoid this Integer wrapper class is marked as final.

75. What is a blank final variable in Java?

When we declare a final variable without giving any initial value, then it is called blank final variable.

76. How can we initialize a blank final variable?

A blank final instance variable can be initialized in a constructor. A blank final static variable can be initialized in the static block of class.

77. Is it allowed to declare main method as final?

Yes, we can mark the main method as final.

Package

78. What is the purpose of package in Java?

A package is used to encapsulate a group of classes, interfaces and sub-packages. Often, it is a hierarchical structure of storing information. It is easier to organize the related classes and sub-packages in this manner.

A Package also provides access protection for classes and interfaces. A package also helps in removing naming collision.

79. What is java.lang package?

In Java, java.lang package contains the classes that are fundamental to the design of Java programming language. The most important class in this package is Object class.

It also contains wrapper classes like- Integer, Boolean, Character etc. It provides Math class for mathematical operations.

80. Which is the most important class in Java?

It is an open-ended question with many answers. In my view, Object class is the most important class of Java programming language. It is the root of all the classes in Java. It provides some very important and fundamental methods.

81. Is it mandatory to import java.lang package every time?

No. By default, JVM loads it internally.

82. Can you import same package or class twice in your class?

If we import same package multiple times in a class, compiler includes it only once. So neither JVM nor Compiler gives any error/warning on including a package multiple times.

If you have two classes with same name, then you may get name collision on importing the class erroneously.

JVM internally loads the class only one time.

83. What is a static import in Java?

Static import is similar to normal import declaration. Normal import allows us to import classes from packages without using package qualifier. Static import allows us to import static members from a class without using class qualifier.

84. What is the difference between import static com.test.Fooclass and import com.test.Fooclass?

First import is a static import and the second import is normal import of a class. First import allows us to import static members of class.

Internationalization

85. What is Locale in Java?

A Locale object represents a specific geographical, political, or cultural region. It is used to locale-sensitive operations in Java.

It helps is following the local conventions of a country, native or region. These conventions can be for formatting the dates, money, numbers etc.

86. How will you use a specific Locale in Java?

To use a specific Locale, we need to load that Locale. We can use ResourceBundle.getBundle(“Locale.UK”) method to load a Locale.

Serialization

87. What is the serialization?

Serialization is a process converting an object into a byte array. This byte array represents the class, version and internal state of the object. JVM can use this byte array to transmit/read the object over a network.

88. What is the purpose of serialization?

Some of the uses of serialization are:

  • Communication: It is used for transmitting an object over network between two machines.
  • Persistence: We can store the object’s state in a database and retrieve it from database later on.
  • Caching: Serialization can be used for caching to improve performance.We may need 10 minutes to build an object, but it may take just 10 seconds to de-serialize the object.
  • Cross JVM Synchronization: It can be used in same way across multiple JVM that follow different architecture.

89. What is Deserialization?

Deserialization is the process of reconstructing the object from the serialized state. It is the reverse process of serialization.

90. What is Serialization and Deserialization conceptually?

Serialization is to convert Object data into a stream of bytes.

Deserialization is to convert a stream of bytes back into a copy of the original object.

91. Why do we mark a data member transient?

Member variables of an object are marked transient to indicate that they should not be serialized.

During serialization process the transient variables are not considered part of the persistent state of an object.

92. Is it allowed to mark a method as transient?

No, Java does not allow marking a method as transient. The transient keyword is valid only for member variables.

93. How does marking a field as transient makes it possible to serialize an object?

Let say we have a class ABC that implements Serializable interface, but it contains a member variable object of class XYZ that does not implement Serializable interface. Due to this it is not possible to Serialize the class ABC.

To solve this issue, we can mark the member variable XYZ as Transient in class ABC. This will allow us to serialize the class ABC.

94. What is Externalizable interface in Java?

Externalizable interface extends Serializable interface in Java. It is used for giving the Class control over saving and restoring the contents of its instances.

A class implements methods writeExternal() and readExternal() to  store and restore the object.

95. What is the difference between Serializable and Externalizable interface?

Serializable is a marker interface but Externalizable is not a marker interface.

When we implement Serializable interface, the class is serialized automatically by default. We can override writeObject() and readObject()methods to control more complex object Serialization process.

In case of Externalizable, we use readExternal() and writeExternal() methods to give control to class for class’s serialization process.

Serializable interface is based on recursive algorithm. Serializable gives you two options. One option is to provide custom way of serialization, the other default way. In Externalizable, you have to always implement readExternal() and writeExternal() methods.

A public no-arg constructor is needed while using Externalizable interface.

In Serialization, we need to define serialVersionUID. If it is not explicitly defined it will be generated automatically based on all the fields, methods of the class.

Reflection

96. What is Reflection in Java?

Reflection is Java language’s ability to inspect and dynamically call classes, methods, attributes etc. at Runtime. It helps in examining or modifying the Runtime behavior of a class at Runtime.

97. What are the uses of Reflection in Java?

Reflection is often used in Testing, Debugging and in Integrated Development Environment (IDE).

Reflection allows you to write programs that do not have to “know” everything at compile time. It makes programs more dynamic, since they can be tied together at runtime.

Many modern frameworks like Spring etc. use Reflection. Some modern languages like Python etc. also use Reflection.

JAVA API for XML Parsing (JAXP) also uses Reflection.

98. How can we access private method of a class from outside the class?

We can use Reflection to access private method of a class from outside the class. IN Java, we use getDeclaredMethod() to get instance of a private method. Then we mark this method accessible and finally invoke it.

In following sample code, we are accessing private method message() of class Foo by Reflection.

FileName: Foo.java
public class Foo {
private void message(){System.out.println(“hello java”); }
}

FileName: FooMethodCall.java
import java.lang.reflect.Method;
public class FooMethodCall{
public static void main(String[] args)throws Exception{
Class c = Class.forName(“Foo”);
Object o= c.newInstance();
Method m =c.getDeclaredMethod(“message”, null);
m.setAccessible(true);
m.invoke(o, null);
}
}

99. How can we create an Object dynamically at Runtime in Java?

We can use Reflection to create an Object dynamically at Runtime in Java. We can use Class.newInstance() or Constructor.newInstance() methods for creating such Objects.

Garbage Collection

100. What is Garbage Collection in Java?

Java has an internal mechanism called Garbage collection to reclaim the memory of unused projects at run time.

Garbage collection is also known as automatic memory management.

101. Why Java provides Garbage Collector?

In Java, there are no pointers. Memory management and allocation is done by JVM. Since memory allocation is automated, after some time JVM may go low on memory. At that time, JVM has to free memory from unused objects. To help with the process of reclaiming memory, Java provides an automated process called Garbage Collector.

102. What is the purpose of gc() in Java?

Java provides two methods System.gc() and Runtime.gc() to request the JVM to run the garbage collection. By using these methods, programmers can explicitly send request for Garbage Collection. But JVM process can reject this request and wait for some time before running the GC.

103. How does Garbage Collection work in Java?

Java has an automated process called Garbage Collector for Memory Management. It is a daemon in JVM that monitors the memory usage and performs memory cleanup. Once JVM is low on memory, GC process finds the unused objects that are not referenced by other objects. These unused objects are cleaned up by Garbage Collector daemon in JVM.

104. When does an object become eligible for Garbage Collection in Java?

An object can be Garbage Collected by JVM, if it is not reachable. There are two cases for deciding eligibility of objects for Garbage Collection:

  • An Object/instance that cannot be reached by a live thread.
  • A set of circularly referenced instances that cannot be reached by any other instance outside that set.

105. Why do we use finalize() method in Java?

Java provides finalize() method to perform any cleanup before Garbage Collection. This method is in Object class, and it is invoked by JVM internally. Developers are free to implement this method for any custom cleanup in case of Garbage Collection.

If an Object is not Garbage Collected, then this method may not be called.

This method is never invoked more than once by JVM.

106. What are the different types of References in Java?

In Java, there are four types of references:

  • Strong Reference
  • Soft Reference
  • Weak Reference
  • Phantom Reference

107. How can we reference an unreferenced object again?

We can provide implementation in finalize() method to reference and unreferenced object. For an unreferenced object, finalize() method is called at the time of Garbage Collection. At this time, Object can pass its reference ‘this’ to finalize() method and revive itself.

108. What kind of process is the Garbage collector thread?

Garbage Collection is a Daemon process in JVM. It is an internal process that keep checking Memory usage and cleans up the memory.

109. What is the purpose of the Runtime class?

The purpose of the Runtime class is to provide access to the Java Runtime system. This class provides certain important methods like:

  • Runtime.freeMemory() – This method returns the value of free memory in JVM
  • Runtime.maxMemory() – This method returns the value of maximum memory that JVM can use.
  • Runtime.gc() – This method can invoke garbage collection.

110. How can we invoke an external process in Java?

Java provides the method Runtime.getRuntime().exec() to invoke an external process from JVM.

111. What are the uses of Runtime class?

Runtime class in Java provides following benefits:

  • It allows to read data via key board
  • It can use system properties and environment variables
  • It helps in running non-java programs from within a java application.

Inner Classes

112. What is a Nested class?

In Java, a Nested class is a class declared inside another class. We can have more than one class declared inside a file.

113. How many types of Nested classes are in Java?

Java provides four types of Nested classes:

  • Member inner class
  • Local inner class
  • Anonymous inner class
  • Static nested class

114. Why do we use Nested Classes?

There are following reasons for using nested classes:

  • Logical Grouping: We can logically group classes in one place. If one class is useful to only one other class, then we put smaller class within the larger class and keep them in one file. This kind of nesting “helper classes” in a top-level class makes the package more streamlined.
  • Encapsulation: Nested classes increase encapsulation. Let say there are two top-level classes, Foo and Bar. Bar needs access to private members of Foo. We can hide class Bar within class Foo. In this way, private members of Foo can be accessed by class Bar. So class Foo remains encapsulated. Also, class Bar remains hidden from the outside world.
  • Code Clarity: Nested classed make the code more readable and well organized. Only Top-level classes are exposed. The helper classes are kept hidden and closer the code where it is used by a Top-level class.

115. What is the difference between a Nested class and an Inner class in Java?

An Inner class in Java is non-static class. It is a type of Nested class that is defined in another class but not qualified with a Static modifier. A Nested class is also a class can be Static Nested class or a non-Static Inner class.

An Inner class has access to other members of the enclosing class, even if they are declared private. A Static Nested class can not access the other members of the enclosing class.

116. What is a Nested interface?

A Nested interface is declared inside another interface or a top-level class. By default it is static.

A Nested interface is also known as Static interface.

117. How can we access the non-final local variable, inside a Local Inner class?

Java allows a Local Inner class to access only Constant local members. So we have to make the non-final local variable as final constant to access it inside a Local Inner class.

118. Can an Interface be defined in a Class?

Yes, we can define a Static Nested interface within a class. Only the enclosing class can access it.

119. Do we have to explicitly mark a Nested Interface public static?

A Nested Interface is implicitly public static. So the modifiers public and static are redundant in declaration.

120. Why do we use Static Nested interface in Java?

Only the enclosing class can access a Static Nested interface. Consider following code in which interface Xyz is enclosed in class Abc.

public class Abc {

public interface Xyz {

void callback();

}

public static void registerCallback(Xyz xyz) {…}

}

// Client Code

Abc.registerCallback(new Abc.Xyz() {

public void callback() {…}

});

Any code that cannot access Abc can not access interface Xyz also.

So the purpose of declaring an Inner interface is to restrict its access from outside world.

String

121. What is the meaning of Immutable in the context of String class in Java?

An Immutable object cannot be modified or changed in Java. String is an Immutable class in Java.

Once a String object is created, it cannot be changed. When we assign the String to a new value, a new object is created.

122. Why a String object is considered immutable in java?

Java language uses String for a variety of purposes. For this it has marked String Immutable.

There is a concept of String literal in Java.

Let say there are 2 String variables A and B that reference to a String object “TestData”. All these variables refer to same String literal. If one reference variable A changes the value of the String literal from “TestData” to “RealData”, then it will affect the other variable as well. Due to which String is considered Immutable. In this case, if one variable A changes the value to “RealData”, then a new String literal with “RealData” is created and A will point to new String literal. While B will keep pointing to “TestData”

123. How many objects does following code create?

Code:
String s1=”HelloWorld”;
String s2=” HelloWorld “;
String s3=” HelloWorld “;

The above code creates only one object. Since there is only one String Literal “HelloWorld” created, all the references point to same object.

124. How many ways are there in Java to create a String object?

Java provides two ways to create a String object. One is by using String Literal, the other is by using new operator.

125. How many objects does following code create?

Code:
String s = new String(“HelloWorld”);

The above code creates two objects. One object is created in String constant pool and the other is created on the heap in non-pool area.

126. What is String interning?

String interning refers to the concept of using only one copy of a distinct String value that is Immutable.

It provides the advantage of making String processing efficient in Time as well as Space complexity. But it introduces extra time in creation of String.

127. Why Java uses String literal concept?

Java uses String literal concept to make Java more efficient in memory. If same String already exists in String constant pool, it can be reused. This saves memory usage.

128. What is the basic difference between a String and StringBuffer object?

String is an immutable object. Its value cannot change after creation. StringBuffer is a mutable object. We can keep appending or modifying the contents of a StringBuffer in Java.

129. How will you create an immutable class in Java?

In Java, we can declare a class final to make it immutable. There are following detailed steps to make it Immutable:

  • Add final modifier to class to prevent it from getting extended
  • Add private modifier to all the fields to prevent direct access
  • Do not provide any setter methods for member variables
  • Add final modifier to all the mutable fields to assign value only once
  • Use Deep Copy to initialize all the fields by a constructor
  • In clone method, return a copy of object instead of the actual object reference

130. What is the use of toString() method in java ?

In Java, Object class has toString() method. This method can be used to return the String representation of an Object. When we print an object, Java implicitly calls toString() method.

Java provides a default implementation for toString() method. But we can override this method to return the format that we want to print.

131. Arrange the three classes String, StringBuffer and StringBuilder in the order of efficiency for String processing operations?

StringBuilder is the most efficient class. It does not have the overhead of Synchronization. StringBuffer is a Synchronized class. It has better performance than String but it is slower than StringBuilder. String is the slowest for any String processing operations, since it is leads to creation of new String literal with each modification.

So the decreasing order of efficiency is: StringBuilder, StringBuffer, String

Exception Handling

132. What is Exception Handling in Java?

Java provides Exception Handling mechanism to handle Runtime errors that occur in JVM. There are checked exceptions in a program that we expect to occur in certain situations.

Exception handling mechanism catches these checked exceptions and takes relevant actions.

133. In Java, what are the differences between a Checked and Unchecked?

Checked Exceptions extend Throwable class, but they do not extend RuntimeException or Error classes. UncheckedException extend RuntimeException class. Checked Exceptions are checked at compile time in Java. Unchecked Exceptions happen at Runtime, so they are not checked at compile time.

IOException, SQLException etc. are examples of Checked Exceptions. NullPointerException, ArithmeticException etc. are examples of Unchecked Exceptions.

134. What is the base class for Error and Exception classes in Java?

Error as well as Exception class is derived from Throwable class in Java.

135. What is a finally block in Java?

Java provides a finally block with a try block. This is an optional block. But finally block is always executed after the execution of try block.

136. What is the use of finally block in Java?

As per Java specification, a finally block is always executed, whether an error occurs or not, whether an exception is handled or not. It helps in doing the cleanup like- Rollback Transaction, Close Connection, Close a file etc.

137. Can we create a finally block without creating a catch block?

Yes. A finally block can follow a try block or catch block. So we can defined a finally block just after a try block.

138. Do we have to always put a catch block after a try block?

Java does not enforce the rule to put a catch block after try block. We can write catch block or finally block after a try block.

Any exception that we want to catch is mentioned in catch block.

139. In what scenarios, a finally block will not be executed?

There are two main scenarios in which finally block is not executed:

  • Program exits by calling system.exit() call.
  • A fatal error causes JVM to crash.

140. Can we re-throw an Exception in Java?

Yes, Java allows to re-throw an Exception.

141. What is the difference between throw and throws in Java?

Java provides throw keyword to throw an exception from a method or a static block. Java provides throws keyword to mention the probable exception thrown by a method in its declaration.

We use throw to explicitly throw an exception. We used throws to declare an exception in method definition.

We cannot propagate checked exceptions with throw only. But checked exceptions can be propagated with throws keyword.

A throw call is followed by an instance. Class or Exception follows a throws keyword. Call to throw occurs within a method. throws is just used with method signature.

We can throw only one exception at a time. But we can mention as many exceptions in throws clause.

142. What is the concept of Exception Propagation?

In Exception Propagation, uncaught exceptions are propagated in the call stack until stack becomes empty. This propagation is called Exception Propagation.

Let say an exception propagates from one method to another method. A() calls B(), which calls C(), which calls D(). And if D() throws an exception, the exception will propagate from D to C to B to A, unless one of the methods catches the exception.

143. When we override a method in a Child class, can we throw an additional Exception that is not thrown by the Parent class method?

Yes, Java allows us to throw additional Exception in a child class, but the additional exception should be an unchecked exception (RuntimeException).

Java Collection

144. What is the difference between Collection and Collections Framework in Java?

In Java, a Collection is an object that contains multiple elements of same type in a single unit. These multiple elements can be accessed through one Collection object.

In Java Collections Framework is a library that provides common architecture for creating, updating and accessing different types of collections. In Collections framework there are common methods that are frequently used by developers for working on a Collection object.

145. What are the main benefits of Collections Framework in Java?

Main benefits of Collections Framework in Java are as follows:

  • Reusability: Java Collections Framework provides common classes and utility methods than can be used with different types of collections. This promotes the reusability of the code. A developer does not have to re-invent the wheel by writing the same method again.
  • Quality: Using Java Collection Framework improves the program quality, since the code is already tested and used by thousands of developers.
  • Speed: Most of programmers report that their development speed increased since they can focus on core logic and use the generic collections provided by Java framework.
  • Maintenance: Since most of the Java Collections framework code is open source and API documents is widely available, it is easy to maintain the code written with the help of Java Collections framework. One developer can easily pick the code of previous developer.

146. What is the root interface of Collection hierarchy in Java?

The root interface of Collection hierarchy in Java is Collection interface.

But the Collection interface extends Iterable interface. Due to this some people consider Iterable interface as the root interface.

Iterable interface is present in java.lang package but Collection interface is present in java.util package. Oracle Java API docs mention that Collection interface is a member of the Java Collections framework.

Whereas, Iterable interface is not stated as a part of Java Collections framework in Java docs.

Due to this Collection interface is the root of Collections Framework.

147. What are the main differences between Collection and Collections?

Main differences between Collection and Collections are as follows:

  • Collection is an interface in Java. But Collections is a class in Java.
  • Collection is a base interface. Collections is a utility class in Java.
  • Collection defines methods that are used for data structures that contain the objects.Collections defines the methods that are used for operations like access, find etc. on a Collection.

148. What are the Thread-safe classes in Java Collections framework?

The Thread-safe classes in Java Collections framework are:

  • Stack
  • Properties
  • Vector
  • Hashtable
  • BlockingQueue
  • ConcurrentMap
  • ConcurrentNavigableMap

149. How will you efficiently remove elements while iterating a Collection?

The right way to remove elements from a collection while iterating is by using ListIterator.remove() method.

E.g.

ListIterator<Integer> iter = myList.iterator();
while(iter.hasNext()) {
itr.remove();

}

Some developers use following code to remove an element which is incorrect:

Iterator<Integer> iter = myList.iterator();
while(iter.hasNext()) {
itr.remove();

}

By doing so we get ConcurrentModificationException.

An iterator is first created to traverse the list. But at the same time the list is changed by remove() method.

In Java, it is not allowed for a thread to modify a collection while another thread is iterating it. ListIterator provides the capability of removing an object during traversal.

150. How will you convert a List into an array of integers like- int[]?

We can use ArrayUtils class in Apache Commons Lang library.

Sample code is:

int[]intArray = ArrayUtils.toPrimitive(myList.toArray(new Integer[0]));

If we use List.toArray(), it will convert List to Integer[].

Another option is:

int[] intArray = new int[myList.size()];
for (int i=0; i < myList.size(); i++)
{ intArray [i] = myList.get(i);

}

151. How will you convert an array of primitive integers int[] to a List collection?

We can use ArrayUtils in Apache Commons Lang library for this purpose.

Sample code is:

List intList = Arrays.asList(ArrayUtils.toObject(intArray));

The other option would be to use a for loop and explicitly adding integers to a List.

Sample code is:

int[]intArray = {10,20,30};
List<Integer> intList = new ArrayList<Integer>();
for (int i: intArray) {
intList.add(i);

}

152. How will you run a filter on a Collection?

We can use CollectionUtils of Apache for this purpose. We will have to create a Predicate that will define the condition for our filter. Then we can apply this Predicate in filter() method.

Sample code is:

In this example we filter any names that are less than 5 characters long.

List<String> namesList = asList( “Red”, “Blue”, “Green” );

List<String> shortNamesList = new ArrayList<String>();

shortNamesList.addAll( namesList );

CollectionUtils.filter( shortNamesList, new Predicate(){

public boolean evaluate( Object input ) {

return ((String) input).length() < 5;

}

} );

We can also use Google Guava library for this.

In Java 8, we can use Predicate to filter a Collection through Stream.

153. How will you convert a List to a Set?

There are two ways to convert a List to a Set in Java.

Option 1: Use HashSet

Set<Integer> mySet = new HashSet<Integer>(myList);

In this case we put a list into a HashSet. Internally hashCode() method is used to identify duplicate elements.

Option 2: Use TreeSet

In this case we use our own comparator to find duplicate objects.

Set<Integer> mySet = new TreeSet<Integer>(myComparator);

mySet.addAll(myList);

154. How will you remove duplicate elements from an ArrayList?

The trick in this question is to use a collection that does not allow duplicate elements. So we use a Set for this purpose.

Option 1: Use Set

If ordering of elements is not important then we just put the elements of ArrayList in a HashSet and then add them back to the ArrayList.

Sample Code is:

ArrayList  myList = // ArrayList with duplicate elements

Set<Integer> mySet = new HashSet<Integer>(myList);

myList.clear();

myList.addAll(mySet);

Option 2: Use LinkedHashSet

If ordering of elements is important then we put the elements of ArrayList in a LinkedHashSet and then add them back to the ArrayList.

Sample Code is:

ArrayList  myList = // ArrayList with duplicate elements

Set<Integer> mySet = new LinkedHashSet<Integer>(myList);

myList.clear();

myList.addAll(mySet);

155. How can you maintain a Collection with elements in Sorted order?

In Java, there are many ways to maintain a Collection with elements in sorted order.

Some collections like TreeSet store elements in the natural ordering. In case of natural ordering we have to implement Comparable interface for comparing the elements.

We can also maintain custom ordering by providing a custom Comparator to a Collection.

Another option is to use the utility method Collections.sort() to  sort a List. This sorting gives nlog(n) order of performance. But if we have to use this method multiple times then it will be costly on performance.

Another option is to use a PriorityQueue that provides an ordered queue. The main difference between PriorityQueue and Collections.sort() is that PriorityQueue maintains a queue in Order all the time, but we can only retrieve head element from queue. We cannot access the elements of PriorityQueue in Random order.

We can use TreeSet to maintain sorted order of elements in collection if there are no duplicate elements in collection.

156. What are the differences between the two data structures: a Vector and an ArrayList?

An ArrayList is a newer class than a Vector. A Vector is considered a legacy class in Java. The differences are:

  • Synchronization: Vector is synchronized, but the ArrayList is not synchronized. So an ArrayList has faster operations than a Vector.
  • Data Growth: Internally both an ArrayList and Vector use an array to store data. When an ArrayList is almost full it increases its size by 50% of the array size. Whereas a Vector increases it by doubling the underlying array size.

157. What are the differences between Collection and Collections in Java?

Main differences between Collection and Collections are:

  • Type: Collection is an interface in Java. Collections is a class.
  • Features: Collection interface provides basic features of data structure to List, Set and Queue interfaces. Collections is a utility class to sort and synchronize collection elements. It has polymorphic algorithms to operate on collections.
  • Method Type: Most of the methods in Collection are at instance level.Collections class has mainly static methods that can work on an instance of Collection.

158. In which scenario, LinkedList is better than ArrayList in Java?

ArrayList is more popular than LinkedList in Java due to its ease of use and random access to elements feature.

But LinkedList is better in the scenario when we do not need random access to elements or there are a lot of insertion, deletion of elements.

159. What are the differences between a List and Set collection in Java?

Main differences between a List and a Set are:

  • Order: List collection is an ordered sequence of elements. A Set is just a distinct collection of elements that is unordered.
  • Positional Access: When we use a List, we can specify where exactly we want to insert an element. In a Set there is no order, so we can insert element anywhere without worrying about order.
  • Duplicate: In a List we can store duplicate elements. A Set can hold only unique elements.

160. What are the differences between a HashSet and TreeSet collection in Java?

Main differences between a HashSet and TreeSet are:

  • Ordering: In a HashSet elements are stored in a random order. In a TreeSet, elements are stored according to natural ordering.
  • Null Value Element: We can store null value object in a HashSet. A TreeSet does not allow to add a null value object.
  • Performance: HashSet performs basic operations like add(), remove(), contains(), size() etc in a constant size time. A TreeSet performs these operations at the order of log(n) time.
  • Speed: A HashSet is better than a TreeSet in performance for most of operations like add(), remove(), contains(), size() etc .
  • Internal Structure: a HashMap in Java internally backs a HashSet. A NavigableMap backs a TreeSet internally.
  • Features:  A  TreeSet has more features compared to a HashSet. It has methods like pollFirst(), pollLast(), first(), last(), ceiling(), lower() etc.
  • Element Comparison: A HashSet uses equals() method for comparison. A TreeSet uses compareTo() method for comparison to maintain ordering of elements.

161. In Java, how will you decide when to use a List, Set or a Map collection?

  • If we want a Collection that does not store duplicate values, then we use a Set based collection.
  • If we want to frequently access elements operations based on an index value then we use a List based collection. E.g. ArrayList
  • If we want to maintain the insertion order of elements in a collection then we use a List based collection.
  • For fast search operation based on a key, value pair, we use a HashMap based collection.
  • If we want to maintain the elements in a sorted order, then we use a TreeSet based collection.

162. What are the differences between a HashMap and a Hashtable in Java?

Main differences between a HashMap and a Hashtable are:

  • Synchronization: HashMap is not a synchronized collection. If it is used in  multi-thread environment, it may not provide thread safety.  A Hashtable is a synchronized collection. Not more than one thread can access a Hashtable at a given moment of time. The thread that works on Hashtable acquires a lock on it and it makes other threads wait till its work is completed.
  • Null values: A HashMap allows only one null key and any number of null values. A Hashtable does not allow null keys and null values.
  • Ordering: A HashMap implementation by LinkedHashMap maintains the insertion order of elements. A TreeMap sorts the mappings based on the ascending order of keys. On the other hand, a Hashtable does not provide guarantee of any kind of order of elements. It does not maintain the mappings of key values in any specific order.
  • Legacy: Hashtable was not the initial part of collection framework in Java. It has been made a collection framework member, after being retrofitted to implement the Map interface. A HashMap implements Map interface and is a part of collection framework since the beginning.
  • Iterator: The Iterator of HashMap is a fail-fast and it throws ConcurrentModificationException if any other Thread modifies the map by inserting or removing any element except iterator’s own remove() method. Enumerator of the Hashtable is not fail-fast.

163. What are the differences between a HashMap and a TreeMap?

Main differences between a HashMap and a TreeMap in Java are:

  • Order: A HashMap does not maintain any order of its keys. In a HashMap there is no guarantee that the element inserted first will be retrieved first.
  • In a TreeMap elements are stored according to natural ordering of elements. A TreeMap uses compareTo() method to store elements in a natural order.
  • Internal Implementation: A HashMap uses Hashing internally. A TreeMap internally uses Red-Black tree implementation.
  • Parent Interfaces: A HashMap implements Map interface. TreeMap implements NavigableMap interface.
  • Null values: A HashMap can store one null key and multiple null values. A TreeMap can not contain null key but it may contain multiple null values.
  • Performance: A HashMap gives constant time performance for operations like get() and put(). A TreeMap gives order of log(n) time performance for get() and put() methods.
  • Comparison: A HashMap uses equals() method to compare keys. A TreeMap uses compareTo() method for maintaining natural ordering.
  • Features: A TreeMap has more features than a HashMap. It has methods like pollFirstEntry() , pollLastEntry() , tailMap() , firstKey() , lastKey() etc. that are not provided by a HashMap.

164. What are the differences between Comparable and Comparator?

Main differences between Comparable and Comparator are:

  • Type: Comparable<T> is an interface in Java where T is the type of objects that this object may be compared to.
  • Comparator<T> is also an interface where T is the type of objects that may be compared by this comparator.
  • Sorting: In Comparable, we can only create one sort sequence. In Comparator we can create multiple sort sequences.
  • Method Used: Comparator<T> interface in Java has method public int compare (Object o1, Object o2) that returns a negative integer, zero, or a positive integer when the object o1 is less than, equal to, or greater than the object o2. A Comparable<T> interface has method public int compareTo(Object o) that returns a negative integer, zero, or a positive integer when this object is less than, equal to, or greater than the object o.
  • Objects for Comparison: The Comparator compares two objects given to it as input.  Comparable interface compares “this” reference with the object given as input.
  • Package location: Comparable interface in Java is defined in java.lang package. Comparator interface in Java is defined in java.util package.

165. In Java, what is the purpose of Properties file?

A Properties file in Java is a list of key-value pairs that can be parsed by java.util.Properties class.

Generally a Properties file has extension .

properties e.g. myapp.properties. Properties files are used for many purposes in all kinds of Java applications. Some of the uses are to store configuration, initial data, application options etc. When we change the value of a key in a properties file, there is no need to recompile the Java application. So it provides benefit of changing values at runtime.

166. What is the reason for overriding equals() method?

The equals() method in Object class is used to check whether two objects are same or not. If we want a custom implementation we can override this method.

For example, a Person class has first name, last name and age. If we want two Person objects to be equal based on name and age, then we can override equals() method to compare the first name, last name and age of Person objects.

Generally in HashMap implementation, if we want to use an object as key, then we override equals() method.

167. How does hashCode() method work in Java?

Object class in Java has hashCode() method. This method returns a hash code value, which is an integer.

The hashCode() is a native method and its implementation is not pure Java.

Java doesn’t generate hashCode(). However, Object generates a HashCode based on the memory address of the instance of the object.

If two objects are same then their hashCode() is also same.

168. Is it a good idea to use Generics in collections?

Yes. A collection is a group of elements put together in an order or based on a property. Often the type of element can vary. But the properties and behavior of a Collection remains same. Therefore it is good to create a Collection with Generics so that it is type-safe and it can be used with wide variety of elements.

169. What is the difference between Collections.emptyList() and creating new instance of Collection?

In both the approaches, we get an empty list. But Collections.emptyList() returns an Immutable list. We cannot add new elements to an Immutable empty list.

Collections.emptyList() works like Singleton pattern. It does not create a new instance of List. It reuses an existing empty list instance.

Therefore, Collections.emptylist() gives better performance if we need to get an emptyList multiple times.

170. How will you copy elements from a Source List to another list?

There are two options to copy a Source List to another list.

Option 1: Use ArrayList constructor

ArrayList<Integer> newList = new ArrayList<Integer>(sourceList);

Option 2:  Use Collection.copy()

To use Collections.copy() destination list should be of same or larger size than source list.

ArrayList<Integer> newList = new ArrayList<Integer>(sourceList.size());
Collections.copy(newList, sourceList);

Collections.copy() does not reallocate the capacity of destination List if it does not have enough space to contain all elements of source List. It throws IndexOutOfBoundsException.

The benefit of Collection.copy() is that it guarantees that the copy will happen in linear time. It is also good for the scenario when we want to reuse an array instead of allocating more memory in the constructor of ArrayList.

One limitation of Collections.copy() is that it can accept only List as source and destination parameters.

171. What are the Java Collection classes that implement List interface?

Java classes that implement List interface are:

  • AbstractList
  • AbstractSequentialList
  • ArrayList
  • AttributeList
  • CopyOnWriteArrayList
  • LinkedList
  • RoleList
  • RoleUnresolvedList
  • Stack
  • Vector

172. What are the Java Collection classes that implement Set interface?

Java classes that implement Set interface are:

  • AbstractSet
  • ConcurrentSkipListSet
  • CopyOnWriteArraySet
  • EnumSet HashSet
  • JobStateReasons
  • LinkedHashSet
  • TreeSet

173. What is the difference between an Iterator and ListIterator in Java?

  • Iterator and ListIterator are two interfaces in Java to traverse data structures. The differences between these two are:
  • ListIterator can be used to traverse only a List. But Iterator can be used to traverse List, Set, and Queue etc.
  • An Iterator traverses the elements in one direction only. It just goes. ListIterator can traverse the elements in two directions i.e. backward as well as forward directions.
  • Iterator cannot provide us index of an element in the Data Structure. ListIterator provides us methods like nextIndex() and previousIndex() to get the index of an element during traversal.
  • Iterator does not allow us to add an element to collection while traversing it. It throws ConcurrentModificationException. ListIterator allows use to add an element at any point of time while traversing a list.
  • An existing element’s value cannot be replaced by using Iterator. ListIterator provides the method set(e) to replace the value of last element returned by next() or previous() methods.

174. What is the difference between Iterator and Enumeration?

Both Iterator and Enumeration are interfaces in Java to access Data Structures. The main differences between these are:

  • Enumeration is an older interface. Iterator is a newer interface.
  • Enumeration can only traverse legacy collections. Iterator can traverse both legacy as well as newer collections.
  • Enumeration does not provide remove() method. So we cannot remove any element during traversal. Iterator provides remove() method.
  • Iterator is a fail-fast interface, it gives ConcurrentModificationException if any thread tries to modify an element in the collection being iterated. Enumeration is not fail-fast.
  • Method names in Iterator are shorter than in an Enumeration.

175. What is the difference between an ArrayList and a LinkedList data structure?

Main differences between ArrayList and LinkedList data structures are:

  • Data Structure: An ArrayList is an indexed based dynamic array. A LinkedList is a Doubly Linked List data structure.
  • Insertion: It is easier to insert new elements in a LinkedList, since there is no need to resize an array. Insertion in ArrayList is O(n), since it may require resizing of array and copying its contents to new array.
  • Remove elements: LinkedList has better performance in removal of elements than ArrayList.
  • Memory Usage: LinkedList uses more memory than ArrayList, since it has to maintain links for next and previous nodes as well.
  • Access: LinkedList is slower in accessing an element, since we have to traverse the list one by one to access the right location.

176. What is the difference between a Set and a Map in Java?

Main differences between a Set and a Map in Java are:

  • Duplicate Elements: A Set does not allow inserting duplicate elements. A Map does not allow using duplicate keys, but it allows inserting duplicate values for unique keys.
  • Null values: A Set allows inserting maximum one null value. In a Map we can have single null key at most and any number of null values.
  • Ordering: A Set does not maintain any order of elements. Some of sub-classes of a Set can sort the elements in an order like LinkedHashSet. A Map does not maintain any order of its elements. Some of its sub-classes like TreeMap store elements of the map in ascending order of keys.

177. What is the use of a Dictionary class?

The Dictionary class in Java is used to store key-value pairs. Any non-null object can be used for key or value. But we cannot insert a null key or null object in Dictionary.

Dictionary class is deprecated now. So it should not be used in newer implementations.

178. What is the default size of load factor in a HashMap collection in Java?

Default value of load factor in a HashMap is 0.75.

179. What is the significance of load factor in a HashMap in Java?

A HashMap in Java has default initial capacity 16 and the load factor is 0.75f (i.e. 75% of current map size). The load factor of a HashMap is the level at which its capacity should be doubled.

For example, in a HashMap of capacity 16 and load factor .75. The capacity will become 32 when the HashMap is 75% full. Therefore, after storing the 12th key– value pair (16 * .75 = 12) into HashMap, its capacity becomes 32.

180. What are the major differences between a HashSet and a HashMap?

The main difference between a HashSet and a HashMap are:

  • Base class: A HashSet class implements the Set interface. Whereas a HashMap class implements the Map interface.
  • Storage: A HashSet is used to store distinct objects. A HashMap is used for storing key & value pairs, so that these can be retrieved by key later on.
  • Duplicate Elements: A HashSet does not allow storing duplicate elements. A HashMap also does not allow duplicate keys. But we can store duplicate values in a HashMap.
  • Null Elements: In a HashSet we can store a single null value. In a HashMap we can store single null key, but any number of null values.
  • Element Type: A HashSet contains only values of objects as its elements. Whereas a HashMap contains entries(key value pairs).
  • Iteration: By using an Iterator we can iterate a HashSet. But a HashMap has to be converted into Set for iteration.

181. What are the similarities between a HashSet and a HashMap in Java?

As the name suggests, HashSet and HashMap are Hashing based collections. Similarities between HashSet and HashMap are:

  • Thread Safety: Both HashMap and HashSet are not synchronized collections. Therefore they are not good for thread-safe operations. To make these thread-safe we need to explicitly use synchronized versions.
  • Order of Elements: None of these classes guarantee the order of elements. These are unordered collections. Internal
  • Implementation: A HashMap backs up a HashSet internally. So HashSet uses a HashMap for performing its operations.
  • Performance: Both of these collections provide constant time performance for basic operations such as insertion and removal of elements.

182. What is the reason for overriding equals() method?

The equals() method in Object class is used to check whether two objects are same or not. If we want a custom implementation we can override this method.

For example, a Person class has first name, last name and age. If we want two Person objects to be equal based on name and age, then we can override equals() method to compare the first name, last name and age of Person objects.

Generally in HashMap implementation, if we want to use an object as key, then we override equals() method.

183. How can we synchronize the elements of a List, a Set or a Map?

Sometimes we need to make collections Thread-safe for use in Multi-threading environment. In Java, Collections class provides useful static methods to make a List, Set or Map as synchronized collections. Some of these methods are:

  • static <T> Collection<T>​synchronizedCollection(Collection<T> c) Returns a synchronized (thread-safe) collection backed by the specified collection.
  • static <T> List<T>​synchronizedList(List<T> list) Returns a synchronized (thread-safe) list backed by the specified list.
  • static <K,V> Map<K,V>​synchronizedMap(Map<K,V> m) Returns a synchronized (thread-safe) map backed by the specified map.
  • static <T> Set<T>​  synchronizedSet(Set<T> s) Returns a synchronized (thread-safe) set backed by the specified set.
  • static <K,V> SortedMap<K,V>​synchronizedSortedMap(SortedMap<K,V> m) Returns a synchronized (thread-safe) sorted map backed by the specified sorted map.
  • static <T> SortedSet<T>​synchronizedSortedSet(SortedSet<T> s) Returns a synchronized (thread-safe) sorted set backed by the specified sorted set.

184. What is Hash Collision? How Java handles hash-collision in HashMap?

In a Hashing scenario, at times two different objects may have same HashCode but they may not be equal. Therefore, Java will face issue while storing the two different objects with same HashCode in a HashMap. This kind of situation is Hash Collision.

There are different techniques of resolving or avoiding Hash Collision. But in HashMap, Java simply replaces the Object at old Key with new Object in case of Hash Collision.

185. What are the Hash Collision resolution techniques?

To resolve a Hash Collision we can use one of the following techniques:

  • Separate Chaining with Linked List
  • Separate Chaining with List Head Cells
  • Open Addressing with Coalesced Hashing
  • Open Addressing with Cuckoo Hashing
  • Hopscotch Hashing
  • Robinhood Hashing

186. What is the difference between Queue and Stack data structures?

Queue is a FIFO data structure. FIFO stands for First In First Out. It means the element added first will be removed first from the queue. A real world example of Queue is a line for buying tickets at a station. The person entering first in the Queue is served first.

Stack is a LIFO data structure. LIFO stands for Last In First Out. The element that is added last is removed first from the collection. In a Stack elements are added or removed from the top of stack.

A real world example of Stack is back button in browser. We can go back one by one only and it works in the reverse order of adding webpages to history .

187. What is an Iterator in Java?

Iterator is an interface in Java to access the elements in a collection. It is in java.util package.

It provides methods to iterate over a Collection class in Java.

Iterator interface in Java is based on Iterator design pattern. By using an Iterator one can traverse a container of objects and can also access the objects in the container. A container of objects is a Collection class in Java.

188. What is the difference between Iterator and Enumeration in Java?

Main differences between Iterator and Enumeration in Java are:

  • Version: Enumeration interface is in Java since JDK 1.0. Iterator interface was introduced in Java 1.2.
  • remove() method: The main difference between Enumeration and Iterator interface is remove() method. Enumeration can just traverse a Collection object. If we use Enumeration, we cannot do any modifications to a Collection while traversing the collection. Iterator interface provides remove() method to remove an element while traversing the Collection. There is not remove() method in Enumeration interface.
  • Method names: Names of methods in Iterator interface are hasNext(), next(), remove(). Names of methods in Enumeration interface are hasMoreElements(), nextElement().
  • Legacy Interface: Enumeration is considered as a legacy interface. It is used to traverse legacy classes like Vector, Stack and HashTable. Iterator is a newer interface that is used to traverse almost all of the classes in Java Collections framework.
  • Fail-fast vs.Fail-safe: Iterator is based on fail-fast principle. It throws ConcurrentModificationException if a collection is modified during iteration over that collection. An Enumeration is based on fail-safe principle. It doesn’t throw any exception if a collection is modified during traversal.
  • Safety: Since Iterator is fail-fast and does not allow modification of a collection by other threads, it is considered safer than Enumeration.

189. What is the design pattern used in the implementation of Enumeration in Java?

Enumeration is based on Iterator design pattern. Iterator design pattern provides a common interface with methods to traverse the collection of objects. It hides the underlying implementation details of the collection.

190. Which methods do we need to override to use an object as key in a HashMap?

If we want to use an object as a key in a HashMap in Java, then we have to make sure that it has the implementation of equals() and hashCode() methods.

191. How will you reverse a List in Java?

In Collections class, Java provides a method reverse(List list) that can be used to reverse a List.

E.g. Collections.reverse(myList);

192. How will you convert an array of String objects into a List?

Java provides Arrays class in java.util package. Arrays class has a method asList() that accepts an Array as input and returns a List as output.

public static <T> List<T> asList(T… a)

String[]  myArray =  {“George”  , “Jack” , “Ryan”};

List myList =  Arrays.asList(myArray);

193. What is the difference between peek(), poll() and remove() methods of Queue interface in java?

In a Java Queue, poll() and remove() methods can be used for removing the head object of Queue. The main difference arises in the case when Queue is empty().

If Queue is empty then poll() method returns null value. If Queue is empty then remove() method throws NoSuchElementException.

In a Java Queue, peek() method retrieves the head of Queue but it does not remove it. If queue is empty then peek() method returns null value.

194. What is the difference between Array and ArrayList in Java?

The main differences between Array and ArrayList in Java are:

  • Size: Array in Java is fixed in size. We cannot change the size of array after creating it. ArrayList is dynamic in size. When we add elements to an ArrayList, its capacity increases automatically.
  • Performance: In Java Array and ArrayList give different performance for different operations.
  • add() or get(): Adding an element to or retrieving an element from an array or ArrayList object has similar performance. These are constant time operations.
  • resize(): Automatic resize of ArrayList slows down the performance. ArrayList is internally backed by an Array. In resize() a temporary array is used to copy elements from old array to new array.
  • Primitives: Array can contain both primitive data types as well as objects. But ArrayList cannot contain primitive data types. It contains only objects.
  • Iterator: In an ArrayList we use an Iterator  object to traverse the elements. We use for loop for iterating elements in an array.
  • Type Safety:  Java helps in ensuring Type Safety of elements in an ArrayList by using Generics. An Array can contain objects of same type of class. If we try to store a different data type object in an Array then it throws ArrayStoreException.
  • Length:  Size of ArrayList can be obtained by using size() method. Every array object has length variable that is same as the length/size of the array.
  • Adding elements: In an ArrayList we can use add() method to add objects. In an Array assignment operator is used for adding elements.
  • Multi-dimension: An Array can be multi-dimensional. An ArrayList is always of single dimension.

195. How will you insert, delete and retrieve elements from a HashMap collection in Java?

We use following methods to insert, delete and retrieve elements in a HashMap.

  • Retrieve: We use get() method to retrieve elements from a HashMap.

Value get(Object key)

  • Insert: We use put() method to insert a key value pair in a HashMap.

Value put(Key k, Value v)

  • Delete: We use remove() method to delete key-value pair from the HashMap.

Value remove(Object key)

196. What are the main differences between HashMap and ConcurrentHashMap in Java?

Main differences between HashMap and ConcurrentHashMap are:

  • Synchronization: A HashMap is not synchronized. But a ConcurrentHashMap is a synchronized object.
  • Null Key: A HashMap can have one null key and any number of null values. A ConcurrentHashMap cannot have null keys or null values.
  • Multi-threading: A ConcurrentHashMap works well in a multi-threading environment.

197. What is the increasing order of performance for following collection classes in Java?

The increasing order of performance is:

  • Hashtable Collections.
  • SynchronizedMap
  • ConcurrentHashMap
  • HashMap

Hashtable has the worst performance and HashMap has the best performance.

198. Why does Map interface not extend Collection interface in Java?

A Map is a collection objects. But Map interface is not compatible with Collection interface in Java.

A Map requires key as well as a value. So it requires two parameters to add an element to a HashMap.

But Collection interface provides add(Object o) method with only one parameter.

Map collection has to provide methods like valueSet, keySet etc.  These methods are specific to Map collection. Where as methods in Collection interface can be reused by a List, Set, Queue etc.

199. What are the different ways to iterate elements of a list in Java?

There are mainly two ways to iterate the elements of list in Java:

  • Iterator: We can get an Iterator for list and use it to iterate the objects of the list.
  • For-each loop: We can use for-each loop to traverse all the elements of a list.

200. What is CopyOnWriteArrayList? How it is different from ArrayList in Java?

CopyOnWriteArrayList was introduced in Java 5 version. It is a thread-safe collection. It is similar to an ArrayList.

In CopyOnWriteArrayList, all mutative operations (add, set etc.) are implemented by making a fresh copy of the underlying array.

Iterator of CopyOnWriteArrayList is guaranteed to not throw ConcurrentModificationException. But Iterator also does not reflect any additions, removals that happened to list after the Iterator was created.

All elements including null are permitted in CopyOnWriteArrayList.

201. How remove() method is implemented in a HashMap?

Remove() method in HashMap uses logic similar to the one used in get() method. First we locate the correct bucket in HashMap for an entry. Then within that bucket we remove the element e. It is similar to removing a node from a single-linked list.

If e is the first element in the bucket we set the corresponding element of Hash to e.next. Else we set the next field of the element just before e to e.next.

202. What is BlockingQueue in Java Collections?

BlockingQueue was introduced in Java 1.5. It extends Queue interface in Java.

BlockingQueue supports operations that wait for the queue to become non-empty when retrieving an element. Also it supports the operations that wait for space to become available in the queue while storing an element.

Some of the features of BlockingQueue are:

  • It does not accept null elements.
  • Its main use is in producer-consumer problems.
  • BlockingQueue implementation is thread-safe.
  • It can be used in inter-thread communications.
  • It does not support any kind of “close” or “shutdown” operation to indicate that no more items will be added.

203. How is TreeMap class implemented in Java?

Internally, a TreeMap class in Java uses Red-Black tree.

It is a NavigableMap. The map sorts the keys in natural order or it can use a Comparator supplied at the creation time.

The implementation of TreeMap is not synchronized in Java.

204. What is the difference between Fail-fast and Fail-safe iterator in Java?

Differences between Fail-fast and Fail-safe iterators are as follows:

  • Fail-fast iterator throws ConcurrentModificationException. But Fail-safe iterator does not throw this exception.
  • Fail-fast iterator does not clone the original collection. Fail-safe iterator creates a copy of the original collection of objects.
  • A Fail-fast iterator tries to immediately throw Exception when it encounters failure. A Fail-safe Iterator works on a copy of collection instead of original collection.

205. How does ConcurrentHashMap work in Java?

ConcurrentHashMap extends AbstractMap in Java. It was introduced in Java 1.5. It provides concurrency in a collection based on a HashMap.

All methods are thread-safe in ConcurrentHashMap.

Internally there is a Hashtable backing a ConcurrentHashMap. Thi