Java Interview Qns

What do you understand by Java virtual machine?

Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM acts like a run-time engine which calls the main method present in the Java code. JVM is the specification which must be implemented in the computer system. The Java code is compiled by JVM to be a Bytecode which is machine independent and close to the native code.

How many types of memory areas are allocated by JVM?

Many types:
  1. Class(Method) Area: Class Area stores per-class structures such as the runtime constant pool, field, method data, and the code for methods.
  2. Heap: It is the runtime data area in which the memory is allocated to the objects
  3. Stack: Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as the thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
  4. Program Counter Register: PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.
  5. Native Method Stack: It contains all the native methods used in the application.

JVM Architecture

Let's understand the internal architecture of JVM. It contains classloader, memory area, execution engine etc.

.

1) Classloader

Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java.
  1. Bootstrap ClassLoader: This is the first classloader which is the super class of Extension classloader. It loads the rt.jarfile which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes etc.
  2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
  3. System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the classfiles from classpath. By default, classpath is set to current directory. You can change the classpath using "-cp" or "-classpath" switch. It is also known as Application classloader.
  1. //Let's see an example to print the classloader name  
  2. public class ClassLoaderExample  
  3. {  
  4.     public static void main(String[] args)  
  5.     {  
  6.         // Let's print the classloader name of current class.   
  7.         //Application/System classloader will load this class  
  8.         Class c=ClassLoaderExample.class;  
  9.         System.out.println(c.getClassLoader());  
  10.         //If we print the classloader name of String, it will print null because it is an 
  11.         //in-built class which is found in rt.jar, so it is loaded by Bootstrap classloader
  12.         System.out.println(String.class.getClassLoader());  
  13.     }  
  14. }     

Output:
sun.misc.Launcher$AppClassLoader@4e0e2f2a
null

These are the internal classloaders provided by Java. If you want to create your own classloader, you need to extend the ClassLoader class.

2) Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack

Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

5) Program Counter Register

PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.

6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine

It contains:
  1. A virtual processor
  2. Interpreter: Read bytecode stream then execute the instructions.
  3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here, the term "compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

8) Java Native Interface

Java Native Interface (JNI) is a framework which provides an interface to communicate with another application written in another language like C, C++, Assembly etc. Java uses JNI framework to send output to the Console or interact with OS libraries.

What is JIT compiler?

Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the bytecode that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

What is the platform?

A platform is the hardware or software environment in which a piece of software is executed. There are two types of platforms, software-based and hardware-based. Java provides the software-based platform.

What are the main differences between the Java platform and other platforms?

There are the following differences between the Java platform and other platforms.
  • Java is the software-based platform whereas other platforms may be the hardware platforms or software-based platforms.
  • Java is executed on the top of other hardware platforms whereas other platforms can only have the hardware components.

What gives Java its 'write once and run anywhere' nature?

The bytecode. Java compiler converts the Java programs into the class file (Byte Code) which is the intermediate language between source code and machine code. This bytecode is not platform specific and can be executed on any computer.

Is Empty .java file name a valid source file name?

Yes, Java allows to save our java file by .java only, we need to compile it by javac .java and run by java classname

Is delete, next, main, exit or null keyword in java?

No.

What is the default value of the local variables?

The local variables are not initialized to any default value, neither primitives nor object references.

  • Public The classes, methods, or variables which are defined as public, can be accessed by any class or method.
  • Protected Protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.
  • Default Default are accessible within the package only. By default, all the classes, methods, and variables are of default scope.
  • Private The private class, methods, or variables defined as private can be accessed within the class only.
The methods or variables defined as static are shared among all the objects of the class. The static is the part of the class and not of the object.

For example, In the class simulating the collection of the students in a college, the name of the college is the common attribute to all the students. Therefore, the college name will be defined as static.

  • Packages avoid the name clashes.
  • The Package provides easier access control.
  • We can also have the hidden classes that are not visible outside and used by the package.
  • It is easier to locate the related classes.

What is an object?

The Object is the real-time entity having some state and behavior. In Java, Object is an instance of the class having the instance variables as the state of the object and the methods as the behavior of the object. The object of a class can be created by using the new keyword.

  • Object-oriented languages follow all the concepts of OOPs whereas, the object-based language doesn't follow all the concepts of OOPs like inheritance and polymorphism.
  • Examples of object-oriented programming are Java, C#, Smalltalk, etc. whereas the examples of object-based languages are JavaScript, VBScript, etc. 
The purpose of the default constructor is to assign the default value to the objects. The java compiler creates a default constructor implicitly if there is no constructor in the class.

Constructor Interview Questions

Is constructor inherited?

No, The constructor is not inherited

Can you make a constructor final?

No, the constructor can't be final

Can we overload the constructors?

Yes, the constructors can be overloaded by changing the number of arguments accepted by the constructor or by changing the data type of the parameters.

What do you understand by copy constructor in Java?

There is no copy constructor in java. However, we can copy the values from one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class

Static Interview Questions

What are the restrictions that are applied to the Java static methods?

Two main restrictions are applied to the static methods.
  • The static method can not use non-static data member or call the non-static method directly.
  • this and super cannot be used in static context as they are non-static.

Can we override the static methods?

No, we can't override static methods.

What if the static modifier is removed from the signature of the main method?

Program compiles. However, at runtime, It throws an error "NoSuchMethodError."

Can we make constructors static?

As we know that the static context (method, block, or variable) belongs to the class, not the object. Since Constructors are invoked only when the object is created, there is no sense to make the constructors static. However, if you try to do so, the compiler will show the compiler error.

Can we make the abstract methods static in Java?

In Java, if we make the abstract methods static, It will become the part of the class, and we can directly call it which is unnecessary. Calling an undefined method is completely useless therefore it is not allowed.

Can you use this() and super() both in a constructor?

No, because this() and super() must be the first statement in the class constructor.

What is object cloning?

The object cloning is used to create the exact copy of an object. The clone() method of the Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.
  1. protected Object clone() throws CloneNotSupportedException
Method Overloading Interview Questions

What is method overloading?

Method overloading is the polymorphism technique which allows us to create multiple methods with the same name but different signature. We can achieve method overloading in two ways.
  • Changing the number of arguments
  • Changing the return type
Method overloading increases the readability of the program.

Why is method overloading not possible by changing the return type in java?

In Java, method overloading is not possible by changing the return type of the program due to avoid the ambiguity.

Can we overload the methods by making them static?

No, We cannot overload the methods by just applying the static keyword to them(number of parameters and types are the same).



Method Overriding Interview Questions

What is method overriding:

If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to implement the interface methods.
Rules for Method overriding
  • The method must have the same name as in the parent class.
  • The method must have the same signature as in the parent class.
  • Two classes must have an IS-A relationship between them.

Can we override the static method?

No, you can't override the static method because they are the part of the class, not the object.

Why can we not override static method?

It is because the static method is the part of the class, and it is bound with class whereas instance method is bound with the object, and static gets memory in class area, and instance gets memory in a heap.

Can we override the overloaded method?

Yes.

Can we override the private methods?

No, we cannot override the private methods because the scope of private methods is limited to the class and we cannot access them outside of the class.

Can we change the scope of the overridden method in the subclass?

Yes, we can change the scope of the overridden method in the subclass. However, we must notice that we cannot decrease the accessibility of the method. The following point must be taken care of while changing the accessibility of the method.
  • The private can be changed to protected, public, or default.
  • The protected can be changed to public or default.
  • The default can be changed to public.
  • The public will always remain public.

Can we modify the throws clause of the superclass method while overriding it in the subclass?

Yes, we can modify the throws clause of the superclass method while overriding it in the subclass. However, there are some rules which are to be followed while overriding in case of exception handling.
  • If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception, but it can declare the unchecked exception.
  • If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

final keyword Interview Questions

What is the final variable?

In Java, the final variable is used to restrict the user from updating it. If we initialize the final variable, we can't change its value. In other words, we can say that the final variable once assigned to a value, can never be changed after that. The final variable which is not assigned to any value can only be assigned through the class constructor.

What is the final method?

If we change any method to a final method, we can't override it.

What is the final class?

If we make any class final, we can't inherit it into any of the subclasses.

What is the final blank variable?

A final variable, not initialized at the time of declaration, is known as the final blank variable. We can't initialize the final blank variable directly. Instead, we have to initialize it by using the class constructor. It is useful in the case when the user has some data which must not be changed by others, for example, PAN Number.

Can we declare a constructor as final?

The constructor can never be declared as final because it is never inherited. Constructors are not ordinary methods; therefore, there is no sense to declare constructors as final. However, if you try to do so, The compiler will throw an error.

Can we declare an interface as final?

No, we cannot declare an interface as final because the interface must be implemented by some class to provide its definition. Therefore, there is no sense to make an interface final. However, if you try to do so, the compiler will show an error.

What is the difference between the final method and abstract method?

The main difference between the final method and abstract method is that the abstract method cannot be final as we need to override them in the subclass to give its definition.



Can you achieve Runtime Polymorphism by data members?

No, because method overriding is used to achieve runtime polymorphism and data members cannot be overridden. We can override the member functions but not the data members.

What is the difference between static binding and dynamic binding?

In case of the static binding, the type of the object is determined at compile-time whereas, in the dynamic binding, the type of the object is determined at runtime.
Static Binding
  1. class Dog{  
  2.  private void eat(){System.out.println("dog is eating...");}  
  3.   
  4.  public static void main(String args[]){  
  5.   Dog d1=new Dog();  
  6.   d1.eat();  
  7.  }  
  8. }  
Dynamic Binding
  1. class Animal{  
  2.  void eat(){System.out.println("animal is eating...");}  
  3. }  
  4.   
  5. class Dog extends Animal{  
  6.  void eat(){System.out.println("dog is eating...");}  
  7.   
  8.  public static void main(String args[]){  
  9.   Animal a=new Dog();  
  10.   a.eat();  
  11.  }  
  12. }  

What is Java instanceOf operator?

The instanceof in Java is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has a null value, it returns false.

Abstraction Interview Questions

What is the abstraction?

Abstraction is a process of hiding the implementation details and showing only functionality to the user. It displays just the essential things to the user and hides the internal information, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery. Abstraction enables you to focus on what the object does instead of how it does it. Abstraction lets you focus on what the object does instead of how it does it.
In Java, there are two ways to achieve the abstraction.
  • Abstract Class
  • Interface

What is the difference between abstraction and encapsulation?

Abstraction hides the implementation details whereas encapsulation wraps code and data into a single unit.

Can there be an abstract method without an abstract class?

No, if there is an abstract method in a class, that class must be abstract.

Can you use abstract and final both with a method?

No, because we need to override the abstract method to provide its implementation, whereas we can't override the final method.

Is it possible to instantiate the abstract class?

No, the abstract class can never be instantiated even if it contains a constructor and all of its methods are implemented.

What is the interface?

The interface is a blueprint for a class that has static constants and abstract methods. It can be used to achieve full abstraction and multiple inheritance. It is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body.

Can you declare an interface method static?

No, because methods of an interface are abstract by default, and we can not use static and abstract together.

Can the Interface be final?

No, because an interface needs to be implemented by the other class and if it is final, it can't be implemented by any class.

What is a marker interface?

A Marker interface can be defined as the interface which has no data member and member functions. For example, Serializable, Cloneable are marker interfaces. The marker interface can be declared as follows.
  1. public interface Serializable{    
  2. }    

Can we define private and protected modifiers for the members in interfaces?

No, they are implicitly public.

When can an object reference be cast to an interface reference?

An object reference can be cast to an interface reference when the object implements the referenced interface.

How to make a read-only class in Java?

A class can be made read-only by making all of the fields private. The read-only class will have only getter methods which return the private property of the class to the main method. We cannot modify this property because there is no setter method available in the class.

How to make a write-only class in Java?

A class can be made write-only by making all of the fields private. The write-only class will have only setter methods which set the value passed from the main method to the private fields. We cannot read the properties of the class because there is no getter method in this class.

What are the advantages of Encapsulation in Java?

There are the following advantages of Encapsulation in Java?
  • By providing only the setter or getter method, you can make the class read-only or write-only. In other words, you can skip the getter or setter methods.
  • It provides you the control over the data. Suppose you want to set the value of id which should be greater than 100 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods.
  • It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data members.
  • The encapsulate class is easy to test. So, it is better for unit testing.
  • The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and fast to create an encapsulated class in Java.
Package Interview Questions

What is the package?

A package is a group of similar type of classes, interfaces, and sub-packages. It provides access protection and removes naming collision. The packages in Java can be categorized into two forms, inbuilt package, and user-defined package. There are many built-in packages such as Java, lang, awt, javax, swing, net, io, util, sql, etc. Consider the following example to create a package in Java.

What are the advantages of defining packages in Java?



By defining packages, we can avoid the name conflicts between the same class names defined in different packages. Packages also enable the developer to organize the similar  
classes more effectively.

  • Define a package package_name. Create the class with the name class_name and save this file with your_class_name.java.

  • Now compile the file by running the following command on the terminal.
    1. javac -d . your_class_name.java  
    The above command creates the package with the name package_name in the present working directory.
  • Now, run the class file by using the absolute class file name, like following.
    1. java package_name.class_name  


How can we access some class in another class in Java?

There are two ways to access a class in another class.
  • By using the fully qualified name: To access a class in a different package, either we must use the fully qualified name of that class, or we must import the package containing that class.
  • By using the relative path, We can use the path of the class that is related to the package that contains our class. It can be the same or subpackage.

Do I need to import java.lang package any time? Why?

No. It is by default loaded internally by the JVM.

What is the static import?

By static import, we can access the static members of a class directly, and there is no to qualify it with the class name.

Exception Handling Interview Questions

How many types of exception can occur in a Java program?

There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked exception. According to Oracle, there are three types of exceptions:
  • Checked Exception: Checked exceptions are the one which are checked at compile-time. For example, SQLException, ClassNotFoundException, etc.

  • Unchecked Exception: Unchecked exceptions are the one which are handled at runtime because they can not be checked at compile-time. For example, ArithmaticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.

  • Error: Error cause the program to exit since they are not recoverable. For Example, OutOfMemoryError, AssertionError, etc.

What is Exception Handling?

Exception Handling is a mechanism that is used to handle runtime errors. It is used primarily to handle checked exceptions. Exception handling maintains the normal flow of the program. There are mainly two types of exceptions: checked and unchecked. Here, the error is considered as the unchecked exception.

Explain the hierarchy of Java Exception classes?

Explain Carefully.

What is the difference between Checked Exception and Unchecked Exception?

1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions, e.g., IOException, SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions, e.g., ArithmeticException, NullPointerException, etc. Unchecked exceptions are not checked at compile-time.

What is the base class for Error and Exception?

The Throwable class is the base class for Error and Exception.

Is it necessary that each try block must be followed by a catch block?

It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. So whatever exceptions are likely to be thrown should be declared in the throws clause of the method.


What is finally block?

The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not. In other words, we can say that finally block is the block which is always executed. Finally block follows try or catch block. If you don't handle the exception, before terminating the program, JVM runs finally block, (if any). The finally block is mainly used to place the cleanup code such as closing a file or closing a connection.


Can finally block be used without a catch?

Yes, According to the definition of finally block, it must be followed by a try or catch block, therefore, we can use try block instead of catch.


Is there any case when finally will not be executed?

Finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).


Can an exception be rethrown?

Yes.

Can subclass overriding method declare an exception if parent class method doesn't throw an exception?

Yes but only unchecked exception not checked.



String Handling Interview Questions

What is String Pool?

String pool is the space reserved in the heap memory that can be used to store the strings. The main advantage of using the String pool is whenever we create a string literal; the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. Therefore, it saves the memory by avoiding the duplicacy.


What is the meaning of immutable regarding String?

The simple meaning of immutable is unmodifiable or unchangeable. In Java, String is immutable, i.e., once string object has been created, its value can't be changed.


Why are the objects immutable in java?

Because Java uses the concept of the string literal. Suppose there are five reference variables, all refer to one object "sachin". If one reference variable changes the value of the object, it will be affected by all the reference variables. That is why string objects are immutable in java.


How many ways can we create the string object?

1) String Literal

Java String literal is created by using double quotes. For Example:
  1. String s="welcome";  
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. String objects are stored in a special memory area known as the string constant pool For example:
  1. String s1="Welcome";  
  2. String s2="Welcome";//It doesn't create a new instance  

2) By new keyword

  1. String s=new String("Welcome");//creates two objects and one reference variable  
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the constant string pool. The variable s will refer to the object in a heap (non-pool).

How many objects will be created in the following code?

  1. String s1="Welcome";  
  2. String s2="Welcome";  
  3. String s3="Welcome";  
Only one object will be created using the above code because strings in Java are immutable.

Why java uses the concept of the string literal?

To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).

How many objects will be created in the following code?

  1. String s = new String("Welcome");  
Two objects, one in string constant pool and other in non-pool(heap).

More details.

How can we create an immutable class in Java?

We can create an immutable class by defining a final class having all of its members as final.

What is the purpose of toString() method in Java?

The toString() method returns the string representation of an object. If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object, etc. depending upon your implementation. By overriding the toString() method of the Object class, we can return the values of the object, so we don't need to write much code.


Why CharArray() is preferred over String to store the password?

String stays in the string pool until the garbage is collected. If we store the password into a string, it stays in the memory for a longer period, and anyone having the memory-dump can extract the password as clear text. On the other hand, Using CharArray allows us to set it to blank whenever we are done with the password. It avoids the security threat with the string by enabling us to control the memory.

Nested classes and Interface Interview Questions

What are the advantages of Java inner classes?

There are two types of advantages of Java inner classes.
  • Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of the outer class including private.
  • Nested classes are used to develop a more readable and maintainable code because it logically groups classes and interfaces in one place only.
  • Code Optimization: It requires less code to write.


What is a nested class?

The nested class can be defined as the class which is defined inside another class or interface. We use the nested class to logically group classes and interfaces in one place so that it can be more readable and maintainable. A nested class can access all the data members of the outer class including private data members and methods.


What are the disadvantages of using inner classes?

There are the following main disadvantages of using inner classes.
  • Inner classes increase the total number of classes used by the developer and therefore increases the workload of JVM since it has to perform some routine operations for those extra classes which result in slower performance.
  • IDEs provide less support to the inner classes as compare to the top level classes and therefore it annoys the developers while working with inner classes.


Is there any difference between nested classes and inner classes?

Yes, inner classes are non-static nested classes. In other words, we can say that inner classes are the part of nested classes.

Can we access the non-final local variable, inside the local inner class?

No, the local variable must be constant if you want to access it in the local inner class.
More details.

What are anonymous inner classes?

Anonymous inner classes are the classes that are automatically declared and instantiated within an expression. We cannot apply different access modifiers to them. Anonymous class cannot be static, and cannot define any static fields, method, or class. In other words, we can say that it a class without the name and can have only one object that is created by its definition.


What is the nested interface?

An Interface that is declared inside the interface or class is known as the nested interface. It is static by default. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The external interface or class must refer to the nested interface. It can't be accessed directly. The nested interface must be public if it is declared inside the interface but it can have any access modifier if declared within the class.

Can a class have an interface?

Yes, an interface can be defined within the class. It is called a nested interface.

More details.

Can an Interface have a class?

Yes, they are static implicitly.

More details.

Garbage Collection Interview Questions

What is Garbage Collection?

Garbage collection is a process of reclaiming the unused runtime objects. It is performed for memory management. In other words, we can say that It is the process of removing unused objects from the memory to free up space and make this space available for Java Virtual Machine. Due to garbage collection java gives 0 as output to a variable whose value is not set, i.e., the variable has been defined but not initialized. For this purpose, we were using free() function in the C language and delete() in C++. In Java, it is performed automatically. So, java provides better memory management.


What is gc()?

The gc() method is used to invoke the garbage collector for cleanup processing. This method is found in System and Runtime classes. This function explicitly makes the Java Virtual Machine free up the space occupied by the unused objects so that it can be utilized or reused.


How is garbage collection controlled?

Garbage collection is managed by JVM. It is performed when there is not enough space in the memory and memory is running low. We can externally call the System.gc() for the garbage collection. However, it depends upon the JVM whether to perform it or not.

How can an object be unreferenced?

There are many ways:
  • By nulling the reference
  • By assigning a reference to another
  • By anonymous object etc.

How can an object be unreferenced?

There are many ways:
  • By nulling the reference
  • By assigning a reference to another
  • By anonymous object etc.

What is the purpose of the finalize() method?

The finalize() method is invoked just before the object is garbage collected. It is used to perform cleanup processing. The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created an object without new, you can use the finalize method to perform cleanup processing (destroying remaining objects). The cleanup processing is the process to free up all the resources, network which was previously used and no longer needed. It is essential to remember that it is not a reserved keyword, finalize method is present in the object class hence it is available in every class as object class is the superclass of every class in java. Here, we must note that neither finalization nor garbage collection is guaranteed.

Can an unreferenced object be referenced again?

Yes,

What kind of thread is the Garbage collector thread?

Daemon thread.

What is the purpose of the Runtime class?

Java Runtime class is used to interact with a java runtime environment. Java Runtime class provides methods to execute a process, invoke GC, get total and free memory, etc. There is only one instance of java.lang.Runtime class is available for one java application. The Runtime.getRuntime() method returns the singleton instance of Runtime class.


File Handling Interview Questions

Give the hierarchy of InputStream and OutputStream classes.

Explain Carefully.

What do you understand by an IO stream?

The stream is a sequence of data that flows from source to destination. It is composed of bytes. In Java, three streams are created for us automatically.
  • System.out: standard output stream
  • System.in: standard input stream
  • System.err: standard error stream

What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented. The ByteStream classes are used to perform input-output of 8-bit bytes whereas the CharacterStream classes are used to perform the input/output for the 16-bit Unicode system. There are many classes in the ByteStream class hierarchy, but the most frequently used classes are FileInputStream and FileOutputStream. The most frequently used classes CharacterStream class hierarchy is FileReader and FileWriter.

What are the super most classes for all the streams?

All the stream classes can be divided into two types of classes that are ByteStream classes and CharacterStream Classes. The ByteStream classes are further divided into InputStream classes and OutputStream classes. CharacterStream classes are also divided into Reader classes and Writer classes. The SuperMost classes for all the InputStream classes is java.io.InputStream and for all the output stream classes is java.io.OutPutStream. Similarly, for all the reader classes, the super-most class is java.io.Reader, and for all the writer classes, it is java.io.Writer.

What are the FileInputStream and FileOutputStream?

Java FileOutputStream is an output stream used for writing data to a file. If you have some primitive values to write into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through the FileOutputStream class. However, for character-oriented data, it is preferred to use FileWriter than FileOutputStream.

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video, etc. You can also read character-stream data. However, for reading streams of characters, it is recommended to use FileReader class.


How to set the Permissions to a file in Java?

In Java, FilePermission class is used to alter the permissions set on a file. Java FilePermission class contains the permission related to a directory or file. All the permissions are related to the path. The path can be of two types:
  • D:\\IO\\-: It indicates that the permission is associated with all subdirectories and files recursively.
  • D:\\IO\\*: It indicates that the permission is associated with all directory and files within this directory excluding subdirectories.

What are FilterStreams?

FilterStream classes are used to add additional functionalities to the other stream classes. FilterStream classes act like an interface which read the data from a stream, filters it, and pass the filtered data to the caller. The FilterStream classes provide extra functionalities like adding line numbers to the destination file, etc.


What is an I/O filter?

An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

In Java, How many ways you can take input from the console?



    In Java, there are three ways by using which, we can take input from the console.

    • Using BufferedReader class: we can take input from the console by wrapping System.in into an InputStreamReader and passing it into the BufferedReader. It provides an efficient reading as the input gets buffered. 
    • Using Scanner class: The Java Scanner class breaks the input into tokens using a delimiter that is whitespace by default. It provides many methods to read and parse various primitive values. Java Scanner class is widely used to parse text for string and primitive types using a regular expression. Java Scanner class extends Object class and implements Iterator and Closeable interfaces. 
    • Using Console class: The Java Console class is used to get input from the console. It provides methods to read texts and passwords. If you read the password using the Console class, it will not be displayed to the user. The java.io.Console class is attached to the system console internally. The Console class is introduced since 1.5. 

    Constructor Interview Questions


    Serialization Interview Questions

    What is serialization?

    Serialization in Java is a mechanism of writing the state of an object into a byte stream. It is used primarily in Hibernate, RMI, JPA, EJB and JMS technologies. It is mainly used to travel object's state on the network (which is known as marshaling). Serializable interface is used to perform serialization. It is helpful when you require to save the state of a program to storage such as the file. At a later point of time, the content of this file can be restored using deserialization. It is also required to implement RMI(Remote Method Invocation). With the help of RMI, it is possible to invoke the method of a Java object on one machine to another machine.

    How can you make a class serializable in Java?

    A class can become serializable by implementing the Serializable interface.

    How can you avoid serialization in child class if the base class is implementing the Serializable interface?

    It is very tricky to prevent serialization of child class if the base class is intended to implement the Serializable interface. However, we cannot do it directly, but the serialization can be avoided by implementing the writeObject() or readObject() methods in the subclass and throw NotSerializableException from these methods.

    Can a Serialized object be transferred via network?

    Yes, we can transfer a serialized object via network because the serialized object is stored in the memory in the form of bytes and can be transmitted over the network. We can also write the serialized object to the disk or the database.

    What is Deserialization?

    Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation of serialization. An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.

    What is the transient keyword?

    If you define any data member as transient, it will not be serialized. By determining transient keyword, the value of variable need not persist when it is restored.
    More details.

    What is Externalizable?

    The Externalizable interface is used to write the state of an object into a byte stream in a compressed format. It is not a marker interface.

    Networking Interview Questions

     Complete this???

    Java Bean Interview  Questions

    What is a JavaBean?

    JavaBean is a reusable software component written in the Java programming language, designed to be manipulated visually by a software development environment, like JBuilder or VisualAge for Java. t. A JavaBean encapsulates many objects into one object so that we can access this object from multiple places. Moreover, it provides the easy maintenance. Consider the following example to create a JavaBean class.

    What is the purpose of using the Java bean?

    According to Java white paper, it is a reusable software component. A bean encapsulates many objects into one object so that we can access this object from multiple places. Moreover, it provides the easy maintenance.


    What do you understand by the bean persistent property?

    The persistence property of Java bean comes into the act when the properties, fields, and state information are saved to or retrieve from the storage.



    RMI Interview Questions
    Complete this???


    Multithreading and Concurrency Interview Questions

    Multithreading and Synchronization are considered as the typical chapter in java programming. In game development companies, multithreading related interview questions are asked mostly.

    What is multithreading?

    Multithreading is a process of executing multiple threads simultaneously. Multithreading is used to obtain the multitasking. It consumes less memory and gives the fast and efficient performance. Its main advantages are:
    • Threads share the same address space.
    • The thread is lightweight.
    • The cost of communication between the processes is low.

    What is the thread?

    A thread is a lightweight subprocess. It is a separate path of execution because each thread runs in a different stack frame. A process may contain multiple threads. Threads share the process resources, but still, they execute independently.

    Differentiate between process and thread?

    There are the following differences between the process and thread.
    • A Program in the execution is called the process whereas; A thread is a subset of the process
    • Processes are independent whereas threads are the subset of process.
    • Process have different address space in memory, while threads contain a shared address space.
    • Context switching can be faster between the threads as compared to context switching between the threads.
    • Inter-process communication is slower and expensive than inter-thread communication.
    • Any change in Parent process doesn't affect the child process whereas changes in parent thread can affect the child thread.

    What do you understand by inter-thread communication?

    • The process of communication between synchronized threads is termed as inter-thread communication.
    • Inter-thread communication is used to avoid thread polling in Java.
    • The thread is paused running in its critical section, and another thread is allowed to enter (or lock) in the same critical section to be executed.
    • It can be obtained by wait(), notify(), and notifyAll() methods.

    What is the purpose of wait() method in Java?

    The wait() method is provided by the Object class in Java. This method is used for inter-thread communication in Java. The java.lang.Object.wait() is used to pause the current thread, and wait until another thread does not call the notify() or notifyAll() method. Its syntax is given below.
    public final void wait()

    Why must wait() method be called from the synchronized block?

    We must call the wait method otherwise it will throw java.lang.IllegalMonitorStateException exception. Moreover, we need wait() method for inter-thread communication with notify() and notifyAll(). Therefore It must be present in the synchronized block for the proper and correct communication.

    What are the advantages of multithreading?

    Multithreading programming has the following advantages:
    • Multithreading allows an application/program to be always reactive for input, even already running with some background tasks
    • Multithreading allows the faster execution of tasks, as threads execute independently.
    • Multithreading provides better utilization of cache memory as threads share the common memory resources.
    • Multithreading reduces the number of the required server as one server can execute multiple threads at a time.

    What are the states in the lifecycle of a Thread?

    A thread can have one of the following states during its lifetime:
    1. New: In this state, a Thread class object is created using a new operator, but the thread is not alive. Thread doesn't start until we call the start() method.
    2. Runnable: In this state, the thread is ready to run after calling the start() method. However, the thread is not yet selected by the thread scheduler.
    3. Running: In this state, the thread scheduler picks the thread from the ready state, and the thread is running.
    4. Waiting/Blocked: In this state, a thread is not running but still alive, or it is waiting for the other thread to finish.
    5. Dead/Terminated: A thread is in terminated or dead state when the run() method exits.

    What is context switching?

    In Context switching the state of the process (or thread) is stored so that it can be restored and execution can be resumed from the same point later. Context switching enables the multiple processes to share the same CPU.

    Differentiate between the Thread class and Runnable interface for creating a Thread?

    The Thread can be created by using two ways.
    • By extending the Thread class
    • By implementing the Thread class
    However, the primary differences between both the ways are given below:
    • By extending the Thread class, we cannot extend any other class, as Java does not allow multiple inheritances while implementing the Runnable interface; we can also extend other base class(if required).
    • By extending the Thread class, each of thread creates the unique object and associates with it while implementing the Runnable interface; multiple threads share the same object
    • Thread class provides various inbuilt methods such as getPriority(), isAlive and many more while the Runnable interface provides a single method, i.e., run().

    What does join() method?

    The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task. Join method is overloaded in Thread class in the following ways.
    • public void join()throws InterruptedException
    • public void join(long milliseconds)throws InterruptedException
    More details.

    Describe the purpose and working of sleep() method.

    The sleep() method in java is used to block a thread for a particular time, which means it pause the execution of a thread for a specific time. There are two methods of doing so.
    Syntax:
    • public static void sleep(long milliseconds)throws InterruptedException
    • public static void sleep(long milliseconds, int nanos)throws InterruptedException
    Working of sleep() method
    When we call the sleep() method, it pauses the execution of the current thread for the given time and gives priority to another thread(if available). Moreover, when the waiting time completed then again previous thread changes its state from waiting to runnable and comes in running state, and the whole process works so on till the execution doesn't complete.

    Is it possible to start a thread twice?

    No, we cannot restart the thread, as once a thread started and executed, it goes to the Dead state. Therefore, if we try to start a thread twice, it will give a runtimeException "java.lang.IllegalThreadStateException".

    Can we call the run() method instead of start()?

    Yes, calling run() method directly is valid, but it will not work as a thread instead it will work as a normal object. There will not be context-switching between the threads. When we call the start() method, it internally calls the run() method, which creates a new stack for a thread while directly calling the run() will not create a new stack.
    More details.

    What about the daemon threads?

    The daemon threads are the low priority threads that provide the background support and services to the user threads. Daemon thread gets automatically terminated by the JVM if the program remains with the daemon thread only, and all other user threads are ended/died. There are two methods for daemon thread available in the Thread class:
    • public void setDaemon(boolean status): It used to mark the thread daemon thread or a user thread.
    • public boolean isDaemon(): It checks the thread is daemon or not.
    More details.

    Can we make the user thread as daemon thread if the thread is started?

    No, if you do so, it will throw IllegalThreadStateException. Therefore, we can only create a daemon thread before starting the thread.

    What is shutdown hook?

    The shutdown hook is a thread that is invoked implicitly before JVM shuts down. So we can use it to perform clean up the resource or save the state when JVM shuts down normally or abruptly. We can add shutdown hook by using the following method:
    1. public void addShutdownHook(Thread hook){}    
    2. Runtime r=Runtime.getRuntime();  
    3. r.addShutdownHook(new MyThread());  
    Some important points about shutdown hooks are :
    • Shutdown hooks initialized but can only be started when JVM shutdown occurred.
    • Shutdown hooks are more reliable than the finalizer() because there are very fewer chances that shutdown hooks not run.
    • The shutdown hook can be stopped by calling the halt(int) method of Runtime class.
    More details.

    When should we interrupt a thread?


    We should interrupt a thread when we want to break out the sleep or wait state of a thread. We can interrupt a thread by calling the interrupt() throwing the InterruptedException.

    What is the synchronization?

    Synchronization is the capability to control the access of multiple threads to any shared resource. It is used:

    1. To prevent thread interference.
    2. To prevent consistency problem.
    When the multiple threads try to do the same task, there is a possibility of an erroneous result, hence to remove this issue, Java uses the process of synchronization which allows only one thread to be executed at a time. Synchronization can be achieved in three ways:
    • by the synchronized method
    • by synchronized block
    • by static synchronization

    What is the purpose of the Synchronized block?

    The Synchronized block can be used to perform synchronization on any specific resource of the method. Only one thread at a time can execute on a particular resource, and all other threads which attempt to enter the synchronized block are blocked.
    • Synchronized block is used to lock an object for any shared resource.
    • The scope of the synchronized block is limited to the block on which, it is applied. Its scope is smaller than a method.

    Can Java object be locked down for exclusive use by a given thread?

    Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.

    What is static synchronization?

    If you make any static method as synchronized, the lock will be on the class not on the object. If we use the synchronized keyword before a method so it will lock the object (one thread can access an object at a time) but if we use static synchronized so it will lock a class (one thread can access a class at a time). More details.

    What is the difference between notify() and notifyAll()?

    The notify() is used to unblock one waiting thread whereas notifyAll() method is used to unblock all the threads in waiting state.

    What is the deadlock?

    Deadlock is a situation in which every thread is waiting for a resource which is held by some other waiting thread. In this situation, Neither of the thread executes nor it gets the chance to be executed. Instead, there exists a universal waiting state among all the threads. Deadlock is a very complicated situation which can break our code at runtime.
    More details.

    What is Thread Scheduler in java?

    In Java, when we create the threads, they are supervised with the help of a Thread Scheduler, which is the part of JVM. Thread scheduler is only responsible for deciding which thread should be executed. Thread scheduler uses two mechanisms for scheduling the threads: Preemptive and Time Slicing.
    Java thread scheduler also works for deciding the following for a thread:
    • It selects the priority of the thread.
    • It determines the waiting time for a thread
    • It checks the Nature of thread

    How is the safety of a thread achieved?

    If a method or class object can be used by multiple threads at a time without any race condition, then the class is thread-safe. Thread safety is used to make a program safe to use in multithreaded programming. It can be achieved by the following ways:
    • Synchronization
    • Using Volatile keyword
    • Using a lock based mechanism
    • Use of atomic wrapper classes

    What is race-condition?

    A Race condition is a problem which occurs in the multithreaded programming when various threads execute simultaneously accessing a shared resource at the same time. The proper use of synchronization can avoid the Race condition.

    What is the volatile keyword in java?

    Volatile keyword is used in multithreaded programming to achieve the thread safety, as a change in one volatile variable is visible to all other threads so one variable can be used by one thread at a time.

    What do you understand by thread pool?

    • Java Thread pool represents a group of worker threads, which are waiting for the task to be allocated.
    • Threads in the thread pool are supervised by the service provider which pulls one thread from the pool and assign a job to it.
    • After completion of the given task, thread again came to the thread pool.
    • The size of the thread pool depends on the total number of threads kept at reserve for execution.
    The advantages of the thread pool are :
    • Using a thread pool, performance can be enhanced.
    • Using a thread pool, better system stability can occur.


    Collections Interview Questions

    What is the Collection framework in Java?

    Collection Framework is a combination of classes and interface, which is used to store and manipulate the data in the form of objects. It provides various classes such as ArrayList, Vector, Stack, and HashSet, etc. and interfaces such as List, Queue, Set, etc. for this purpose.

    What are the main differences between array and collection?

    Array and Collection are somewhat similar regarding storing the references of objects and manipulating the data, but they differ in many ways. The main differences between the array and Collection are defined below:
    • Arrays are always of fixed size, i.e., a user can not increase or decrease the length of the array according to their requirement or at runtime, but In Collection, size can be changed dynamically as per need.
    • Arrays can only store homogeneous or similar type objects, but in Collection, heterogeneous objects can be stored.
    • Arrays cannot provide the ?ready-made? methods for user requirements as sorting, searching, etc. but Collection includes readymade methods to use.

    Explain various interfaces used in Collection framework?

    Collection framework implements various interfaces, Collection interface and Map interface (java.util.Map) are the mainly used interfaces of Java Collection Framework. List of interfaces of Collection Framework is given below:
    1. Collection interface: Collection (java.util.Collection) is the primary interface, and every collection must implement this interface.
    Syntax:
    1. public interface Collection<E>extends Iterable  
    Where <E> represents that this interface is of Generic type
    2. List interface: List interface extends the Collection interface, and it is an ordered collection of objects. It contains duplicate elements. It also allows random access of elements.
    Syntax:
    1. public interface List<E> extends Collection<E>  
    3. Set interface: Set (java.util.Set) interface is a collection which cannot contain duplicate elements. It can only include inherited methods of Collection interface
    Syntax:
    1. public interface Set<E> extends Collection<E>  
    Queue interface: Queue (java.util.Queue) interface defines queue data structure, which stores the elements in the form FIFO (first in first out).
    Syntax:
    1. public interface Queue<E> extends Collection<E>  
    4. Dequeue interface: it is a double-ended-queue. It allows the insertion and removal of elements from both ends. It implants the properties of both Stack and queue so it can perform LIFO (Last in first out) stack and FIFO (first in first out) queue, operations.
    Syntax:
    1. public interface Dequeue<E> extends Queue<E>  
    5. Map interface: A Map (java.util.Map) represents a key, value pair storage of elements. Map interface does not implement the Collection interface. It can only contain a unique key but can have duplicate elements. There are two interfaces which implement Map in java that are Map interface and Sorted Map.

    What is the difference between List and Set?

    The List and Set both extend the collection interface. However, there are some differences between the both which are listed below.
    • The List can contain duplicate elements whereas Set includes unique items.
    • The List is an ordered collection which maintains the insertion order whereas Set is an unordered collection which does not preserve the insertion order.
    • The List interface contains a single legacy class which is Vector class whereas Set interface does not have any legacy class.
    • The List interface can allow n number of null values whereas Set interface only allows a single null value.

    What is the difference between HashSet and TreeSet?

    The HashSet and TreeSet, both classes, implement Set interface. The differences between the both are listed below.
    • HashSet maintains no order whereas TreeSet maintains ascending order.
    • HashSet impended by hash table whereas TreeSet implemented by a Tree structure.
    • HashSet performs faster than TreeSet.
    • HashSet is backed by HashMap whereas TreeSet is backed by TreeMap.

    What is the difference between Set and Map?

    The differences between the Set and Map are given below.
    • Set contains values only whereas Map contains key and values both.
    • Set contains unique values whereas Map can contain unique Keys with duplicate values.
    • Set holds a single number of null value whereas Map can include a single null key with n number of null values.

    What is the difference between HashSet and HashMap?

    The differences between the HashSet and HashMap are listed below.
    • HashSet contains only values whereas HashMap includes the entry (key, value). HashSet can be iterated, but HashMap needs to convert into Set to be iterated.
    • HashSet implements Set interface whereas HashMap implements the Map interface
    • HashSet cannot have any duplicate value whereas HashMap can contain duplicate values with unique keys.
    • HashSet contains the only single number of null value whereas HashMap can hold a single null key with n number of null values.

    What is the difference between HashMap and TreeMap?

    The differences between the HashMap and TreeMap are given below.
    • HashMap maintains no order, but TreeMap maintains ascending order.
    • HashMap is implemented by hash table whereas TreeMap is implemented by a Tree structure.
    • HashMap can be sorted by Key or value whereas TreeMap can be sorted by Key.
    • HashMap may contain a null key with multiple null values whereas TreeMap cannot hold a null key but can have multiple null values.

    What is the difference between Collection and Collections?

    The differences between the Collection and Collections are given below.
    • The Collection is an interface whereas Collections is a class.
    • The Collection interface provides the standard functionality of data structure to List, Set, and Queue. However, Collections class is to sort and synchronize the collection elements.
    • The Collection interface provides the methods that can be used for data structure whereas Collections class provides the static methods which can be used for various operation on a collection.

    What is the advantage of Properties file?

    If you change the value in the properties file, you don't need to recompile the java class. So, it makes the application easy to manage. It is used to store information which is to be changed frequently.

    What does the hashCode() method?

    The hashCode() method returns a hash code value (an integer number).
    The hashCode() method returns the same integer number if two keys (by calling equals() method) are identical.
    However, it is possible that two hash code numbers can have different or the same keys.
    If two objects do not produce an equal result by using the equals() method, then the hashcode() method will provide the different integer result for both the objects.

    Why we override equals() method?

    The equals method is used to check whether two objects are the same or not. It needs to be overridden if we want to check the objects based on the property.
    For example, Employee is a class that has 3 data members: id, name, and salary. However, we want to check the equality of employee object by the salary. Then, we need to override the equals() method.

    How to synchronize List, Set and Map elements?

    Yes, Collections class provides methods to make List, Set or Map elements as synchronized:
    public static List synchronizedList(List l){}
    public static Set synchronizedSet(Set s){}
    public static SortedSet synchronizedSortedSet(SortedSet s){}
    public static Map synchronizedMap(Map m){}
    public static SortedMap synchronizedSortedMap(SortedMap m){}



    What is the advantage of the generic collection?

    There are three main advantages of using the generic collection.
    • If we use the generic class, we don't need typecasting.
    • It is type-safe and checked at compile time.
    • Generic confirms the stability of the code by making it bug detectable at compile time.

    What is the Dictionary class?

    The Dictionary class provides the capability to store key-value pairs.

    What is the default size of load factor in hashing based collection?

    The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.

    What do you understand by fail-fast?

    The Iterator in java which immediately throws ConcurrentmodificationException, if any structural modification occurs in, is called as a Fail-fast iterator. Fail-fats iterator does not require any extra space in memory.

    What is the difference between the length of an Array and size of ArrayList?

    The length of an array can be obtained using the property of length whereas ArrayList does not support length property, but we can use size() method to get the number of objects in the list.
    Finding the length of the array
    1. Int [] array = new int[4];  
    2. System.out.println("The size of the array is " + array.length);  
    3.           
    Finding the size of the ArrayList
    1. ArrayList<String> list=new ArrayList<String>();    
    2. list.add("ankit");    
    3. list.add("nippun");  
    4. System.out.println(list.size()); 


    How to convert ArrayList to Array and Array to ArrayList?

    We can convert an Array to ArrayList by using the asList() method of Arrays class. asList() method is the static method of Arrays class and accepts the List object. Consider the following syntax:
    1. Arrays.asList(item)  
    We can convert an ArrayList to Array using toArray() method of the ArrayList class. Consider the following syntax to convert the ArrayList to the List object.
    1. List_object.toArray(new String[List_object.size()])  

    How to make Java ArrayList Read-Only?

    We can obtain java ArrayList Read-only by calling the Collections.unmodifiableCollection() method. When we define an ArrayList as Read-only then we cannot perform any modification in the collection through  add(), remove() or set() method.

    How to remove duplicates from ArrayList?

    There are two ways to remove duplicates from the ArrayList.
    • Using HashSet: By using HashSet we can remove the duplicate element from the ArrayList, but it will not then preserve the insertion order.
    • Using LinkedHashSet: We can also maintain the insertion order by using LinkedHashSet instead of HashSet.
    The Process to remove duplicate elements from ArrayList using the LinkedHashSet:
    • Copy all the elements of ArrayList to LinkedHashSet.
    • Empty the ArrayList using clear() method, which will remove all the elements from the list.
    • Now copy all the elements of LinkedHashset to ArrayList.

    How to reverse ArrayList?

    To reverse an ArrayList, we can use reverse() method of Collections class.

     How to sort ArrayList in descending order?

    To sort the ArrayList in descending order, we can use the reverseOrder method of Collections class.

    How to synchronize ArrayList?

    We can synchronize ArrayList in two ways.
    • Using Collections.synchronizedList() method
    • Using CopyOnWriteArrayList<T>

    When to use ArrayList and LinkedList?

    LinkedLists are better to use for the update operations whereas ArrayLists are better to use for the search operations.
















    No comments:

    Post a Comment