Showing posts with label Java interview. Show all posts
Showing posts with label Java interview. Show all posts

Friday, May 31, 2024

Java Exception Handling Interview Questions And Answers

In this post interview questions and answers for exception handling in Java are listed. This compilation will help the Java developers in preparing for their interviews.

  1. What is Exception Handling?

    Exception Handling in Java provides a way to handle a situation when an exception is thrown and shows a meaningful message to the user and continue with the flow of the program.

    When an exceptional condition occurs with in a method, the method (where the exception occurred) creates an Exception Object and throws it. The created exception object contains information about the error, its type and the state of the program when the error occurred.

    The method where the exception is thrown may handle that exception itself or pass it on. In case it passes it on, run time system goes through the method hierarchy that had been called to get to the current method to search for a method that can handle the exception.

    Five keywords used to manage Java exception handling

    • try- Any code that might throw an exception is enclosed within a try block.
    • catch- If an exception occurs in try block, catch block can provide exception handlers to handle it in a rational manner.
    • finally- The finally block always executes when the try block exits. So, any code that must execute after a try block is completed should be put in finally block.
    • throw- throw is used to manually thrown an exception.
    • throws- Any exception that is thrown in a method but not handled there must be specified in a throws clause.
    Read more about Exception handling in Java here.

  2. Explain the exception hierarchy in Java?

    Throwable class is the super class of all the exception types. Below Throwable class there are two subclasses which denotes two distinct branches of exceptions-

    • Exception- An Exception indicates that a problem has occurred, but it is not a serious system problem. The user programs you write will throw and catch Exceptions.
    • Error- It defines exceptions that are not expected to be caught by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself.
      Examples of error are StackOverflowError, OutOfMemoryError etc.
    • Below Exception there is a distinct subclass RunTimeExcpetion- RunTimeExcpetion and its descendants denote the exceptional conditions that are external to the application, and the application usually cannot anticipate or recover from them.

    Read more about exception hierarchy in Java here.

  3. What is the difference between Checked Exception and Unchecked Exception?

    Checked Exception is a direct subclass of Exception where as unchecked exception is a subclass of RunTimeException.

    Checked exception should be wrapped in a try-catch block or specified as throws clause where as there is no such requirement for unchecked exception.

    Failure to provide exception handling mechanism for checked exception result in compiler error whereas no compile time error for unchecked exception.

    Checked exceptions are designed to reduce the number of exceptions which are not properly handled and where there is a reasonable chance for recovery. UnCheckedExceptions are mostly programming errors.

    Read more about difference between Checked Exception and Unchecked Exception here.

  4. What is the difference between error and exception?

    Exception- An Exception indicates that a problem has occurred, but it is not a serious system problem. The user programs you write will throw and catch Exceptions.

    Error- It defines exceptions that are not expected to be caught by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself.
    Examples of error are StackOverflowError, OutOfMemoryError etc.


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

    No it is not mandatory that there should be a catch block after a try block. try block can have only a matching finally block. So there are these valid combinations try-catch-finally, try-catch, try-finally.

    Read more about try-catch block here.

  6. What is finally block?

    When an exception occurs in the code, the flow of the execution may change or even end abruptly. That may cause problem if some resources were opened in the method.
    For example, if a file was opened in a method and it was not closed in the end as some exception occurred then the resources may remain open consuming memory. finally provides that exception-handling mechanism to clean up.

    Code with in the finally block will be executed after a try/catch block has completed. The finally block will be executed whether or not an exception is thrown.

    Read more about finally block here.

  7. Is it possible to have a finally block without catch?

    Yes we can have a try-finally block, catch is optional. We can have these combinations try-catch-finally, try-catch, try-finally.

    Read more about finally block here.

  8. Are you aware of any scenario when finally will not be executed?

    According to Java docs. If the JVM exits (By explicitly using System.exit() or a JVM crash) while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

    Read more about finally here.

  9. What is a nested try statement?

    A try-catch-finally block can reside inside another try-catch-finally block that is known as nested try statement.

    public class NestedTryDemo {
      public static void main(String[] args) {
        try{
          System.out.println("In Outer try block");
          try{
            System.out.println("In Inner try block");
            int a = 7 / 0;
          }catch (IllegalArgumentException e) {
            System.out.println("IllegalArgumentException caught");
          }finally{
            System.out.println("In Inner finally");
          }
        }catch (ArithmeticException e) {
          System.out.println("ArithmeticException caught");
        }finally {
          System.out.println("In Outer finally");
        }
      }
    }
    
    Read more about nested try statement here.

  10. What are multiple catch blocks?

    There might be a case when a code enclosed with in a try block throws more than one exception. To handle these types of situations, two or more catch clauses can be specified where each catch clause catches a different type of exception. When an exception is thrown, each of the catch statement is inspected in order, and the first one whose type matches that of the thrown exception is executed.

    int a[] = {0};
    try{
      int b = 7/a[i];
    }catch(ArithmeticException aExp){
      aExp.printStackTrace();
    }catch(ArrayIndexOutOfBoundsException aiExp){
      aiExp.printStackTrace();
    }
    
    Read more about multiple catch blocks here.

  11. What is exception propagation?

    When an exceptional condition occurs within a method, the method (where the exception occurred) creates an Exception Object and throws it. The created exception object contains information about the error, its type and the state of the program when the error occurred.
    The method where the exception is thrown may handle that exception itself or pass it on. In case it passes it on, run time system goes through the method hierarchy that had been called to get to the current method to search for a method that can handle the exception.
    If your program is not able to catch any particular exception, that will ultimately be processed by the default handler. This process of going through the method stack is known as Exception propagation.

    Read more about exception propagation here.

  12. What is throw keyword?

    It is possible for a Java program to throw an exception explicitly that is done using the throw statement.

    The general form of throw is-
    throw throwableObject;

    We can get this throwableObject in 2 ways-
    • By using the Exception parameter of catch block.
    • Create a new one using the new operator.
    try{
       throw new NullPointerException();   
      }catch(NullPointerException nExp){
       System.out.println("Exception caught in catch block of displayValue");
       throw nExp;
      }
     }
    
    Read more about throw keyword here.

  13. What is throws clause?

    If in a method we don't want to handle any exception but want to leave it to the calling method to handle any exception that is thrown by the called method, it is done using throws keyword.

    Using throws a method can just declare the exception it may throw and callers of the method have to provide exception handling for those exceptions (or they can also declare them using throws).

    General form of a method declaration that includes a throws clause

    type method-name(parameter-list) throws exception-list
    {
    // body of method
    }
    
    Here, exception-list is a comma-separated list of the exceptions that a method can throw.
    Read more about throws clause here.

  14. Difference between throw and throws?

    • throw is used to throw an exception.
    • throws is used to declare an exception, in the method signature, that can be thrown from a method.
    Read more about difference between throw and throws here.

  15. final Vs finally Vs finalize

    • final- final keyword is used to restrict in some way. It can be used with variables, methods and classes. When a variable is declared as final, its value can not be changed once it is initialized. Except in case of blank final variable, which must be initialized in the constructor.
      If you make a method final in Java, that method can't be overridden in a sub class.
      If a class is declared as final then it can not be sub classed.
    • finally- finally is part of exception handling mechanism in Java. finally block is used with try-catch block. finally block is always executed whether any exception is thrown or not and raised exception is handled in catch block or not. Since finally block always executes thus it is primarily used to close the opened resources like database connection, file handles etc.
    • finalize()- finalize() method is a protected method of java.lang.Object class. Since it is in Object class thus it is inherited by every class. This method is called by garbage collector thread before removing an object from the memory. This method can be overridden by a class to provide any cleanup operation and gives object final chance to cleanup before getting garbage collected.
      protected void finalize() throws Throwable
      {
        //resource clean up operations
      }
      
    Read more about final Vs finally Vs finalize here.

  16. What are the rules of exception handling with respect to method overriding?

    There are certain restrictions while overriding a method in case of exception handling in Java. Broadly there are two rules-

    • If superclass method has not declared any exception using throws clause then subclass overridden method can't declare any checked exception though it can declare unchecked exception.
    • If superclass method has declared an exception using throws clause then subclass overridden method can do one of the three things.
      • sub-class can declare the same exception as declared in the super-class method.
      • subclass can declare the subtype exception of the exception declared in the superclass method. But subclass method can not declare any exception that is up in the hierarchy than the exception declared in the super class method.
      • subclass method can choose not to declare any exception at all.
    Read more about exception handling and method overriding here.

  17. What is the error in the following code?

    class Parent{
       public void displayMsg() throws IOException{
         System.out.println("In Parent displayMsg()");
        throw new IOException("Problem in method - displayMsg - Parent");
       }
    }
    public class ExceptionOverrideDemo extends Parent{
      public void displayMsg() throws Exception{  
        System.out.println("In ExceptionOverrideDemo displayMsg()"); 
        throw new Exception("Problem in method - displayMsg - ExceptionOverrideDemo");
      }  
    }
     

    Here parent class had declared IOException where as subclass has declared Exception. Exception is the super class of IOException thus it is wrong according to the rules of method overriding and exception handling. Thus the code will give compiler error.

    Read more about exception handling and method overriding here.

  18. What is multi-catch statement in Java 7?

    Before Java 7 multi-catch statement, if two or more exceptions were handled in the same way, we still had to write separate catch blocks for handling them.

    catch(IOException exp){
      logger.error(exp);
      throw exp;
    }catch(SQLException exp){
      logger.error(exp);
      throw exp;
    }
    

    With Java 7 and later it is possible to catch multiple exceptions in one catch block, which eliminates the duplicated code. Each exception type within the multi-catch statement is separated by Pipe symbol (|).

    catch(IOException | SQLException exp){
      logger.error(exp);
      throw exp;
    }
    
    Read more about multi-catch statement in Java 7 here.

  19. What is try-with-resources or ARM in Java 7?

    Java 7 introduced a new form of try known as try-with-resources for Automatic Resource Management (ARM). Here resource is an object that must be closed after the program is finished with it. Example of resources would be an opened file handle or database connection etc.

    Before the introduction of try-with-resources we had to explicitly close the resources once the try block completes normally or abruptly.

    try {
        br = new BufferedReader(new FileReader("C:\\test.txt"));
        System.out.println(br.readLine());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
      try {
        if (br != null){
          System.out.println("Closing the file");
          br.close();
        }                
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
    

    try-with-resources helps in reducing such boiler plate code. Let's see the same example using try-with-resources.

    try(BufferedReader br = new BufferedReader(new FileReader("C:\\test.txt"))) {            
      System.out.println(br.readLine());
    } catch (IOException e) {
      e.printStackTrace();
    } 
    
    Read more about try-with-resources in Java 7 here.

  20. When is custom exception class needed? How to create a custom exception class?

    According to Java Docs, you should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's.

    • Do you need an exception type that isn't represented by those in the Java platform?
    • Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
    • Does your code throw more than one related exception?
    • If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?
    Read more about creating custom exception class here.

  21. What is the difference Between StackOverflowError and OutOfMemoryError in Java?

    StackOverflowError- Whenever you run any Java program even if you don’t explicitly create any thread a main thread is started and that thread runs the program. For each thread JVM creates a stack, whenever any method is invoked a new frame is created and pushed into the JVM stack for the thread. Each frame stores data corresponding to the invoked method including local variables, operand stack and a reference to the run-time constant pool and reference to exception table. Once the method execution is completed corresponding stack frame is popped out of the stack.
    JVM throws StackOverflowError if the stack memory requirement of any method exceeds the permitted stack memory size.

    OutOfMemoryError- In Java, memory for each object, for arrays and for instance variables (variables at class level not method level) is created on the heap. When there are no references to an object that object is garbage collected thus clearing the heap memory. If you try to create an object or array that tries to take more memory than the allocated heap memory or there are a lot of objects in heap that are still referenced so can’t be garbage collected and JVM tries to allocate heap memory for a new object JVM throws java.lang.OutOfMemoryError because there is no sufficient heap memory.

    Read more about difference Between StackOverflowError and OutOfMemoryError here.

Related Topics

  1. Java Multithreading Interview Questions And Answers
  2. Java Collections Interview Questions And Answers
  3. Java String Interview Questions And Answers
  4. Core Java Basics Interview Questions And Answers
  5. Java OOP Interview Questions And Answers
  6. Java Concurrency Interview Questions And Answers
  7. Java Lambda Expressions Interview Questions And Answers
  8. Java Stream API Interview Questions And Answers

Thursday, January 11, 2024

Java Stream API Interview Questions And Answers

In this post Java Stream API Interview Questions and answers are listed. This compilation will help the Java developers in preparing for their interviews.

  1. What is Stream API in Java?

    Stream API is added in Java 8 and works very well in conjunction with lambda expressions. You can create a pipeline of stream operations to manipulate data by performing operations like search, filter, sort, count, map etc.

    Read more about Stream API in Java here.

  2. What is stream in Stream API?

    A stream can be visualized as a pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc.), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate)), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer)).

    Read more about Stream API in Java here.

  3. Explain stream operations with an example?

    In this example let's take an ArrayList as an input. There are two operations; take only those elements of the list which are greater than 5 and then sort the result. After that print the elements of the list.

    // Creating the list
    List<Integer> numList = Arrays.asList(34, 6, 3, 12, 65, 1, 8);
    numList.stream().filter((n) -> n > 5).sorted().forEach(System.out::println); 
    
    Here ArrayList is the data source for the stream and there are two intermediate operations–
    • filter- Filter condition here is; take only those elements of the list which are greater than 5. Click to read more about filter() method.
    • sorted- sort that filtered output of the last stream. Click to read more about sorted() method.
    Terminal operation here is forEach statement (provided in Java 8) which iterates the sorted result and displays them. Read more about forEach statement in Java 8 here.

  4. How many types of Stream operations are there?

    Stream operations are divided into intermediate and terminal operations, and are combined to form stream pipelines.

    • Intermediate operations return a new stream. They are always lazy; executing an intermediate operation does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate.
    • Terminal operations such as Stream.forEach or IntStream.sum, may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.
    See some Stream API examples here.

  5. What are Stateless and Stateful operations in Java stream?

    Intermediate operations are further divided into stateless and stateful operations.

    • Stateless operations, such as filter() and map(), retain no state from previously seen element when processing a new element, each element can be processed independently of operations on other elements.
    • Stateful operations, such as distinct() and sorted(), may incorporate state from previously seen elements when processing new elements. Stateful operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream.
    See some Stream API examples here.

  6. What is Parallel Stream in Java Stream API?

    You can execute streams in serial or in parallel. When a stream executes in parallel, the Java runtime partitions the stream into multiple sub-streams.

    As example- Collection has methods Collection.stream() and Collection.parallelStream(), which produce sequential and parallel streams respectively.

    Read more about parallel stream here.

  7. What is the benefit of using parallel stream?

    When parallel stream is used the Java runtime partitions the stream into multiple sub-streams. This parallel execution of data, with each sub-stream running in a separate thread, will result in increase in performance.

    Read more about parallel stream here.

  8. Can you use streams with primitives?

    Streams work only on object references. They can’t work on primitive types so you have two options to use primitives.

    • You can wrap primitive types into a wrapper object. As example Stream<Integer>, Stream<Long> or Stream<Double>.
    • Second and better option is to use primitive specializations of Stream like IntStream, LongStream, and DoubleStream that can store primitive values.
    • As example- IntStream is = IntStream.of(3, 4, 5, 6);

    Read more about Primitive type streams in Java here.

  9. How can you transform Stream to primitive type Stream?

    Stream interface provides methods mapToInt, mapToDouble and mapToLong that can be used to transform stream of objects to a stream of primitive types.

    As example- If you have a list of employee objects and you want to get the maximum salary. In that case you can take the salary field and use mapToInt method to get a stream of primitive types. Then you can use max method on that primmitive type stream.

    OptionalInt maxSalary = empList.parallelStream().mapToInt(e -> e.getSalary()).max();
    
    Read more about Primitive type streams in Java Stream API here.

  10. What are Reduction Operations in Java Stream API?

    Stream API contains many terminal operations (such as average, sum, min, max, and count) that return one value by combining the contents of a stream. These operations are called reduction operations because these operations reduce the stream to a single non-stream value.

    Read more about Reduction Operations in Java Stream API here.

  11. What are Map operation in Java Stream API?

    Map operations are used to do the element mapping from one stream to another. Map operation will return a stream consisting of the results of applying the given function to the elements of this stream. So, whatever function is provided is applied on all the elements of the stream.

    Since new stream is returned map operation is an intermediate operation.

    Read more about Map operation in Java Stream API here.

  12. What is a mutable reduction operation?

    A mutable reduction operation can be defined as an operation that accumulates input elements into a mutable result container, such as a Collection or StringBuilder.

    Read more about Reduction operation in Java Stream API here.

  13. What is a collect method in Java stream?

    Using collect method you can store the result of the stream operation into a collection. This is a terminal operation.

    As example- If you have employee objects and you want a list having names of all the employees you can use the toList method of the Collectors class.

    List<String> nameList = empList.stream().map(Employee::getName).collect(Collectors.toList());
    
    Read more about Collecting in Java Stream API here.

  14. What is flatMap() method in Java?

    In mapping operation the given function is applied to all the elements of the stream. Where as flattening a structure, means bringing all the nested structures at the same level.

    As example if you have a list of Strings, list<String> like - [[“a”, “b”, “c”], [“c”, “d”], [“c”, “e”, “f”]] then flattening it will bring everything to the same level and the structure you will have be like this-

    [“a”, “b”, “c”, “c”, “d”, “c”, “e”, “f”]
    

    flatMap() method means you are bringing both of them together, function will be applied to all the elements of the stream and then it will be flatten to have a single level structure.

    Read more about FlatMap in Java here.

  15. What is a Spliterator in Java?

    Spliterators, like iterators, are for traversing the elements of a source. Spliterator can split the source and iterate the splitted parts in parallel. That way a huge data source can be divided into small sized units that can be traversed and processed in parallel.

    You can also use spliterator even if you are not using parallel execution.

    Read more about Spliterator in Java here.

Related Topics

  1. Java Lambda Expressions Interview Questions And Answers
  2. Java Concurrency Interview Questions And Answers
  3. Java Multithreading Interview Questions And Answers
  4. Java Collections Interview Questions And Answers
  5. Java Exception Handling Interview Questions And Answers
  6. Java String Interview Questions And Answers
  7. Java OOP Interview Questions And Answers
  8. Core Java Basics Interview Questions And Answers

Friday, December 2, 2022

Java Concurrency Interview Questions And Answers

In this post Java Concurrency Interview questions and answers are listed. This compilation will help the Java developers in preparing for their interviews.

  1. What is CountDownLatch in Java concurrency?

    CountDownLatch can be visualized as a latch that is released only after the given number of events occur. CountDownLatch is initialized with that count (given number of events).

    Each time one of those events occur count is decremented, for that countdown() method is used. Thread(s) that are waiting for the latch to release (current count reaches zero due to invocations of the countDown()method) are blocked using await() method.

    It is useful in the scenario when you want one or more threads to wait until one or more events being performed in other threads complete.

    Read more about CountDownLatch here.
  2. What is CyclicBarrier in Java concurrency?

    CyclicBarrier is useful in scenarios where you want set of threads to wait for each other to reach a common barrier point. When each thread reaches the barrier (common point) you need to call await() method on the CyclicBarrier object. This will suspend the thread until all the thread also call the await() method on the same CyclicBarrier object.

    Once all the specified threads have called await() method that will trip the barrier and all threads can resume operation.

    The barrier is called cyclic because it can be re-used after the waiting threads are released.

    Read more about CyclicBarrier here.
  3. What is the difference between a CountDownLatch and CyclicBarrier?

    • When you are using a CountDownLatch, you specify the number of calls to the countdown() method when creating a CountDownLatch object. What this means is you can use CountDownLatch with only a single thread and using countdown() to decrement as and when the specified even occur.
      When you are using CyclicBarrier you specify the number of threads that should call await() method in order to trip the barrier. That means if you have a CyclicBarrier initialized to 3 that means you should have at least 3 threads to call await().
    • CountDownLatch can't be reused, when count reaches zero it cannot be reset.
      CyclicBarrier can be reused after the waiting threads are released.
    Read more differences and explanation here.
  4. If a CountDownLatch is initialized with some count let's say 3 (new CountDownLatch(3)). Do we need to have 3 threads for countdown in that case?

    No. Same number of threads are not required. A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.

    Read more about CountDownLatch here.
  5. What is Phaser in Java concurrency?

    Phaser is more suitable for use where it is required to synchronize threads over one or more phases of activity. Though Phaser can be used to synchronize a single phase, in that case it acts more like a CyclicBarrier.

    Phaser is reusable (like CyclicBarrier) and more flexible in usage.

    The number of parties registered to synchronize on a phaser may vary over time. Tasks may be registered at any time (using methods register(), bulkRegister(int), or by specifying initial number of parties in the constructor). Tasks may also be optionally deregistered upon any arrival (using arriveAndDeregister()).

    Read more about Phaser here.
  6. What is Exchanger in Java concurrency?

    Exchanger makes it easy for two threads to exchange data between themselves.

    Exchanger provides a synchronization point at which two threads can pair and swap elements. Exchanger waits until two separate threads call its exchange() method. When two threads have called the exchange() method, Exchanger will swap the objects presented by the threads.

    Read more about Exchanger here.
  7. What is Semaphore in Java concurrency?

    The Semaphore class present in java.util.concurrent package is a counting semaphore in which a semaphore, conceptually, maintains a set of permits. Thread that wants to access the shared resource tries to acquire a permit using acquire() method. At that time if the Semaphore's count is greater than zero thread will acquire a permit and Semaphore's count will be decremented by one. If Semaphore's count is zero, when thread calls acquire() method, then the thread will be blocked until a permit is available. When thread is done with the shared resource access, it can call the release() method to release the permit. That results in the Semaphore's count incremented by one.

    Read more about Semaphore here.
  8. Write a Java program to print odd/even numbers using semaphore?

    See the program with explanation here-

    Print odd/even numbers using semaphore
  9. What is ReentrantLock in Java?

    ReentrantLock is a concrete implementation of the Lock interface which is present in java.util.concurrent.locks package.

    Every object created in Java has one mutually exclusive lock associated with it. When you are using synchronized you are using that lock implicitly (with no other feature) whereas when you are using any of the lock implementation (like Reentrant lock) you are using that lock explicitly. Which means there are methods like lock() to acquire the lock and unlock() to release the lock. Along with that ReentrantLock provides many other features like fairness, ability to interrupt and a thread waiting for a lock only for a specified period.

    Read more about ReentrantLock here.
  10. What is the Difference between ReentrantLock and Synchronized?

    • When you use a synchronized block or method you just need to write synchronized keyword (and provide associated object) acquiring lock and releasing it is done implicitly.

      With ReentrantLock acquiring and releasing lock is done by user using lock() and unlock() methods.

    • Synchronized forces all lock acquisition and release to occur in a block-structured way which means when multiple locks are acquired they must be released in the opposite order, and all locks must be released in the same lexical scope in which they were acquired.

      ReentrantLock provides more flexibility, it allows a lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order.

    • ReentrantLock provides additional functionality over the use of synchronized methods and statements by providing an option for fairness, providing a non-blocking attempt to acquire a lock (tryLock()), an attempt to acquire the lock that can be interrupted (lockInterruptibly(), and an attempt to acquire the lock that can timeout (tryLock(long, TimeUnit)).
    Read more differences between ReentrantLock and Synchronized here.
  11. Why is it named ReentrantLock?

    It is called ReentrantLock as there is an acquisition count associated with the lock which means when you use lock() method to acquire a lock and you get it then the acquisition count is 1.

    A Reentrant lock will also allow the lock holder to enter another block of code with the same lock object as thread already owned it. In that case, if a thread that holds the lock acquires it again, the acquisition count is incremented and the lock then needs to be released twice to truly release the lock.

    Read more about ReentrantLock here.
  12. What is ReadWriteLock in Java?

    In a multi-threading application multiple reads can occur simultaneously for a shared resource. It is only when multiple writes happen simultaneously or intermix of read and write that there is a chance of writing the wrong value or reading the wrong value.

    ReadWriteLock uses the same idea in order to boost the performance by having separate pair of locks. A ReadWriteLock maintains a pair of associated locks -

    • One for read-only operations;
    • and
    • One for writing.

    The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.


  13. What is ReentrantReadWriteLock in Java concurrency?

    ReentrantReadWriteLock is an implementation of the ReadWriteLock interface which provides a pair of read-write lock.
    • To get a read lock you need to use - rw.readLock().lock();
    • To get a write lock you need to use - rw.writeLock().lock();
    Where rw is an object of ReentrantReadWriteLock class.

    ReentrantReadWriteLock also allows downgrading from the write lock to a read lock. You can first acquire a write lock, then the read lock and then release the write lock.

    Read more about ReentrantReadWriteLock here.
  14. How ReadWritelock can help in reducing contention among multiple threads? OR
    What is benefit of using ReadWriteLock in Java?

    ReadWriteLock provides separate set of locks for reading and writing operations. Where read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.

    So read operations are not mutually exclusive. It exploits the fact that while only a single thread at a time (a writer thread) can modify the shared data, in many cases any number of threads can concurrently read the data (hence reader threads).

    Thus in the applications where reads are more than writes or duration of reads is more the thread contention will be less as read lock is shared by many thread rather than being mutually exclusive. So you won't have a situation where only one thread is reading and other threads are waiting.

    Read more about ReentrantReadWriteLock here.
  15. What is ConcurrentHashMap in Java?

    ConcurrentHashMap is also a hash based map like HashMap, how it differs is the locking strategy used by ConcurrentHashMap. Unlike HashTable (or synchronized HashMap) it doesn't synchronize every method on a common lock. ConcurrentHashMap uses separate lock for separate buckets thus locking only a portion of the Map.

    That way ConcurrentHashMap depite being a thread safe alternative to HashTable gives much better performance.

    Read more about ConcurrentHashMap here.
  16. What is lock striping in concurrent programming?

    The concept of lock striping is to have separate locks for a portion of a data structure where each lock is locking on a variable sized set of independent objects.

    That's how ConcurrentHashMap in Java provides synchronization. By default ConcurrentHashMap has 16 buckets and each bucket has its own lock so there are 16 locks too. So the threads which are accessing keys in separate buckets can access them simultaneously.

    Read more about lock striping here.
  17. What is the Difference between HashMap and ConcurrentHashMap in Java?

    • ConcurrentHashMap is thread safe and fit for use in a multi-threaded environment whereas HashMap is not thread safe.
    • HashMap can be synchronized using the Collections.synchronizedMap() method but that synchronizes all the methods of the HashMap and effectively reduces it to a data structure where one thread can enter at a time.
      In ConcurrentHashMap synchronization is done a little differently. Rather than locking every method on a common lock, ConcurrentHashMap uses separate lock for separate buckets thus locking only a portion of the Map.
    Read more difference here here.
  18. Why ConcurrentHashMap is faster than Hashtable in Java?

    In HashTable each method is synchronized on a single lock which means at any given time only one thread can enter any method.
    ConcurrentHashMap uses separate lock for separate buckets thus locking only a portion of the Map. By default there are 16 buckets and also separate locks for separate buckets. So the default concurrency level is 16. Thus theoretically at any given time 16 threads can access separate buckets without blocking which improves the performance of the ConcurrentHashMap.

    In ConcurrentHashMap performance is further improved by providing read access concurrently without any blocking. Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove).

    Read more about ConcurrentHashMap here.
  19. What is CopyOnWriteArrayList in Java?

    CopyOnWriteArrayList is also an implementation of the List interface but it is a thread safe variant. This thread safety is achieved by making a fresh copy of the underlying array with every mutative operations (add, set, and so on).

    Using CopyOnWriteArrayList provides better performance in scenarios where there are more iterations of the list than mutations.

    Read more about CopyOnWriteArrayList here.
  20. What is the Difference between ArrayList and CopyOnWriteArrayList in Java?

    ArrayList is not thread-safe whereas CopyOnWriteArrayList is thread-safe and fit for use in multi-threaded environment.

    Iterator returned by ArrayList is fail-fast. Iterator returned by CopyOnWriteArrayList is fail-safe.

    Performance wise ArrayList is faster as it is not synchronized and there is no added burden of thread-safety. CopyOnWriteArrayList is comparatively slower and if there are lots of writes by various threads that will degrade the performance of the CopyOnwriteArrayList as there will be copies made per mutation.

    Read more differences and explanation here.
  21. What is CopyOnWriteArraySet in Java?

    CopyOnWriteArraySet is a thread-safe collection and it internally uses CopyOnWriteArrayList for all of its operations.

    Since it uses CopyOnWriteArrayList internally so thread-safety is achieved in the same way in CopyOnwriteArraySet as in CopyOnWriteArrayList - all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.

    The iterator returned by CopyOnwriteArraySet is fail-safe which means any structural modification made to the CopyOnwriteArraySet won't throw ConcurrentModificationException.

    Read more about CopyOnWriteArraySet here.
  22. What is ConcurrentSkipListMap in Java?

    ConcurrentSkipListMap implements ConcurrentNavigableMap and it is a sorted map just like TreeMap with the added feature of being concurrent.
    ConcurrentSkipListMap is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

    Read more about ConcurrentSkipListMap here.
  23. What is ConcurrentSkipListSet in Java?

    ConcurrentSkipListSet implements NavigableSet and it is a sorted set just like TreeSet with added feature of being concurrent.
    The elements of the set are kept sorted according to their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

    Read more about ConcurrentSkipListSet here.
  24. What is ConcurrentLinkedQueue in Java?

    ConcurrentLinkedQueue is an unbounded thread-safe queue which stores its elements as linked nodes. This queue orders elements FIFO (first-in-first-out).
    It doesn't block operations as it is done in the implementations of BlockingQueue interface like ArrayBlockingQueue.

    Read more about ConcurrentLinkedQueue here.
  25. What is ConcurrentLinkedDequeue in Java?

    ConcurrentLinkedDeque is an unbounded thread-safeDeque which stores its elements as linked nodes. Since it implements deque interface ConcurrentLinkedDequesupports element insertion and removal at both ends.

    ConcurrentLinkedDequeue is thread safe and it doesn't block operations.

    Read more about ConcurrentLinkedDequeue here.
  26. What do you mean by non-blocking algorithm/data structure?

    An algorithm is called non-blocking if it doesn't block threads in such a way that only one thread has access to the data structure and all the other threads are waiting. Same way failure of any thread in a non-blocking algorithm doesn't mean failure or suspension of other threads.

    Implementation of non-blocking data structures in Java like atomic variables or ConcurrentLinkedQueue use an atomic read-modify-write kind of instruction based on compare-and-swap.

    Read more about non-blocking algorithm here.
  27. What is Busy Spinning? When will you use Busy Spinning as waiting strategy?

    Busy spinning or busy wait in a multi-threaded environment is a technique where other threads loop continuously waiting for a thread to complete its task and signal them to start.

    Busy spinning is wasteful of CPU cycles as thread just keep running in a loop unless the condition given in the loop satisfies. Busy spinning may give some advantage in multi-core processors. If a thread relinquishes CPU, the CPU cache for the thread where the thread state, data are stored will also be lost, if the thread resumes its operation on another CPU. In that case it has to rebuild the cache again.

    Read more about Busy Spinning here.
  28. What is BlockingQueue in Java Concurrency?

    BlockingQueueinterface is added in Java 5 with in the java.util.concurrent package.

    BlockingQueue is a queue that can block the operations. Which means BlockingQueue supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

    BlockingQueue provides following blocking methods-
    • put(E e)- Inserts the specified element into this queue, waiting if necessary for space to become available.
    • take()- Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.
    Read more about BlockingQueue here.
  29. Write a Java program to code producer consumer design using blocking queue.

    Please refer Producer-Consumer Java program using ArrayBlockingQueue for the Java program to code producer consumer design using blocking queue.
  30. What is blocking method in Java?

    Methods which want to execute the task assigned without relinquishing control to other thread are called blocking methods.

    A very relevant example of blocking methods, which most of you would have encountered is read() method of theInputStream class. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

    Read more about blocking method here.
  31. What is ArrayBlockingQueue in Java Concurrency?

    ArrayBlockingQueue is an implementation of the BlockingQueue interface. ArrayBlockingQueue is a bounded blocking queue which internally uses an array to store elements.

    Since ArrayBlockingQueue is bounded it means it has to be created with some initial capacity and that capacity cannot be changed later. Attempts to put an element into a full queue will result in the operation blocking; attempts to take an element from an empty queue will similarly block.

    Read more about ArrayBlockingQueue here.
  32. What is LinkedBlockingQueue in Java Concurrency?

    LinkedBlockingQueue is an implementation of BlockingQueue interface.

    LinkedBlockingQueue internally uses linked nodes to store elements. It is optionally bounded and that's where it differs from ArrayBlockingQueue which is bounded.

    Read more about LinkedBlockingQueue here.
  33. What is PriorityBlockingQueue in Java Concurrency?

    PriorityBlockingQueue class implements the BlockingQueue interface. The elements of the PriorityBlockingQueue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which of the following constructor is used.

    • PriorityBlockingQueue()- Creates a PriorityBlockingQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
    • PriorityBlockingQueue(int initialCapacity, Comparator<? super E> comparator)- Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to the specified comparator.
    PriorityBlockingQueue class does not permit null elements. Read more about PriorityBlockingQueue here.
  34. What is SynchronousQueue in Java?

    SynchronousQueue is an implementation of the BlockingQueue interface. SynchronousQueue does not have any internal capacity, not even a capacity of one. In SynchronousQueue each insert operation must wait for a corresponding remove operation by another thread, and vice versa.

    If you put an element in SynchronousQueue using put() method it will wait for another thread to receive it, you can't put any other element in the SynchronousQueue as it is blocked.

    Read more about SynchronousQueue here.
  35. What is DelayQueue in Java Concurrency?

    DelayQueue is an unbounded implementation of BlockingQueue interface. DelayQueue can store elements of type Delayed only and an element can only be retrieved from DelayQueue when its delay has expired.

    When you implement Delayed interface two methods have to be implemented getDelay(TimeUnit unit) and compareTo(T o).

    getDelay(TimeUnit unit)- Returns the remaining delay associated with this object, in the given time unit.

    Read more about DelayQueue here.
  36. What is TransferQueue in Java?

    TransferQueue interface, added in Java 7, extends BlockingQueue interface. The extra functionality provided by TransferQueue interface is that it provides blocking method which will wait until other thread receives your element.

    That's how it differs from BlockingQueue where you can only put element into queue or retrieve element from queue and block if queue is full (while you are putting elements) or block if queue is empty (while you are retrieving elements).

    TransferQueue has a blocking method transfer(E e) which will ensure that the element is transferred to the consumer, it will wait if required to do so.

    Read more about TransferQueue here.
  37. What is LinkedTransferQueue in Java?

    LinkedTransferQueue, is an implementation of the TransferQueue. It is an unbounded queue and stores elements as linked nodes.

    Read more about TransferQueue here.
  38. What is BlockingDeque in Java Concurrency?

    BlockingDeque interface (added in Java 6) is a Deque that provides additional support for blocking operations. Blocking methods of BlockingDeque interface come in four forms.

    • Throw exception- Methods falling in this category will throw exception if blocked.
    • Return special value- This type of methods will return some value if need to wait, like false.
    • Blocks- This type of methods will wait if necessary for space to become available.
    • Times out- This type of methods will block for only a given maximum time limit before giving up.

    BlockingDeque is thread safe, does not permit null elements, and may (or may not) be capacity-constrained.

    Read more about BlockingDeque here.
  39. What is LinkedBlockingDeque in Java?

    LinkedBlockingDeque is an implementation of the BlockingDeque interface and it was added in Java 6. LinkedBlockingDeque is an optionally bounded deque and it stores its elements as linked nodes.

    Read more about LinkedBlockingDeque here.

  40. What is Executor in Java concurrency?

    The concurrent API has a feature called executors that provides an alternative to managing threads through the Thread class. At the core of the executors is the Executor interface- An object of type Executor can execute runnable tasks. An Executor is normally used instead of explicitly creating threads.
    For example If r is a Runnable object, and e is an Executor object you can replace

    (new Thread(r)).start();
    
    with
    e.execute(r);
    
    The Executor interface provides a single method, execute -
    void execute(Runnable command)
    

    Read more about Executor here.

  41. What is ExecutorService in Java concurrency?

    ExecutorService interface extends Executor interface and provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.
    ExecutorService has more versatile submit method. Like execute, submit accepts Runnable objects, but also accepts Callable objects, which allow the task to return a value. The submit method returns a Future object, which is used to retrieve the Callable return value and to manage the status of both Callable and Runnable tasks.

    Read more about ExecutorService here.

  42. Name any class that implements Executor or ExecutorService interface?

    In the Java concurrency there are three predefined executor classes that implement the Executor and ExecutorService interface.

    • ThreadPoolExecutor- Implements the Executor and ExecutorService interfaces and executes the submitted task using one of the pooled thread.
    • ScheduledThreadPoolExecutor- It extends ThreadPoolExecutor and also implements the ScheduledExecutorService. This class schedule commands to run after a given delay, or to execute periodically.
    • ForkJoinPool- It implements the Executor and ExecutorService interfaces and is used by the Fork/Join Framework.
    Read more about ExecutorService here.

  43. What is difference between submit() and execute() method of Executor and ExecutorService in Java?

    • execute() method is provided by Executor interface where as submit() method is provided by ExecutorService.
    • execute() method only takes Runnable as argument- execute(Runnable command) and does not return any value.
    • ExecutorService has more versatile submit() method. submit() method is overloaded and accepts both Runnable objects and Callable objects, submit also allows the task to return a value (an object of type Future). The Future's get method will return the given result upon successful completion.

  44. How can I immediately block a thread even if I am using submit method and using a callable object?

    If you would like to immediately block waiting for a task, you can use constructions of the form

    result = exec.submit(aCallable).get();
    

  45. What will happen if submit method can’t schedule a task for execution?

    It will throw RejectedExecutionException.


  46. How to shut down an ExecutorService?

    An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService.
    The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted.

    Read more about ExecutorService here.
  47. What is a ScheduledExecutorService?

    ScheduledExecutorService extends ExecutorService and provides methods that can schedule commands to run after a given delay, or to execute periodically.
    It has methods that execute a Runnable or Callable task after a specified delay.

    • schedule(Callable<V> callable, long delay, TimeUnit unit) - Creates and executes a ScheduledFuture that becomes enabled after the given delay.
    • schedule(Runnable command, long delay, TimeUnit unit) - Creates and executes a one-shot action that becomes enabled after the given delay.

    Read more about ScheduledExecutorService here.
  48. What is Executors class?

    Executors class provide factory and utility methods for Executors framework classes like Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable.
    Though you can use ThreadPoolExecutor and ScheduledThreadPoolExecutor directly, but the best way to get an executor is to use one of the static factory methods provided by the Executors utility class.
    Some of the factory methods-

    • static ExecutorService newCachedThreadPool()- Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.
    • static ExecutorService newFixedThreadPool(int numThreads)- Creates a thread pool that reuses a fixed number of threads.
    • static ScheduledExecutorService newScheduledThreadPool(int numThreads)- Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.
    • newSingleThreadExecutor()- Creates an Executor that uses a single worker thread operating off an unbounded queue.
    As example -
    ExecutorService ex = Executors.newFixedThreadPool(2);
    


  49. What is threadpool in Java?

    In a large scale application if each task uses its own thread then allocating and deallocating many thread objects creates a significant memory management overhead.
    Thread pool as the name suggests provides a set of threads, any task which has to be executed get a thread from this pool.

    // creating executor with pool of 2 threads
      ExecutorService ex = Executors.newFixedThreadPool(2);
      // running 6 tasks
      ex.execute(new Task());
      ex.execute(new Task());
      ex.execute(new Task());
      ex.execute(new Task());
      ex.execute(new Task());
      ex.execute(new Task());
      //shutting down the executor service
      ex.shutdown();
    
    Even if we are running 6 tasks here, all these tasks would be run using the 2 threads from the pool.


  50. How to construct a thread pool with 2 threads that executes some tasks that return a value?

    You can create a fixed thread pool using the newFixedThreadPool() method of the Executors class.

    // creating executor with pool of 2 threads
      ExecutorService ex = Executors.newFixedThreadPool(2);
      // running tasks
      Future f1 = ex.submit(new Task());
      Future f2 = ex.submit(new Task());
      try {
       // getting the future value
       System.out.println("Future f1 " + f1.get());
       System.out.println("Future f1 " + f1.get());
      } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      } catch (ExecutionException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
      ex.shutdown();
    


  51. What is Callable and Future in Java concurrency?

    Callable, an interface, was added in Java 5. It allows you to define a task to be completed by a thread asynchronously. The Callable interface has a call() method, since it is a generic interface so it can return any value (Object, String, Integer etc.) based on how it is initialized. Main feature of the call() method provided by Callable interface is that it can return value.
    Future interface- A Future represents the result of an asynchronous computation. When you submit a callable task using the submit() method of the ExecutorService, Future object is returned.
    Future provides methods to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.
    get()- get() method retrieves the result of the computation, blocking if necessary for the computation to complete.

    Read more about Callable and Future here.
  52. What is atomic variable in Java?

    In Java concurrency classes like AtomicInteger, AtomicLong are provided with a int, long value respectively that may be updated atomically.
    These atomic variable classes in Java concurrency like AtomicInteger, AtomicLong uses non-blocking algorithm. These non-blocking algorithms use low-level atomic machine instructions such as compare-and-swap instead of locks to ensure data integrity under concurrent access.

    Read more about AtomicInteger here.

Related Topics

  1. Java OOP Interview Questions And Answers
  2. Core Java Basics Interview Questions And Answers
  3. Java String Interview Questions And Answers
  4. Java Exception Handling Interview Questions And Answers
  5. Java Multithreading Interview Questions And Answers
  6. Java Collections Interview Questions And Answers
  7. Java Lambda Expressions Interview Questions And Answers
  8. Java Stream API Interview Questions And Answers

Sunday, May 22, 2022

Core Java Basics Interview Questions And Answers

  1. What are JVM, JRE and JDK?

    JVM

    JVM meaning Java Virtual Machine is an abstract layer between a Java program and the platform that Java Program is running on.
    JVM is platform dependent and different implementations of JVMs are available for specific platforms.

    JRE

    JRE meaning Java Runtime Environment provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language.

    JDK

    JDK meaning Java Development Kit is a superset of the JRE, and contains everything that is in the JRE, plus development tools such as the compilers and debuggers necessary for developing applets and applications.

    Read more about JVM, JRE and JDK here

  2. What is bytecode in Java or Why java is called platform independent?

    Java programs are both compiled and interpreted which means-
    When we do javac javaprogram, the java source code is compiled into a .class file which is actually a bytecode. The generated bytecode is portable and it's format is same across platforms.
    After compilation, the interpreter reads the generated byte code & transforms it according to the native platform.
    The compiled bytecode doesn't run on CPU directly, JVM sits in between and interpret the bytecode into readable machine language for the CPU. So Java program is platform independent but JVM is platform dependent and different implementations of JVMs are available for specific platforms.


  3. Java is pass by value or pass by reference?

    Java is pass by value for both primitive types as well as for objects.

    Read more about Java pass by value or pass by reference here

  4. What is package in Java?

    A package is a namespace that organizes a set of related classes and interfaces. Packages also help in  preventing naming conflicts.
    Packages also provide visibility control mechanism. You can define classes and class members inside a package that are not visible to the classes in other packages.

    Read more about Package in Java here

  5. What are access modifiers in Java?

    Access level modifiers are used to control the visibility of the class or the members of the class i.e. fields and methods.

    Types of Access Modifiers

    • private- private modifier specifies that the member can only be accessed in its own class.
    • default (or package-private)- If no specifier is used (which is known as default access) member is visible only within its own package.
    • protected- protected modifier specifies that the member can only be accessed within its own package and by a subclass of its class in another package.
    • public- public modifier specifies that member is visible to all classes everywhere.
    Read more about Access Modifiers here

  6. What all access modifiers can be used with a class?

    At the class level only two of the modifiers can be used, public or default.
    If a class is declared with the modifier public, that class is visible to all classes everywhere.
    If a class has no modifier (the default), it is visible only within its own package.

    Read more about Access Modifiers here

  7. What all access modifiers can be used with class fields?

    All the four types of access modifiers- public, protected, default, private can be used with variables declared in the class.

    • If a field is declared as public then it is visible to all classes in the same package or other packages.
    • If a fields is declared with no access specifier (default) then it can be accessed by any class in the same package.
    • If a field is defined as protected then it is accessible to any class in the same package or to any subclass (of the class where field is declared) in different package.
    • If a field is defined private then that field can only be accessed in its own class.


  8. What all access modifiers can be used with class methods?

    All the four types of access modifiers- public, protected, default, private can be used with methods of the class and access modifier for the methods work the same way as for the fields.


  9. What all access modifiers can be used with constructors?

    All the four types of access modifiers- public, protected, default, private can be used with constructors of the class.

    • In case constructor of the class is private then the object of that class can be created by that class only.
    • In case constructor is marked as protected then a subclass in different package can access the protected constructor.
    • If a constructor is declared with no access specifier (default) then it can be accessed by any class in the same package.
    • If a constructor is declared as public then it is visible to all classes in the same package or other packages.


  10. What is automatic numeric promotion in Java?

    In Java numeric promotion happens in case of primitive types when those primitives are used in an expression.

    For Example

    byte a = 100;
    byte b = 50;
    int i = a * b;
    

    In the above code a * b will exceed the range of its byte operand (range of byte is -128 to 127). In these types of situations Java will automatically promote the byte, short or char to int when evaluating an expression.

    Read more about automatic numeric promotion here

  11. What is constructor?

    In Java there is a special method provided to initialize objects when they are created. This special method which is used for automatic initialization is called Constructor.
    Constructor has the same name as the class in which it is created and defined just like a method, that is, constructor's syntax is similar to a method

    Read more about constructor here.

  12. What is default constructor in Java?

    When a constructor is not explicitly defined for a class, then Java creates a default no-arg constructor for a class that is called default constructor.

    Read more about constructor here.

  13. What is Parameterized Constructor in Java?

    If we want our object's fields to be initialized with specific values, we can do it by adding parameters to the constructor.

    Read more about constructor here.

  14. What is constructor chaining in Java?

    In case when we have a hierarchy of classes (inheritance) the constructors of the classes are invoked in an order. That order is known as constructor chaining.
    For example, If class A is super-class and there is Class B which is subclass of A. In that case if a new instance of class B is created, order in which constructors of Class A and Class B are executed is from super-class to subclass.

    Read more about constructor chaining here.

  15. What is constructor overloading in Java?

    Like method overloading there is also an option to have multiple constructors within the same class where the constructors differ in number and/or types of parameters, that process is known as Constructor overloading.

    Read more about constructor overloading here.

  16. Are constructors from the super class inherited in the sub-class?

    No constructors are not inherited in Java.


  17. What is this in java?

    this in java is a reference to the current object on which the method or constructor was invoked. this can be used inside any method or constructor to refer to the current object.

    Read more about this here

  18. What is super in java?

    The super keyword in java is essentially a reference variable that can be used to refer to its immediate parent class.
    Usage of super-

    • Invoke the constructor of the super class.
    • Accessing the variables and methods of parent class.

    Read more about super here

  19. If there is a parent class A and two child classes class B and class C, can object of type A refer to object of type B or to an object of type C?

    Yes Parent class object can refer to child class object.

    A a;
    B b = new B();
    C c = new C();
    a = b;
    a = c; 
    
    is permissible.

  20. In the above case can child class object hold parent class reference?

    No that will result in compile time error without type casting.

    A a;
    B b = new B();
    b = a;
    

    This will result in error. You will have to typecast it.

    b = (B) a; 
    
    Read more about type casting in Java here

  21. What is instanceof operator?

    An object can only be cast to its own class or one of its super-type, if you try to cast to any other object you may either get a compile-time error or a class-cast exception.

    You can use instanceof operator to check whether the object can be cast to that type safely or not.

    Read more about instanceof operator here

  22. What is interface in Java?

    Interfaces help in achieving full abstraction in Java, as using interface, you can specify what a class should do, but how class does it is not specified.
    Interfaces look syntactically similar to classes, but they differ in many ways-

    • Interfaces don't have instance variables.
    • In interfaces methods are declared with out any body. They end with a semicolon.
    • Interface can't be instantiated.
    • Interfaces don't have constructors.
    • An interface is implemented by a class not extended.
    • An interface can extend multiple interfaces.

    Read more about interfaces here.

  23. Can an Interface be final?

    No, interface can't be final. The whole idea of having an interface is to inherit it and implement it. Having it as final means it can't be subclassed.

    Read more about interfaces here.

  24. Is it possible to declare an interface method static?

    Not before Java 8, from Java 8 it is possible to have interface static methods.

    Read more about interface here and interface static method here.

  25. What are interface default/defender methods?

    With the release of Java 8, it is now possible to add default method in interfaces. With the addition of default method to an interface, addition of new method, to even an interface will not break the pre-existing code.
    An interface default method is defined the same way a method will be defined in a class. One difference is that in interface default method is preceded by the keyword default. For example

    public interface MyInterface {
     int method1();
     // default method, providing default implementation
     default String displayGreeting(){
      return "Hello from MyInterface";
     }
    }
    

    Read more about interface default method here.

  26. Can an Interface implement another Interface?

    No, an interface can't implement another interface. Though, interface can extend another interface.

    Read more about extending interface here.

  27. Can an Interface extend another Interface?

    Yes,interface can extend another interface.

    Read more about extending interface here.

  28. Is it possible to have final method in an interface?

    No, whole idea of interface is to have abstract methods for which implementation is provided by the implementing classes. Making a method as final in interface will mean it can't be overridden which will mean implementing class can't provide an implementation for that method.

    Read more about interfaces here.

  29. Is it possible to define a class inside an interface?

    Yes.An interface can have an inner class. That class will be accessed by using interfaceName.ClassName.


  30. What is a nested interface?

    An interface or a class can have another interface. Such an interface is known as nested interface or a member interface.When a nested interface is used outside, it must be used as a fully qualified name i.e. must be qualified by the name of the class or interface of which it is a member.

    Read more about nested interface here.

  31. What is a marker interface?

    A marker interface is an interface that has no method declarations or fields in it. It is used as a tag to let the compiler know it needs to add some special behavior to the class implementing marker interface. That is why marker interface is also known as tag interface.

    Read more about marker interfaces here.

  32. What is an abstract class?

    An abstract class is a class that is declared using the abstract keyword. An abstract class may contain methods without any implementation, called abstract methods.

    Read more about abstract class here.

  33. Is it possible to have abstract method in a class that is not abstract?

    No. If there is even a single abstract method in a class that class has to be declared as abstract.

    Read more about abstract class here.

  34. Is it possible to instantiate an abstract class?

    No. An abstract class can not be instantiated on its own, but abstract class can be used to create object references.

    Read more about abstract class here.

  35. Is it possible to have an abstract class without any abstract method?

    Yes. Even if there are no abstract methods in a class that class can still be declared as abstract. That abstract class still can not be instantiated.

    Read more about abstract class here.

  36. Can you use abstract and final both with a method?

    No. The whole idea of having a abstract method in a class is that it would be implemented by the inheriting class. Whereas making a method final means it can't be overridden thus can't be provided implementation in inheriting class. So using both of them is not possible.

    Read more about abstract class here and about final here

  37. What are the differences between abstract class and interface?

    Abstract Class Interface
    Methods Abstract class can have both abstract and non-abstract methods. Interface can have abstract methods only.
    Note: From Java 8 interfaces can have default methods and static methods.
    Access Modifiers Abstract class methods can have public, protected, private and default modifier apart from abstarct methods. In interface methods are by default public abstract only.
    Variables Abstract class fields can be non-static or non-final. In interface all the fields are by default public, static, final.
    Implementation Abstract class may have some methods with implementation and some methods as abstract. In interface all the methods are by default abstract, where only method signature is provided. Note: From Java 8 interfaces can have default methods and static methods.
    Constructor Abstract class have a constructor, it may be user supplied or default in case no constructor is written by a user. Interface can't have a constructor.
    Multiple Inheritance Abstract class can extend at most one class and implement one or more interfaces. Interface can only extend one or more interfaces.
    Abstraction Abstract class can provide both partial or full abstraction. Interface provides full abstraction as no implementation is provided for any of the method.
    Extends/Implements Abstract class are extended by the sub-classes. Sub-classes need to provide implementation for all the abstract methods of the extended abstract class or be declared as abstract itself. Interface is implemented by a class and the implementing class needs to provide implementation for all the methods declared in an interface. If a class does not implement all the methods of interface then that class must be declared as abstract.
    Easy to evolve Abstract class was considered easy to evolve as abstract classes could add new methods and provide default implementation to those methods. Interface was not considered easy to evolve as, in the case of adding new method to an interface, all the implementing classes had to be changed to provide implementation for the new method. With Java 8 even interfaces can have default methods so that issue has been addresses.


  38. Why multiple inheritance not supported through Java?

    Multiple inheritance by extending several classes is one feature omitted in the Java language as the designers of the Java language opined that multiple inheritance is a confusing feature and it causes more problems than it solves.

    One of the reason given for omitting multiple inheritance is to avoid “diamond problem” which is one of the classic multiple inheritance problem.

    Read more about why multiple inheritance is not supported in Java here.

  39. What is diamond problem in Java?

    Refer https://www.netjstech.com/2017/06/why-no-multiple-inheritance-in-java-diamond-problem.html to read about diamond problem in Java.


  40. Can we implement more than one interfaces in Java?

    Yes in Java you can implement more than one interface.


  41. What is Static variable in Java?

    A variable declared as static is associated with the class rather than with any object. When objects of its class are created, copy of static variable is not created per object. All objects of the class share the same static variable.

    Read more about static keyword here.

  42. What is static method in Java?

    A static method is associated with the class rather than objects of the class. Static method can be called directly with the class name ClassName.static_method() rather than with the object of the class.

    Read more about static method here.

  43. What is static block in Java?

    A static block in a class is executed only once, when the class is first loaded, even before the main method.

    Example of static block

    public class StaticDemo {
    // static blank final variable
     static final int i;
     static int b;
    static {
      System.out.println("in static block");
      i = 5;
      b = i * 5;
      System.out.println("Values " + i + " " +  b);
     }
    }
    
    Read more about static block here.

  44. Can we have static variable inside a method?

    No. Since static variables belong to a class where as variables declared inside a method are local variables and belong to that method. So variables inside a method can be declared as final, but not static, public, protected or private.

    Read more about static keyword here.

  45. Why can't we access non-static variable from static method?
    OR
    Why non-static variable can not be accessed from main method in Java?

    Static methods or fields can be accessed without even creating an instance of the class, we just need to qualify the static member with the class name and access it. But non-static members need instance of the class to be created to come into existence. That is the reason why non-static field or method can not be called from the static context.

    Read more about Static reference to the non-static method or field error here.

  46. Can we overload static method?

    Static methods can be overloaded just as 'instance methods'. So it is possible to have two or more static methods having the same name, but the parameters are different in types or number.

    Read more about static overloading here.

  47. Can we override static method?

    Static methods can not be overridden in Java. Though it is possible to have a static method with same signature in sub-class but in that case sub-class method hides the super class method rather than overriding it.

    Read more about static method overriding here.

  48. Why main method is static in Java?

    When a class is loaded JVM needs an entry point (main method). JVM needs to access that main method with out creating an instance of the class, that is why main method is static.
    If it is not declared as static then instance of the main class has to be created which may cause ambiguity.

    public class A {
     private int i;
     A(int i){
      this.i = i;
     }
     public static void main(String args[]){
     }
    }
    

    Here in the class there is a constructor with one argument i. Now in order to create an object of the class what should be passed as i? To avoid these types of ambiguities it doesn't make sense for the JVM to have to create an object of the class before the entry point (main method) is called. That's why main method is static.

    Read more about Why main method is static here.

  49. What is static import in Java?

    In order to access any static member (static field or method) of the class, it is necessary to qualify references with the class they came from.
    As example- ClassName.static_method()

    With static import feature of Java 5, members defined in a class as public static can be used without qualifying it with the class name, in any Java class which does a static import. This shortens the syntax required to use a static member.

    Read more about static import in Java here.

  50. What is final in Java?

    final keyword in java has its usage in preventing the user from modifying a field, method or class.

    • final field- A variable declared as final prevents the content of that variable being modified.
    • final method- A method declared as final prevents the user from overriding that method.
    • final class- A class declared as final can not be extended thus prevents inheritance.

    Read more about final keyword here.

  51. What is a final blank variable?

    A final variable can be initialized only once but it can be done in two ways.

    • Value is assigned when the variable is declared.
    • Value is assigned with in a constructor.
    A final variable that has not been assigned a value while declaring a variable is called blank final variable, in that case it forces the constructor to initialize it.

    Read more about final keyword here.

  52. What if a list is declared as final, is it possible to add or remove values from that list?

    When an object reference variable is declared as final, object fields can still be changed but the reference can't be changed.
    So yes it is possible to add or remove values from the list even if the list is declared as final.

    But we can't change the reference of that list. For example

    final List tempList = new Arraylist();
    tempList.add("1"); // permitted
    tempList = new ArrayList()// This will result in an error as we are trying to change the reference
    

  53. What is a final method?

    A method can be declared as final in order to avoid method overriding. Method declared as final in super class cannot be overridden in subclass.

    Read more about final method here.

  54. What is a final class?

    A class declared as final can't be extended thus avoiding inheritance altogether.
    If creator of the class is sure that the class has all the required functionality and should be used as it is with out extending it then it should be declared as final.

    Read more about final class here.

  55. What is finalize method in Java?

    If an object need to perform some action before it is garbage collected that can be done using finalize method. In finalize method we can provide the actions to release the resources before the object is destroyed.

    finalize method is provided as a protected method in the Object class.

    protected void finalize() throws Throwable
    
    Read more about finalize method here.

  56. When is finalize method called?

    The finalize method is called by the garbage collector when it determines no more references to the object exist.

    Read more about finalize method here.

  57. Can we use the finalize method provided by the Object class?

    The finalize method of class Object performs no special action; it simply returns normally.

    Subclasses of Object class should override finalize method and provide the required implementation.

    Read more about Object class here.

  58. What are the best practices for overriding finalize method?

    If overriding finalize() it is a good programming practice to use a try-catch-finally statement and to always call super.finalize().

    Read more about finalize method here.

  59. What is covariant return type?

    Before Java 5, when you override a superclass method in a subclass the method signature had to be exactly same, i.e., the name, argument types and return type of the overriding method in the sub-class had to be exactly same as that of the super-class method.

    This is relaxed a bit in Java 5 in case of return type. The sub-class method's return type may be different from super-class method's return type but the return type of the subclass should be a subtype of return type of super class method. Which means, if method in the super-class has return type R1 and the overriding method in the subclass has return type R2 then R2 must be the subtype of R1. That is known as covariant return type.

    Read more about covariant return type here.

  60. What is strictfp in Java?

    strictfp is a keyword in Java that restricts floating-point calculations to ensure portability. Prior to JVM 1.2, floating-point calculations were strict; which meant, all intermediate floating-point results were represented as IEEE single or double precisions only. As a consequence, errors of calculation (round-off errors), overflows and underflows would occur with greater frequency than in architectures which did intermediate calculations in greater precision.

    Since JVM 1.2, intermediate computations are not limited to the standard 32 bit and 64 bit precisions. On platforms that can handle other representations e.g. 80-bit double extended on x86 or x86-64 platforms, those representations can be used, helping to prevent round-off errors and overflows, thereby increasing precision.

    Read more about strictfp in Java here.

  61. What is serialization and deserialization in Java?

    Object serialization is the mechanism of converting object into byte stream. Where as the reverse process of constituting the object from those bytes is known as deserialization.

    Read more about serialization in Java here.

  62. What are the benefits of serialization?

    Once an object is converted to a byte stream those bytes can be -

    • Transmitted from one JVM to another where the object can be reconstituted using those bytes and used in further processing.
    • Stored on a disk/DB for further use.
    Read more about serialization in Java here.

  63. When a serialized object is transmitted across the network where different operating system is used will it work?

    Yes serialization offers that portability. When a serialized object is transmitted across the network the serialization mechanism will take into account the differences in operating systems. Thus an object converted into byte streams in Windows OS can be transmitted across the network and deserialized into an object in the Unix operating system.

    Read more about serialization in Java here.

  64. What is Serializable interface in Java?

    Serializable interface is a marker interface and does not have any field or method. It is part of java.io package.
    Any class whose object has to be serialized should implement Serializable interface.

    Read more about marker interface here.

  65. Suppose I have a Person class in which Address class object is referred. Person class implements Serializable interface but Address class doesn't. Will you be able to serialize a Person object in that case?

    No, in this case you will get exception (java.io.NotSerializableException) when you try to serialize the Person class object.
    All the classes which are to be serialized should be implementing Serializable interface. Since in this case Address class whose object is used in Person class doesn't implement Serializable interface an exception will be thrown.


  66. What is ObjectOutputStream class?

    An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. This class provides writeObject method which is used to write an object to the stream.

    Read more about ObjectOutputStream class here.

  67. What is ObjectInputStream class?

    An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. This class provides readObject method which is used to read an object from the stream.

    Read more about ObjectInputStream class here.

  68. What if you provide your own writeObject() and readObject() methods?

    If you want to have some control over the process of serialization and deserialization rather than using the default serialization mechanism which for us, as end user, is automatic then you can add your own implementation of writeObject() and readObject() methods.

    If you add methods writeObject() and readObject(), these methods will be called automatically when the object is serialized and deserialized respectively and provide the serialization mechanism rather than using the default mechanism.


  69. What is transient keyword in Java?

    If you want to exclude any object field from getting serialized you can use transient keyword along with that field. Note that you cannot use transient keyword with methods or local variables it can only be used with member variables.

    Read more about transient here.

  70. What is Externalizable interface in Java?

    Externalizable interface extends the Serializable interface and adds two methods writeExternal() and readExternal(). When you use Externalizable for your serialization, you will implement Externalizable interface and implement writeExternal() and readExternal() methods. These two methods will be called while serializing and deserializing respectively.

    Read more about Externalizable interface here.

  71. How is the class object serialized if it implements Externalizable interface?

    An object which is to be serialized is tested for the Externalizable interface. If the object supports Externalizable, the writeExternal method is called. If the object does not support Externalizable and does implement Serializable, the object is saved using ObjectOutputStream.

    When an Externalizable object is reconstructed, an instance is created using the public no-arg constructor, then the readExternal method called. Serializable objects are restored by reading them from an ObjectInputStream.

    Read more about Externalizable interface here.

  72. What are the conditions when class implements Externalizable interface?

    A default no-arg constructor has to be there in the class while using externalizable as object is created using no-arg constructor while deserializing and then the object is initialized using the logic in readExternal() method.

    Order that is used in writeExternal() method for writing the fields should be maintained in readExternal() method.

    Read more about Externalizable interface here.

  73. What is serialVersionUID?

    The serialVersionUID helps in versioning in a Serializable class. serialVersionUID is declared as a private static final long field in the serializable class.
    Suppose you have some class which is serialized and it changes before it is deserialized. If serialVersionUID was generated for the class when serializing it then the generated serialVersionUID while deserializing will differ as the class has changed.

    Read more about serialVersionUID and how it helps with version control here.

  74. How is serialVersionUID generated?

    The stream-unique identifier is a 64-bit hash of the class name, interface class names, methods, and fields. If you are using IDE like eclipse that will give you an option to add generated serialVersionUID or to add default serialVersionUID.
    If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class.

    Read more about serialVersionUID and how it helps with version control here.

  75. What is Serialization Proxy pattern?

    Its a way of designing your class where proxy pattern defines its serialization mechanism. Rather than serializing the original class you provide functionality to serialize the proxy class instead. For the class which has to be serialized a proxy class is also created which is then serialized instead of the original class.
    In serialization Proxy pattern writeReplace() method and readResolve() methods are used for serialization.

    Read more about Serialization Proxy pattern here.

  76. What is writeReplace() method?

    Serializable classes that use an alternative object (proxy object) when writing an object to the stream should implement writeReplace() method with the exact signature:

    ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException;
    
    This writeReplace() method is invoked by serialization if the method exists and this method is defined within the original class whose object is serialized.

    Read more about Serialization Proxy pattern here.

  77. What is readResolve() method?

    Using serialization proxy pattern you serialize the proxy class instead of the original class. At the time of deserializing it should create the original class object. Thus the classes that need to provide a replacement object when the serialized object is read from the stream should implement readResolve() method with the exact signature.

    ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;
    

    Read more about Serialization Proxy pattern here.

  78. How does Serialization Proxy pattern work?

    Rather than serializing the original class you provide functionality using the writeReplace() method to serialize the proxy class instead. writeReplace() method is implemented in the original class.

    At the time of deserialization proxy object is deserialized and then the readResolve() method is called. That’s where you will have to provide the functionality to create the original class object regular way. readResolve() method is implemented in the proxy class.

    Read more about Serialization Proxy pattern here.

  79. What is cloning process?

    If you want to quickly create an object using the existing object in such a way that you get a new instance (where the reference between the objects is not shared) with the same content for the fields in the new object as in existing object. Then you can clone the existing object to create an exact copy.


  80. How is cloning of the object done in Java?

    In Java you can use clone() method to create an exact copy of the existing object.
    clone() method is defined as protected in the Object class which you must override as public in any derived classes that you want to clone.
    Signature of clone method in Object class- protected native Object clone() throws CloneNotSupportedException;

    Read more about Object cloning in Java here.

  81. What is Cloneable interface?

    Your class, whose object you want to clone, must implement Cloneable interface which is part of java.lang package. Not implementing Cloneable interface will result in CloneNotSupportedException exception being thrown when clone method is called.

    Read more about Object cloning in Java here.

  82. What all methods are there in Cloneable interface?

    Cloneable interface is a marker interface and defines no members of its own.

    Read more about marker interface here.

  83. What are the steps in cloning process?

    There are two required steps if you want to clone any object.

    • You need to call clone() method of the Object class or provide your own implementation by overriding the clone() method in your class.
    • Your class, whose object you want to clone, must implement Cloneable interface.

    Read more about Object cloning in Java here.

  84. What are the advantages of cloning?

    If you have an object, creation of which using the usual way is costly; as example if you have to call DB in order to get data to create and initialize your object. In that scenario rather than hitting DB every time to create your object you can cache it, clone it when object is needed and update it in DB only when needed.


  85. What is Shallow copy?

    If the class whose object you want to clone has reference to other class objects then those reference are shared.
    When you clone an object all the values for the fields are copied to the cloned object. Since Java is pass by value, if the field value is a reference to an object (a memory address) it copies that reference to the field of the cloned object. In that case referenced field is shared between both objects and any change made to the referenced field will be reflected in the other object too.
    This process of cloning when the field values are copied to the new object is known as shallow copy.

    Read more about Shallow copy here.

  86. What is deep copy?

    If you don’t want references of object being copied during the cloning process then option is deep copy. When a deep copy is done objects referenced by the cloned object are distinct from those referenced by original object, and independent.
    Deep copies are more expensive, as you need to create additional objects, and can be substantially more complicated, due to references possibly forming a complicated graph.

    Read more about deep copy here.

Related Topics

  1. Java OOP Interview Questions And Answers
  2. Java String Interview Questions And Answers
  3. Java Exception Handling Interview Questions And Answers
  4. Java Multithreading Interview Questions And Answers
  5. Java Collections Interview Questions And Answers
  6. Java Concurrency Interview Questions And Answers
  7. Java Lambda Expressions Interview Questions And Answers
  8. Java Stream API Interview Questions And Answers