Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

Does order of specifiers matter in Java? Will static public void work for main() method?

Answer»

Order of specifiers doesn’t MATTER in Java. The static public VOID will work for sure and the program WOULD COMPILE and run correctly.

2.

Can the main method be declared final?

Answer»

Yes, we can declare the main method as FINAL LIKE:

public static final void main(String[] ARGS)
3.

Why do we call System.gc() in Java

Answer»

The garbage collector is run using the System.gc() METHOD in Java. The use of this method is an indicator to the JVM to recycle the unused objects so that the memory can be freed and available for quick reuse as required. The System.gc() method does not return any values.

A program that DEMONSTRATES this method is given as follows:

public class Demo {    public static void main(String[] args) throws InterruptedException    {        Demo obj = new Demo();        obj = NULL;        System.gc();    }    @OVERRIDE    protected void finalize() throws Throwable    {        System.out.println("The garbage collector is called...");        System.out.println("The object that is garbage collected is: " + this);    } }

The output of the above program is as follows:

The garbage collector is called... The object that is garbage collected is: Demo@7978f9b4
4.

Best practices related to Java Collections Framework?

Answer»

Collections in Java is BASICALLY a framework that allows the storage and manipulation of a group of objects by providing an architecture. All the possible operations in Java such as searching, sorting, deletion, insertion etc. can be performed using the Java Collections.

Some of the best practices related to the Collections Framework in Java are given as follows:

  • Using Arrays and Collections utility classes

The Arrays and Collections utility classes provided by the Java Collections Framework should be used as required as they PROVIDE many useful methods to search, sort and MODIFY ELEMENTS in a collection

  • Do not use the classic for loop

Instead of using a classic for loop to iterate a list collection, use an iterator. This is because if the for loop variable is altered inside the loop, it can lead to bugs.

  • Choosing the right collections

Before using collections, the right collection needs to be chosen according to the problem that needs to be solved.

  • Using the Stream API on collections

There is a stream method in every collection in Java 8 that returns a stream of elements. This MEANS that the aggregate functions can be easily performed using the Stream API.

  • Prefer isEmpty() over size()

The isEmpty() method should be preferred over the size() method to check the emptiness of a collection. Even though there is performance difference between these two methods, this is done to enhance the readability of this code.

  • Do not return null in a method that returns a collection

If a method returns a collection, then it should not return null if there is no element in the collection. Instead, it should return an empty collection.

  • Specify initial capacity of a collection if possible

The initial capacity of a collection is always specified by an overloaded constructor that is contained in almost all concrete collection classes.

5.

What is a Static Nested Class in Java?

Answer»

A STATIC nested class is a nested class DECLARED as static. A nested class can’t ACCESS the data members and METHODS of the outer class.

6.

C++ supports Pointers, while Java does not. Why?

Answer»

Pointers are considered unsafe in Java, so it does not SUPPORT it. The LACK of pointers is to STOP Java PROGRAMS from referencing MEMORY locations illegally.

7.

Why do we use variable length arguments in Java?

Answer»

The variable length arguments come into picture when you do not initially know the number of arguments PASSED to the method.

The variable length arguments can be zero or more. An example is shown below:

public class Demo {  public static void Varargs(String... str)  {    System.out.println("Arguments... ");    for (String s : str)      System.out.println(s);    System.out.println("Count = " + str.length );  }  public static void main(String ARGS[])  {    Varargs("ARG1", "arg2");  } }

The above program displays the following output:

Arguments... arg1 arg2 Count = 2
8.

What are the types of Base64 encoding in Java?

Answer»

The following are the TYPES of Base64 ENCODING:

  • Simple: The OUTPUT is mapped to a set of characters lying in A-Za-z0-9+/.
  • URL: The output is mapped to set of characters lying in A-Za-z0-9+_.
  • MIME: The output is mapped to MIME friendly FORMAT. It is represented in lines of no more than 76 characters each, and uses a carriage return '\r' followed by a linefeed '\n' as the line separator.
9.

What enhancements Java 9 brought to Process API?

Answer»

The Process API now provide more INFORMATION like:

  • Process's native process ID,
  • Accumulated CPU TIME,
  • PARENT process
  • Method to destroy a process
  • Process’s Descendants, ETC.
10.

Constructor vs Method in Java

Answer»

A method has a return TYPE UNLIKE constructor. Constructor is invoked implicitly. Whereas method is invoked explicitly.

The NAME of the constructor is the same as the class name. HOWEVER, the name of the method may or may not be same as the name of the class.

11.

Which class is used in Java to serialize an object?

Answer»

To SERIALIZE an OBJECT, USE the ObjectOutputStream CLASS.

12.

Why to use Argument Index in Java?

Answer»

If you want to reorder OUTPUT in Java, then use Argument Index.

Let’s say the output is:

abc def ghi jkl mno

And you want to reorder and display it as:

ghi jkl mno abc def

For this, use the Argument Index as shown in the FOLLOWING example:

public class DEMO {  public static void main(String[] args) {       System.out.printf("Initial Output = %s %s %s %s %s\n", "abc", "def", "ghi", "jkl", "mno");          System.out.printf("Update output = %3$s %4$s %5$s %1$s %2$s\n", "abc", "def", "ghi", "jkl", "mno" );     } }

The above example displays that we have reordered the output:

Initial Output = abc def ghi jkl mno Update output = ghi jkl mno abc def
13.

What are the restrictions applied to Java static methods?

Answer»

The following are the RESTRICTIONS applied to STATIC METHODS in Java:

  • Static method can access only static TYPE data.
  • These methods cannot invoke non-static method directly.
  • The ‘this’ and ‘super’ cannot be used in static context.
  • You can’t override static methods in a subclass
14.

What happens when an exception is thrown from the top of the stack in Java?

Answer»

When an EXCEPTION is thrown from the TOP of the stack, exception propagation OCCURS. Here are some of the points when the exception is not caught:

  • The exception drops down the call stack of the PRECEDING METHOD.
  • If it is still not caught there itself, it further goes down to the preceding method.
  • The above goes till the method reaches the bottom of the call stack
  • This can also go on till it is caught somewhere in between.
15.

Which collection classes are thread-safe in Java

Answer»

The collection classes that are thread safe in Java are Stack, Vector, Properties, Hashtable ETC. Details about some of these collection classes are given as follows:

Stack class in Java

The Stack class in Java implements the stack data structure that is based on the principle of LIFO. So, the stack class can provide many operations such as push, pop, peek, search, empty etc.

A program that demonstrates the Stack class is given as follows:

import java.io.*; import java.util.*; public class Demo {        public STATIC void main (String[] ARGS)    {        Stack<Integer> stack = new Stack<Integer>();        stack.push(4);        stack.push(1);        stack.push(9);        Integer num1 = (Integer) stack.pop();        System.out.println("The element popped is: " + num1);        Integer num2 = (Integer) stack.peek();        System.out.println("Element on stack TOP is: " + num2);    } }

The output of the above program is as follows:

The element popped is: 9 Element on stack top is: 1

Vector class in Java

An array of OBJECTS that grows as required is implemented by the Vector class in Java. A program that demonstrates the Vector class is given as follows:

import java.util.*; public class Demo {    public static void main(String[] arg)    {        Vector vector = new Vector();        vector.add(9);        vector.add(3);        vector.add("Apple");        vector.add(1);        vector.add("Mango");        System.out.println("The vector is: " + vector);        vector.remove(1);        System.out.println("The vector after element at index 1 is removed is: " + vector);    } }

The output of the above program is as follows:

The vector is: [9, 3, Apple, 1, Mango] The vector after element at index 1 is removed is: [9, Apple, 1, Mango]
16.

Covariant return type in Java

Answer»

Covariant return TYPES REFER to the return type of the overriding method. It is possible to have DIFFERENT return types for overriding methods in the child class since Java 5. HOWEVER, the return type of the child class should be a subtype of the return type of the parent class.

A program that demonstrates covariant return type in Java is given as follows:

class C1 {      C1 ret()    {        return this;    }   }   public class C2 extends C1 {      C2 ret()    {        return this;    }      void DISPLAY()    {        System.out.println("This is the covariant return type");    }      public static void main(String args[])    {          new C2().ret().display();      }   }  

The output of the above program is as follows:

This is the covariant return type

The above program demonstrates covariant return type as the return type of the class C1 ret() method is C1 while the return type of the class C2 ret() method is C2 and it is method overriding while both methods have different return types.

17.

Create Immutable class in Java

Answer»

An immutable class in Java is one that cannot change its state after its construction. Some of the requirements to create an immutable class in Java are GIVEN as FOLLOWS:

  1. The class should be final so that other classes can’t extend it.
  2. All the fields of the class should be final so that they are only initialized one time inside the constructor.
  3. Setter methods should not be exposed.
  4. A new instance of the class should be returned if any methods that MODIFY the state of the class are exposed.
  5. If there Is a mutable object inside the constructor, only a clone copy of the passed argument should be USED.

An example that demonstrates the creation of an immutable class in Java is given as follows:

public final class Employee {    final int empNum;    final String name;    final int salary;    public Employee(int empNum, String name, int salary)    {        this.empNum = empNum;        this.name = name;        this.salary = salary;    }    public int empNumReturn()    {        return empNum;    }    public String nameReturn()    {        return name;    }    public int salaryReturn()    {        return salary;    } }

The class given above is a basic immutable class. This class does not contain any mutable object or any setter methods. This type of a basic class is normally used for caching purposes.

18.

Are constructors inherited in Java?

Answer»

The CONSTRUCTORS aren’t INHERITED in JAVA.

19.

Sort a HashMap according to values in Java

Answer»

A method is created to sort the HashMap according to VALUE. The HashMap contains the names of 5 students as the key and their average marks as the value. Therefore, the HashMap is sorted according to the marks obtained by the students.

A program that demonstrates this is given as follows:

import java.util.*; import java.lang.*; public class Example {    public static HashMap<String, Integer> sortHashMapByValue(HashMap<String, Integer> studentDetails)    {        List<Map.Entry<String, Integer> > list =               new LinkedList<Map.Entry<String, Integer> >(studentDetails.entrySet());        Collections.sort(list, new Comparator<Map.Entry<String, Integer> >()        {            public int compare(Map.Entry<String, Integer> val1,                                 Map.Entry<String, Integer> val2)            {                return (val1.getValue()).COMPARETO(val2.getValue());            }        });        HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>();        for (Map.Entry<String, Integer> i : list)        {            temp.put(i.getKey(), i.getValue());        }        return temp;    }    public static VOID main(String[] args)    {        HashMap<String, Integer> studentDetails = new HashMap<String, Integer>();        studentDetails.put("AMY", 56);        studentDetails.put("John", 99);        studentDetails.put("Peter", 25);        studentDetails.put("Susan", 85);        studentDetails.put("Harry", 68);        System.out.println("Original HashMap");        for (Map.Entry<String, Integer> i : studentDetails.entrySet())        {            System.out.println("Key = " + i.getKey() +                            ", Value = " + i.getValue());        }        Map<String, Integer> sortedStudentDetails = sortHashMapByValue(studentDetails);        System.out.println("\nSorted HashMap");        for (Map.Entry<String, Integer> i : sortedStudentDetails.entrySet())        {            System.out.println("Key = " + i.getKey() +                            ", Value = " + i.getValue());        }    } }

The output of the above program is as follows:

Original HashMap Key = Harry, Value = 68 Key = Susan, Value = 85 Key = John, Value = 99 Key = Peter, Value = 25 Key = Amy, Value = 56 Sorted HashMap Key = Peter, Value = 25 Key = Amy, Value = 56 Key = Harry, Value = 68 Key = Susan, Value = 85 Key = John, Value = 99
20.

Static vs Dynamic Binding in Java

Answer»

Static binding can be resolved at the compile time by the COMPILER. All the static, final and private method binding is DONE at compile time. Another word for static binding is EARLY binding.

An example of static binding is given as follows:

public class Demo {    public static class ANIMAL    {        static VOID display()        {            System.out.println("This is an Animal");        }    }    public static class Mammal extends Animal    {        static void display()        {            System.out.println("This is a Mammal");        }    }    public static void main(String[] args)    {        Animal obj1 = new Animal();        Mammal obj2 = new Mammal();        obj1.display();        obj2.display();    } }

The output of the above program is as follows:

This is an Animal This is a Mammal

In dynamic binding, the type of the object is determined at run time. One of the examples of dynamic binding is overriding.

An example of dynamic binding is given as follows:

public class Demo {    public static class Animal    {        void display()        {            System.out.println("This is an Animal");        }    }    public static class Mammal extends Animal    {        @Override        void display()        {            System.out.println("This is a Mammal");        }    }    public static void main(String[] args)    {        Animal obj1 = new Animal();        Animal obj2 = new Mammal();        obj1.display();        obj2.display();    } }

The output of the above program is as follows:

This is an Animal This is a Mammal
21.

Set permission to a file in Java

Answer»

File permissions are set on the file when the operations PERMISSIBLE for the file need to be restricted by the user.

The permissible permissions for a file are given below:

  1. Readable - This permission TESTS if the application can read the file that is denoted by the abstract path name.
  2. Writable - This permission tests if the application can change the file that is denoted by the abstract path name.
  3. Executable - This permission tests if the application can execute the file that is denoted by the abstract path name.

The methods that can be used to change the permissions of a file are setExecutable, setReadable and setWritable.

A program that demonstrates the permissions of a file is given as follows:

IMPORT java.io.*; public class Demo {    public static void main(String[] args)    {        File f = NEW File("C:\\Users\\Aaron\\Desktop\\text.txt");        boolean exists = f.exists();        if(exists == true)        {            f.setExecutable(true);            f.setReadable(true);            f.setWritable(false);            System.out.println("The File permissions are now changed.");            System.out.println("Executable: " + f.canExecute());            System.out.println("Readable: " + f.canRead());            System.out.println("Writable: "+ f.canWrite());        }        else        {            System.out.println("File not found.");        }    } }

The output of the above program is as follows:

The File permissions are now changed. Executable: true Readable: true Writable: false
22.

What is Spliterator in Java SE 8?

Answer»

Spliterator is used for traversing the elements of a Collection, GENERATOR function, IO channel etc. It provides excellent support for parallel traversal as well as sequential traversal and hence is INCLUDED in the JDK 8.

The Spliterator is quite useful EVEN if parallel traversal is not REQUIRED as it combines the hasNext and next operations into a single method.

A program that demonstrates a Spliterator in Java is given as follows:

import java.util.ArrayList; import java.util.Spliterator; import java.util.stream.Stream; public class SpliteratorDemo   {    public static void main(String[] args)      {        ArrayList<Integer> arrList = new ArrayList<>();        arrList.add(7);        arrList.add(2);        arrList.add(1);        arrList.add(9);        arrList.add(4);        Stream<Integer> s1 = arrList.stream();        Spliterator<Integer> split = s1.spliterator();        System.out.println("The estimated size is: " + split.estimateSize());        System.out.println("The arraylist contents are:");        split.forEachRemaining((n) -> System.out.println(n));    } }

The output of the above program is as follows:

The estimated size is: 5 The arraylist contents are: 7 2 1 9 4
23.

What is blank or uninitialized final variable in Java

Answer»

A final variable in Java is a special type of variable that can only be assigned a value one TIME, either at declaration time or at some other time.

A final variable that is not assigned a value at declaration time is known as a blank or uninitialized final variable. In other words, this variable is not initialized at its declaration time. An EXAMPLE is given as follows:

final int val;    // This is a blank final variable val = 6;

A program that demonstrates a blank or uninitialized final variable in Java is given as follows:

class Demo {    final int NUM;    Demo(int NUM1)    {        num = num1;    } } public class Main {    public static void main(String args[])    {        Demo obj = new Demo(87);        System.out.println("Value of num is: " + obj.num);    } }

The OUTPUT of the above program is as follows: 

Value of num is: 87
24.

Restrict Inheritance for a class in Java

Answer»

Inheritance can be restricted for a class in Java using the KEYWORD final. In other WORDS, if a class is declared as final, then no other class can be extended from it. This is quite useful while creating an immutable class  

An example of this is given as follows:

final class C1 {     // methods and fields } class C2 extends C1 {     // Not possible }

An error is generated if the class C2 tries to EXTEND the class C1 as it is a final class and so cannot be inherited.

25.

Can this keyword be used to refer static members?

Answer»

This keyword cannot be used to refer to the static members of the CLASS. The reason is the “this” keyword points to the current object of the class and the static member does not need any object to be called.

The static members of the class can be accessed directly as no object is required. A program that demonstrates this is as follows:

public class Demo {    static INT a = 45;    static int b;    static void FUNC()    {        System.out.println("Static function");        b = a + 5;    }    public static void MAIN(String[] args)    {       func();       System.out.println("VALUE of a is: " + a);       System.out.println("Value of b is: " + b);      } }

The output of the above program is as follows:

Static function Value of a is: 45 Value of b is: 50
26.

Get the name of the Enum constant in Java

Answer»

The NAME of the enum constant is RETURNED by the method java.lang.Enum.name(). The method returns the name exactly as it was declared in the enum declaration.

A program that DEMONSTRATES the java.lang.Enum.name() method is given as follows:

enum Shape {    CIRCLE, TRIANGLE, SQUARE, RECTANGLE; } public class Demo {    public static void MAIN(String[] args)    {        Shape s = Shape.SQUARE;        System.out.print("The name of enum constant is: " + s.name());    } }

The output of the above program is as follows:

The name of enum constant is: SQUARE
27.

What were the drawbacks of Date/ Time API in Java 7 that lead to some enhancements to the API in Java 8?

Answer»

The following were the drawbacks:

  • java.util.DATE is not thread safe.
  • No UNIFORMITY, since the default Date starts from 1900, month starts from 1, and day starts from 0.

The above drawbacks were fixed in Java 8 like INTRODUCTION of utility methods for date operations.

28.

Check if a character is letter or number in Java

Answer»

The method isLetterOrDigit() can be used to check if a character is a letter or a number in Java. If the character is a letter or a number then the method returns true, OTHERWISE it returns false.

A program that demonstrates this is given as follows:

public class MAINCLASS {  public STATIC void main(String[] args)  {    char CHARACTER1 = 'A';    char character2 = '*';    if (Character.isLetterOrDigit(character1))    {      System.out.println(character1 + " is a character or DIGIT");    }    else    {      System.out.println(character1 + " is not a character or digit");    }    if (Character.isLetterOrDigit(character2))    {      System.out.println(character2 + " is a character or digit");    }    else    {      System.out.println(character2 + " is not a character or digit");    }  } }

The output of the above program is as follows:

A is a character or digit * is not a character or digit
29.

Get current date and time in Java

Answer»

The current date and time can be obtained using many METHODS in Java. One of these is using the LocalDateTime.now() method. The instance of the LocalDateTime class is RETURNED by this method which can then be printed.

A program that demonstrates this is given as FOLLOWS:

import java.time.format.DateTimeFormatter;   import java.time.LocalDateTime;    PUBLIC class Demo {      public static void MAIN(String[] args)  {      DateTimeFormatter datetime = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");     LocalDateTime curDateTime = LocalDateTime.now();     System.out.println("The current date time is: " + datetime.format(curDateTime));    }    }

The output of the above program is as follows:

The current date time is: 2018/12/15 12:18:54
30.

Why overflow of Datatypes occurs in Java?

Answer»

Overflow OCCURS when the VALUE is more than the maximum value of the specified datatype. LET’s say the datatype is LONG. If the value SET is more than the Long.MAX_VALUE, then overflow occurs.

31.

A class can be made final. Can we make a Constructor final in Java?

Answer»

A class is MADE FINAL in JAVA so that it cannot be extended. But we cannot make a CONSTRUCTOR final.

32.

Compare two integer arrays in Java

Answer»

Two integer arrays in JAVA are said to be equal if they have the same number of elements and all the CORRESPONDING elements in the arrays are ALSO the same. So, the two arrays can be COMPARED in Java by using the Arrays.equals() method.

A program that demonstrates this method is given as follows:

import java.util.Arrays; public class DEMO {    public static void main (String[] args)      {        int arr1[] = {5, 8, 2, 9, 7, 1, 6, 3, 4};        int arr2[] = {5, 8, 2, 9, 7, 1, 6, 3, 4};        int i;        System.out.print("The array 1 is: ");        for (i=0; i<9; i++)          System.out.print(arr1[i] + " ");        System.out.print("\nThe array 2 is: ");        for (i=0; i<9; i++)          System.out.print(arr2[i] + " ");        if (Arrays.equals(arr1, arr2))            System.out.println("\nThe above two arrays are the same");        else            System.out.println("\nThe above two arrays are not the same");    } }

The output of the above program is as follows:

The array 1 is: 5 8 2 9 7 1 6 3 4 The array 2 is: 5 8 2 9 7 1 6 3 4 The above two arrays are the same
33.

Can an Interface extend another Interface?

Answer»

An interface in JAVA is a collection of abstract methods. This interface is IMPLEMENTED by a class that abstract methods of the interface.

An interface can extend another interface using the extends keyword. In this way, the methods of the parent interface are inherited by the child interface.

An example of an interface extending another is given as follows:

public interface Department {   public void name(); } public interface Finance extends Department {   public void expenses();   public void quarterlyReports();   public void income(); } public interface Marketing extends Department {   public void onlineBudget();   public void offlineBudget(); }

The class that IMPLEMENTS the Finance interface NEEDS to implement 4 methods as there are 3 methods in Finance and it inherits 1 method from Department. Similarly, the class that implements the Marketing interface needs to implement 3 methods as there are 2 methods in Marketing and it inherits 1 method from Department.

34.

Can we declare a class as Abstract without having any abstract method?

Answer»

An abstract class is a class that cannot be instantiated on its own. It can be created in Java using the abstract keyword.

A class can be declared as an abstract class without having an abstract method. In that case, the class created cannot be instantiated but can be inherited.

A PROGRAM that demonstrates this is given as follows:

abstract class BaseClass {        void DISPLAY()    {        System.out.println("INSIDE the BaseClass");    } } class DerivedClass extends BaseClass { } public class Demo {    public static void MAIN(String args[])    {        DerivedClass obj = NEW DerivedClass();        obj.display();    } }

The output of the above program is as follows:

Inside the BaseClass
35.

Iterator vs ListIterator in Java

Answer»

Both ITERATOR and ListIterator in Java are an interface in the Collection framework. The Iterator is used to traverse the Collection elements by iterating each element individually in the forward direction.

ListIterator extends the Iterator and is used to traverse the Collection elements in both forward and BACKWARD directions. Also, elements can be added, modified and removed in the Collection using ListIterator which is not possible using Iterator.

The differences between Iterator and ListIterator are given as FOLLOWS:

Iterator
ListIterator
The Iterator is used to traverse the Collection elements in the forward direction.
The ListIterator is used to traverse the Collection elements in the forward and backward direction.
Maps, Lists, SETS etc. can be traversed using an Iterator.
Only List objects can be traversed using a ListIterator.
Elements cannot be modified in a Collection by an Iterator.
Elements can be modified in a Collection by a ListIterator.
Elements cannot be added to a Collection by an Iterator.
Elements can be added to a Collection by a ListIterator.
There is no METHOD in the Iterator to find an element index in a Collection.
There is a method in the ListIterator to find an element index in a Collection.
36.

What is a Thread in Java? Can we start a dead thread again?

Answer»

A thread in Java is the path that is followed when a program is executed. There is atleast ONE thread in all Java programs that is created by the JVM at the start of the program. This is known as the main thread. The java.lang.Thread class CREATES and CONTROLS all the Java threads.

The thread life cycle in Java contains 5 states. These are given below:

  1. New
  2. Runnable
  3. Running
  4. Blocked (Non-runnable)
  5. Terminated

Can a dead thread be started again in Java?

It is not possible to start a thread after it has completed execution i.e. after it is dead a thread cannot be BROUGHT to runnable state.

It is better to start a new instance. The actions that need to be executed should be wrapped in the Runnable interface and then the Runnable can be passed to the new instance of Thread.

37.

Volatile keyword in Java

Answer»

A class can be made thread safe using the volatile keyword. This means that multiple threads can use the class instance or methods at the same time without any problem.

The USAGE of the volatile keyword on a particular variable means the following:

  1. The VALUE of the variable with the volatile keyword is never CACHED thread locally. This means that all the read and write operations on the variable are saved in the main memory.
  2. The access to the variable appears as though it is enclosed in a synchronized block and is synchronized on itself.

An example of the volatile keyword is given as follows:

class Shared {   static volatile int value = 15; }

In the above example, if there are any changes made by one thread then they are reflected in the other threads as WELL using the volatile keyword.

Differences between volatile and synchronized

Some of the differences between volatile and synchronized are given as follows:

Characteristic
volatile
synchronized
Is null allowed?
Yes
No
Variable Type
Object variable or primitive variable
Object variable
When does synchronization occur?
When a volatile variable is accessed
When a synchronized block is explicitly entered or exited.
Are all cached variables synchronized on access?
This is true from Java 5 onwards.
Yes
Can this be used to combine several operations into a single atomic operation?
This is not possible before Java 5 but in Java 5 it is.
Yes
38.

When do we throw ArrayStoreException in Java

Answer»

If there is an attempt to store the wrong TYPE of object into an ARRAY of objects, then the ArrayStoreException is thrown in Java. This exception is thrown at runtime.

A program that demonstrates a try-catch block to HANDLE an ArrayStoreException in Java is given as follows:

public class Demo {    public static VOID main(String args[])    {        try        {            Object obj[] = new Integer[5];            obj[0] = 7.5;        }        catch (ArrayStoreException e)        {            System.out.println("The ArrayStoreException is found: " + e);        }    } }

The OUTPUT of the above program is as follows:

The ArrayStoreException is found: java.lang.ArrayStoreException: java.lang.Double
39.

Out Of Memory Error in Java?

Answer»

All the objects in Java are allocated memory from the heap memory. When an object cannot be allocated any memory because there is no more memory AVAILABLE and no memory can be obtained using the garbage collector, then the EXCEPTION OutOfMemoryError occurs in Java.

The Out Of Memory Error usually occurs if there is too much data processing at a time or objects are held for too long. This exception can also occur because of problems that are out of programmer control such as an application server that doesn’t clean up after deploys

A program that demonstrates the Out Of Memory Error in Java is given as FOLLOWS:

IMPORT java.util.*; public class Demo {    static List<String> l = new ArrayList<String>();    public static void main(String args[]) throws Exception    {        Integer[] arr = new Integer[5000 * 5000];    } }

The output of the above program is as follows:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at Demo.main(Demo.java:9)
40.

Can we start a thread twice in Java?

Answer»

It is not possible to START a thread twice in Java. In other words, after a thread is started once, it cannot be started again. If the thread is started a second time, then the  IllegalThreadStateException is thrown.

A program that DEMONSTRATES this is given as FOLLOWS:

PUBLIC class ThreadDemo extends Thread {      public VOID run()    {        System.out.println("Thread is running");      }    public static void main(String args[])    {        ThreadDemo thread = new ThreadDemo();          thread.start();          thread.start();      } }  

The output of the above program is as follows:

Thread is running Exception in thread "main" java.lang.IllegalThreadStateException at java.lang.Thread.start(Thread.java:708) at ThreadDemo.main(ThreadDemo.java:13)

As is seen from the above program, if the thread is started the second time, the  IllegalThreadStateException is thrown.

41.

How to format a date in Java?

Answer»

The methods to FORMAT the data in Java are provided in the class java.text.SimpleDateFormat. This class is a concrete class that is used for formatting and parsing the date and it inherits from the java.text.DateFormat class.

A program to format the date in Java using the java.text.SimpleDateFormat is given as FOLLOWS:

import java.text.SimpleDateFormat;   import java.util.Date;   public class Demo {      public static void MAIN(String[] args)    {        Date d = new Date();          SimpleDateFormat SDformat = new SimpleDateFormat("dd / MM / yy");          String curDate = SDformat.format(d);          System.out.println("The date is: " + curDate);      } }

The OUTPUT of the above program is as follows:

The date is: 14 / 12 / 18
42.

Is try without a catch allowed in Java?

Answer»

The TRY, catch and finally blocks are used for exception handling. The try block is allowed without a catch block in Java but the finally block should be PROVIDED. The finally block always executes whether there is an exception or not in the try block. The only time it does not execute is if System.exit() is called.

A program that demonstrates the try without a catch block is Java is GIVEN as follows:

PUBLIC class Demo {    public static void MAIN(String args[])    {         try         {             System.out.println("The try block");         }         finally         {             System.out.println("The finally block");         }    } }

The output of the above program is as follows:

The try block The finally block
43.

Can we declare main method final in Java?

Answer»

The final keyword is a non-access MODIFIER in Java that is only applicable for variables, methods or classes.

The MAIN method can be declared as final in Java and the JVM has no problem with that. However, it is not possible to override the main method in Java unlike any final method.

A program that declares the main method as final in Java is given as follows:

public class Demo {    public final static VOID main(STRING[] args)    {        System.out.println("The Main Method is declared final");    } }

The OUTPUT of the above program is as follows:

The Main Method is declared final
44.

Why were Streams introduced in Java 8?

Answer»

STREAMS support aggregate operations and introduced in JAVA 8. It is a sequence of OBJECTS with operations like Sorted, Map, Filter, etc.

For Streams, the following package is used:

import java.util.STREAM.*;

Here is an example of Stream operations in Java 8 to work with map and collect:

import java.util.*; import java.util.stream.*; public class Demo {  public static void main(String args[])  {    List<Integer> L = Arrays.asList(29, 35, 67);    List<Integer> res = l.stream().map(a -> a*a).collect(Collectors.toList());    System.out.println(res);  } }
45.

Can Diamond operator be used with anonymous class in Java 9?

Answer»

Yes, Diamond operator can be USED with anonymous class in Java 9. It was INTRODUCED in Java 7 to make code more readable. Till Java 7, ENHANCEMENTS weren’t introduced for Diamond operator to use with Anonymous inner classes.

46.

Best Practices while working with Collections in Java

Answer»

A group of objects can be stored and manipulated using an architecture that is provided by the Collections API in Java. All the possible operations in Java such as searching, sorting, deletion, insertion etc. can be performed using the Java Collections.

Some of the BEST practices of while working with Collections in Java are given as follows:

1. CHOOSING the right collections

Before using collections, the right collection needs to be chosen according to the problem that needs to be solved.

2. Using Arrays and Collections utility classes

The Arrays and Collections utility classes provided by the Java Collections Framework should be used as required as they provide many useful methods to SEARCH, sort and modify elements in a collection

3. Specify initial capacity of a collection if possible

The initial capacity of a collection is always specified by an overloaded CONSTRUCTOR that is contained in almost all concrete collection classes.

4. Prefer isEmpty() over size()

The isEmpty() method should be preferred over the size() method to check the emptiness of a collection. Even though there is a performance difference between these two methods, this is done to enhance the readability of this code.

5. Do not return null in a method that returns a collection

If a method returns a collection, then it should not return null if there is no element in the collection. Instead, it should return an empty collection.

6. Using the Stream API on collections

There is a stream method in every collection in Java 8 that returns a stream of elements. This means that the aggregate functions can be easily performed using the Stream API.

7. Do not use the classic for loop

Instead of using a classic for loop to iterate a list collection, use an iterator. This is because if the for loop variable is altered inside the loop, it can LEAD to bugs.

47.

Best Practices while working with multi-threading in Java

Answer»

The most important usage of threads can be achieved USING Multithreading. This means that multiple tasks can run in parallel. Some of the best practices of multi-threading in Java are given as follows:

1. Minimize the locking scope

The locking scope should be minimized as any code inside a lock cannot be executed concurrently and this REDUCES the application performance.

2. Concurrent Collections should be preferred over synchronized Collection

Concurrent Collections should be preferred over synchronized Collections as they provide more scalability and performance.

3. Prefer Immutable Classes

Immutable classes like String, Integer etc. as well as other wrapper classes should be used as they simplify the concurrent code writing. This is because there is no NEED to worry about the state.

4. Thread Pool Executors should be preferred instead of Threads

A thread pool is a better option for a scalable Java application as thread creation is quite expensive.

5. Use Local Variables

Instead of using class or instance variables, local variables should be used as much as possible.

6. BlockingQueue should be preferred for producer-consumer design

The best way to implement the producer consumer design pattern is using BlockingQueue. This is quite important as many concurrency problems are based on  the producer consumer design.

7. Synchronization utility should be preferred over wait notify

There are a lot of synchronization utilities like CyclicBarrier, COUNTDOWNLATCH and Semaphore which should be used instead of wait and notify.

8. Use Semaphore to create bounds

There should be bounds on different resources such as the file system ,database, sockets etc. to build a stable system. These bounds can be created using semaphores.

48.

When double-type is preferred over float-type in Java?

Answer»

The double-type and the FLOAT-type are both used to represent floating point numbers in Java. However, for some situations double-type is better and in some cases float-type is better.

Double-type is preferred over float-type if more precise and accurate result is required. The precision of double-type is up to 15 to 16 decimal points while the precision of float type is only around 6 to 7 decimal digits.

Another reason that double-type may be preferred over float-type is that it has a larger range. It uses 1 bit for sign, 11 bits for exponent and 52 bits for MANTISSA while float-type only uses 1 bit for sign, 8 bits for exponent and 23 bits for mantissa.

A program that demonstrates double-type and float-type in Java is given as FOLLOWS:

public class Demo {    public static void main(String []args)    {        double d = 55.637848675695785;        float f = 25.657933f;        System.out.println("Value of double = " + d);        System.out.println("Value of float = " + f);    } }

The OUTPUT of the above program is as follows:

Value of double = 55.637848675695786 Value of float = 25.657932
49.

Why do we need Wrapper classes in Java?

Answer»

A WRAPPER class is a specific class whose object CONTAINS or WRAPS PRIMITIVE data types. It can also be said that primitive data types are wrapped into an object of a wrapper class.

Some of the reasons the wrapper classes are required in Java are given as follows:

  1. The wrapper classes convert the primitive data types into objects. This is required if the arguments passed to the methods need to be modified as the primitive data types are passed by value.
  2. Synchronization in multithreading is supported by objects and so wrapper classes may be required.
  3. Only objects and not primitive types are stored in data structures such as ArrayList and Vector in the Collection framework.
  4. Another use of wrapper classes is because the classes in the java.util package HANDLE only objects.

A list of all the primitive data types and the corresponding wrapper classes is given as follows:

Primitive Data Type
Wrapper Class
Char
Character
Byte
Byte
Long
Integer
Short
Short
float
Float
Double
Double
Boolean
Boolean
50.

Shallow and Deep copy in Java

Answer»

Shallow copy and deep copy are related to the cloning PROCESS i.e. creating a copy of an object in Java. Details about the shallow and deep copy are given as follows:

Shallow Copy in Java

A shallow copy of an object is able to copy the main object but not the inner objects. This means that the original object the created copy shares the inner objects.

An example of this is given as follows:

public class Employee {   private Name name;   private DepartmentDetails dept;   public Employee(Employee emp)   {        this.name = emp.name;        this.dept = emp.dept;   } . . . }

In the above example, if a shallow copy is created of an object of class Employee, then a SECOND Employee is created but the Name and DepartmentDetails objects are shared by both the objects. So if CHANGES are made to one of the objects, then they be reflected in the object created using a shallow copy.

Deep Copy in Java

The deep copy of an object is a fully independent copy and the WHOLE object structure is copied when a new deep copy is created.

An example of this is given as follows:

public class Employee {   private Name name;   private DepartmentDetails dept;   public Employee(Employee emp)   {        this.name = emp.name;        this.dept = emp.dept;   } . . . }

In the above example, if a deep copy is created of an object of class Employee then the whole object structure is copied and if changes are made to one of the objects, then they would not be reflected in the object created using a deep copy.