Top Java 8 Interview Questions and Answers

Posted in /   /  

Top Java 8 Interview Questions and Answers

Vinay Khatri
Last updated on September 27, 2022

    Java is one of the most popular and widely used programming languages. Many organizations use it for web, desktop, and mobile app development, which is why Java Developers are always in demand.

    With so many high-level programming languages thriving in the market, Oracle Corporation, which is the developer of Java, releases a new version of Java every year to ensure that the programming language stays competitive in the market.

    The new versions or updates do not change the complete syntax; they are only supposed to bring new advanced features in Java. Also, many new versions are intended to solve the bugs or issues present in the preceding versions.

    Nonetheless, what we are going to discuss in this article are some of the most popular Java 8 interview questions that can help you land a well-paying job. Also, you need to know that Java 8 is among the most popular versions of Java that many developers learn to get started with Java.

    Top Java 8 Interview Questions

    The current version of Java is Java 17, but here we have covered the Java 8 interview questions because Java 8 is the most used and stable Java version and most organizations use it for their projects. Following are the most commonly asked Java 8 interview questions:

    Basic Java 8 Interview Questions

    1. Name the new features which were introduced in Java 8.

    • Lambda Expression
    • Default methods in the interface
    • Functional Interface
    • Optional
    • Method references
    • Date API
    • Stream API
    • Nashorn, JavaScript Engine
    • javac Enhancements
    • JVM Changes
    • Java 8 Compact Profiles: compact1,compact2,compact3
    • JDBC 4.2
    • JAXP 1.6
    • Java DB 10.10
    • Networking

    2. What are the major advantages of using Java 8?

    Here are the key advantages that developers get while working with Java 8:

    • Compact coding
    • Enhanced code reusability
    • Testable code
    • Better utilization of multi-core CPUs
    • Reduced boilerplate

    3. What is the Lambda expression?

    Lambda expression is one of the new features of Java 8 , and it is also known as anonymous functions. Lambda Expression provides an easy and concise way to write the user-defined function in a single line. It comprises a set of parameters and the function body, and we can call it without a name.

    Lambda Expression Syntax: (Argument List) ->{function body;}

    Lambda Expression Example:

     public class ThreadSample {
     public static void main(String[] args) {
      // old way
      new Thread(new Runnable() {
       @Override
       public void run() {
        System.out.println("Thread is started");
       }
      }).start();
      // using lambda Expression
      new Thread(()->System.out.println("Thread is started")).start();
     }
    
    }

    4. Explain the syntax of Lambda Expression.

    The Lambda expression syntax is divided into 3 parts:

    • Arguments
    • Array token
    • Function body or statement

    Argument : The lambda expression is similar to the user-defined function with no name, and as a function, it can accept zero or more than 0 arguments.

    Array token : Array token is a special symbol, represented by ->, and it acts as a separator between the arguments and function body.

    Body : The body contains the expression or statement, and it resides in curly braces.

    Example:

    (int a,int b)-> {a+b};

    Here a and b are two integer arguments, -> symbol is the array token, and a+b is the function body or statement.

    5. What is the type of Lambda Expression?

    In other high-level programming languages that support first-class functions, the type of a Lambda expression is a function. However, Java 8 represents the Lambda expression as an object. Also, when we define a lambda expression in Java, it must be bound to a particular object type which is known as a functional interface.

    6. Give some advantages of Lambda Expressions.

    The use of Lamba expressions helps to:

    • Increase code conciseness.
    • Reduce the code bloat.
    • Enhance code readability and reusability.
    • Eliminate the use of unnecessary variables.
    • Simplify variable scope.
    • Minimize boilerplate codes.

    7. What is the target type of a Lambda Expression?

    The functional interface for which the Lambda Expression has been invoked becomes its target type.

    Example:

    interface TT 
    {
       // interface body
    }
    TT le = (x,y) -> {//};

    here TT is the target type of lambda expression le .

    8. What is StringJoiner?

    StringJoiner is the new class introduced in Java 8 which is used to join the string using a delimiter. We can also use prefix and suffix with StringJoiner to add a specific string at the beginning and end of a string.

    Example:

    StringJoiner joiner = new StringJoiner(",", PREFIX, SUFFIX);

    9. What are the Functional Interfaces?

    Functional Interfaces were first introduced in Java 8, and they allow users to define exactly one abstract method inside the interface. These interfaces are also known as Single Abstract Method Interface (SAM interface). To create a functional interface in Java, we can either use Lambda expressions, method references, or constructor references.

    10. Relate Lambda Expression with Functional Interfaces.

    Using the lambda expression, we can apply the abstract method in an interface to create a functional interface.

    11. Why do we need a Functional Interface in Java?

    In Java 8, a functional interface was introduced to implement the concept of Lambda expression. So, an abstract method can be implemented with a Lambda expression.

    12. How can you create your Functional Interface?

    Java can implicitly identify functional interface, however, we can also annotate it with @FunctionalInterface.

    Example:

    @FunctionalInterface
    interface CustomFunctionalInterface {
       void display();
    }
    public class FunctionInterfaceLambdaTest {
       public static void main(String args[]) {
          // Using Anonymous inner class
          CustomFunctionalInterface test1 = new CustomFunctionalInterface() {
             public void display() {
                System.out.println("Display using Anonymous inner class");
             }
          };
          test1.display();
          // Using Lambda Expression
          CustomFunctionalInterface test2 = () -> {    // lambda expression
             System.out.println("Display using Lambda Expression");
          };
          test2.display();
       }
    }

    13. Is it necessary to mention the annotation @FunctionalInterface to define a Functional Interface?

    Even if we do not mention the @FunctionalInterface, the compiler would not throw any error, so it’s completely the choice of developers whether they mention the annotation or not. However, it’s a good practice to mention the annotation. If we mention an interface with @FuntionalInterface and try to create more than one abstract method, the compiler would throw an error.

    14. What is the key difference between collections and stream API?

    The collection is used to store and group the data in a proper data structure , whereas the stream is used to perform data operations on that data.

    15. Mention some of the Limitations of Stream API in Java 8?

    Following are the key limitations of Stream API:

    • If we use a parallel stream when lambda expressions are stateful, this could result in a random response.
    • A Stream cannot be used later once it has been consumed.
    • There are too many complex methods in Stream API which make it hard to learn.

    16. What is Spliterator?

    Basically, it is an Iterator like Java Iterator and ListIterator, which is used to iterate elements from a collection, an I/O channel, or a Generator function. It is introduced in Java 8 and defined as an interface in Java collection API, and it resides in java.util package. It uses tryAdvance() method to iterate in multiple threads for parallel processing and forEachRemaining() method for a single thread.

    17. What is the key difference between Iterator and Spliterator?

    We can use the Spliterator with Stream, whereas we can only use iterator with collections. Spliterator gives support for sequential and parallel iteration. On the other hand, iterator only supports sequential iteration.

    18. Comment on method reference in Java 8.

    Method reference feature is introduced in Java 8, and it is used to refer to the method of functional interface. It can also be considered as an easy and compact form of the lambda expression.

    Example:

    interface Sayable{ 
        void say(); 
    } 
    
    public class MethodReference { 
        public static void saySomething(){ 
            System.out.println("Static Method."); 
        } 
        public static void main(String[] args) { 
            // Referring static method 
            Sayable sayable = MethodReference::saySomething; 
            // Calling interface method 
            sayable.say(); 
        } 
    }

    19. How to access the name of the parameter?

    In Java 8, we have a class java.lang.reflect.parameter that helps us to get the information related to the parameter's name and its modifiers.

    20. What is the O ptional class in Java 8?

    In Java 8, to avoid the NullPointerException, developers use the Optional class from the java.util.package. With the Optional class, we can write readable and compact code without using too many null checks. Also, we can specify the alternative values to return or alternative code to run.

    Example:

    import java.util.Optional;  
    public class Optional_Class{  
        public static void main(String[] args) {  
            String[] words = new String[10];  
            Optional<String> checkNull = 
                          Optional.ofNullable(words[5]);  
            if (checkNull.isPresent()) {  
                String word = words[5].toLowerCase();  
                System.out.print(word);  
            } else 
                System.out.println("Null Word");  
        }  
    }

    21. Name the method provided by the option for the fallback mechanism in case of a null value.

    If there is a null value in the option, we can use the orElseGet() method as a fallback mechanism.

    22. Comment on the Static method in the Interface.

    Inside an Interface, if we define a method with a static keyword, it would be considered as a static method. The static method contains the full definition of the method, and the class which implements the interface cannot override the interface static method.

    Intermediate Java 8 Interview Questions

    23. What are the default methods?

    The concept of the default method introduced in Java 8 allows the interface to have methods without affecting the class that implements the interface. To define a default method in an interface, we use the default keyword and the class which implements the interface can access the default method with the class instance. By using the class itself, a user can also override the default method.

    Example:

    public interface Story {
        default void tell(){
            System.out.println("story telling");
        }
    }
    
    public class People implements Story{
        public static void main(String[] args){
            People person = new People();
            person.tell();
        }
    
    }

    24. Why do we require Default methods?

    In earlier versions of Java, when we do not have the default methods, we have to use the abstract method in the interface. The main problem with the abstract methods and interface was that the code has to be provided in the class which is implementing the interface if there is a new method introduced in the interface. To solve this problem and improve the backward compatibility of the class with the interface, default methods were introduced.

    25. What is the difference between Predicate and Functions?

    The predicate interface accepts an argument and returns a Boolean value, whereas the function interface returns an object value. The predicate has a method named test(), which tests the passed argument and also tests for the condition. On the other hand, Function has a method named apply(), which applies logic on the passed argument.

    Syntax: Predicate<T>

    Here T represents the object type of the input or argument. Function <T, R>: Here T is the type of the object passed to the function and R is the type of return object

    Example:

    Function<String, Integer> length = str -> str.length();
    Predicate gt_lt = i -> i>0 ;

    26. What is the major difference between Internal and External iterator?

    In general, programmers control the external iterator, whereas the iterator itself controls the internal iterator. Internal iterator reduces the chances of error in code, thus making the code more readable, whereas the possibility that the user can commit some error is high with the external iterator.

    27. Name the drawbacks of old date-time APIs which were solved with Java 8.

    • Unsafe Threads: Before Java 8, java.util.Date was mutable and not thread-safe. However, with Java 8 new date-time APIs, we get immutable and safer thread date APIs.
    • Few Operation: There were limited operations and methods for the old Date APIs, but with new Java 8 date APIs, we get many new operations.

    28. Name some Data and Time APIs of Java 8.

    • LocalDate/LocalTime and LocalDateTime API: These APIs are ideal to use when we do not require a time zone.
    • ZonedDateTime API: We use this API when we require a time zone.
    • Period and Duration: These APIs deal with the amount of time.
    • ChronoUnit: ChronoUnit allows the replacement of the integer values used in old APIs to represent the date, month, and year.
    • TemporalAdjuster: This API is suitable for date-related operations.

    29. How can we get the difference between the two dates?

    To get the difference between two days or to get the duration between two dates, we can use the Java 8 Period Class.

    Example:

    Period duration = Period.between(date_1, date_2);

    30. Name the method introduced in Java 8 to process Arrays on multi-core machines.

    The new arrays parallel method introduced in Java 8 for parallel processing of Arrays on the multi-core machines are as follows:

    • parallelSetAll()
    • parallelSort()

    31. What is the diamond problem of multiple inheritances?

    Consider this C++ class for example:

    class A {
    public:
         void fun() { ... }
    }
    class B extends A {}
    class C extends A {}
    class D extends B, C {}

    Here the class D can access the class A method fun(), but if the class B and C override the fun() method in their scope, then the ambiguity will arrive in method resolution by Class D . This ambiguity of method accessing can lead to a trap in multiple inheritances, which is known as a diamond problem.

    32. How does the Java 8 update deal with the diamond problem of multiple inheritances?

    Java 8 interface set the following rules for multiple inheritances to tackle the diamond problem:

    • The inherited method from a class would be given priority over the default method inherited from an interface.
    • Derived interfaces take higher precedence than the interfaces higher-up in the inheritance hierarchy.
    • After following the above two rules, if the problem still persists, then implementing class has to override the method.

    Advance Java 8 Interview Questions

    33. Write a code to get the current date and time using Java 8 date and time APIs.

    import java.time.*;
    import java.time.format.DateTimeFormatter;
    
    public class Date {
    public static void GetTimeandDate()
    {
        LocalDate date = LocalDate.now();     // the current date
        System.out.println("the current date is "+date);
        LocalTime time = LocalTime.now();     // the current time
        System.out.println("the current time is "+ time);
    }
    
        // Main Function
        public static void main(String[] args) 
        {
            GetTimeandDate (); // calling the method
        }
    }

    34. What is Metaspace?

    Metaspace is a new concept in Java 8 to replace the concept of PermGen (Permanent Generation) memory space. Java 8 introduced a new memory space known as Metaspace that handles the memory allocation of the classes and gives better results for the native memory region.

    35. What is PermGem? Do we still have it in Java 8?

    We do not have PermGem in Java 8, it got replaced by the Metaspace. PermGen stands for Permanent Generation, and it is a special heap space that is separated from the main memory heap. Before Java 8, the Java Virtual Machine would use PermGen to keep track of the loaded class and to store all the static content in the memory section.

    36. Use only Java 8 APIs, and write code for this statement- “You have given a list of students and you need to filter out all the students whose marks are greater than 1000 and you also need to print their name”.

    //essential imports
    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;
    
    //Code Logic
    List<String> StudentsFilter = Students_List.stream().filter(s->s.Marks()>1000).map(Students::Names).collect(Collectors.toList());

    37. With the help of Java 8 APIs write code to solve this statement- “You have given a list of Students, print the number of students who get marks less than 400.”

    //Code Logic
    
    List<Students> StudentsList = createStudentsList();
    long count = StudentsList.stream().filter(s->s.Marks()>25).count();
    
    System.out.println("There are  " +count +"students who score less than 500");

    38. With the help of Java 8 APIs write a code to solve this statement- “You have given a list of Students, find all the students with the name Luffy.”

    //Code Logic
    
    List<Students> StudentsList = createStudentsList();
    Optional<Students> s = StudentsList.stream().filter(s->s.Name().equalsIgnoreCase("Luffy")).findAny();
    if(s.isPresent())
         System.out.println(s.get());

    39. With the help of Java 8 APIs write a code to solve this statement- “You have given a list of Students, you need to find the student which scores the highest marks.”

    List<Students> StudentsList = createStudentsList();
    OptionalInt highest = StudentsList.stream().mapToInt(Students::Marks).max();
    
    if(max.isPresent())
           System.out.println("The highest score is: "+ highest.getAsInt());

    40. With the help of Java 8 APIs write a code to solve this statement- “You have given a list of Students, sort all the students based on their rank.”

    List<Students> StudentsList = createStudentsList();
    StudentsList.sort((s1,s2)->s1.rank()-s2.Marks());
    StudentsList.forEach(System.out::println);

    41. With the help of Java 8 APIs write a code to solve this statement- “you have given a list of Students, now join all the student's name with a comma(,).”

    //Code logic
    
    List<Students> StudentsList = createStudentsList();
    List<String> StudentsNames = StudentsList.stream().map(Students::Name).collect(Collectors.toList());
    String names = String.join(",", StudentsNames);
    System.out.println("All Students : "+names);

    42. With the help of Java 8 APIs write a code to solve this statement- “You have given a list of Students, group them all by their names ”

    //Essential Imports
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    //Code Logic
    List<Students> StudentsList = createStudentsList();
    Map<String, List<Students>> map = StudentsList.stream().collect(Collectors.groupingBy(Students::Name));
    map.forEach((name,Student_List)->System.out.println("Name: "+name+" ==>"+ Student_List));

    43. What is the difference between intermediate and terminal operations in the stream?

    If a stream operation returns another stream as a result, it becomes an Intermediate stream operation. If a stream returns a non-stream value, such as primitive or object or the collection, or returns nothing, then it becomes a terminal stream operation.

    Examples of Intermediate Operations:

    • filter(Predicate)
    • map(Function)
    • flatmap(Function)
    • sorted(Comparator)
    • distinct()
    • limit(long n)
    • skip(long n)

    Examples of terminal Operations:

    • forEach
    • toArray
    • reduce
    • collect
    • min
    • max
    • count
    • anyMatch
    • allMatch
    • noneMatch
    • findFirst
    • findAny

    44. With the help of Java 8 APIs write a code to solve this statement- “You have given a list of numbers, you need to remove all the duplicates element from the list ”

    import java.util.Arrays;
    import java.util.List;
    import java.util.Set;
    import java.util.stream.Collectors;
    public class OnlyUniqueElements {
                    public static void main(String[] args)
                    {
                      Integer[] lis=new Integer[]{20,40,70,90,20,20,40,80,70,50,60,10};
                      List<Integer> List_with_Duplicate = Arrays.asList(lis);
    
                       Set<Integer> Set_without_dups = List_with_Duplicate.stream().collect(Collectors.toSet());
                       Set_without_dups.forEach((i)->System.out.print(" "+i));
                    }
    }

    45. What is the difference between findFirst() and findAny()?

    The findAny() method helps us to find any element from a Stream. We use it when we are not concerned about the element order, and this method returns an Optional instance. The findFirst() method finds the first element in the stream. We use this method when we want to find the first element from the sequence, or when we are concerned with the element order,

    46. With the help of Java 8 APIs write a code to solve this statement-  “you have given a list of numbers, you need to square them and filter out the number which is greater than 20000 and then you also need to find their average”

    import java.util.Arrays;
    import java.util.List;
    import java.util.OptionalDouble;
    
    public class Squares_Average {
        public static void main(String[] args)
          {
             Integer[] lis=new Integer[]{122,250,223,679,500,770,340,382};
             List<Integer> list = Arrays.asList(lis);
     
            //calculating average
            OptionalDouble average = list.stream().mapToInt(n->n*n).filter(n->n>10000).average();
            if(average.isPresent())
                 //printing average as double
                 System.out.println("Your Result is: "+average.getAsDouble());                     
            }
    }

    47. Why do we use the Optional class in Java 8?

    To tackle the problem of NullPointerException in Java 8, we use the Optional class.

    48. What is the predicate function in an interface?

    The predicate function in the interface represents the generic functional interface that accepts a single argument and returns the result as a boolean value. It resides in the java.util.function package.

    49 What is the Consumer interface in Java 8?

    The Consumer interface is a functional interface that resides in java.util.function package. This functional method accepts one argument and does not return any value.

    Example:

    Consumer<String> consumerStr=s->{ System.out.println(s); };

    50. What is the supplier function interface?

    Supplier interface is a functional interface that is a part of java.utils.function package. This functional method does not accept any argument value but returns an object value using the get() method.

    Conclusion

    Java 8 is one of the most stable versions of Java, and many organizations still use it for developing new projects and maintaining their already running applications.

    The Java 8 interview questions discussed in this article can help you prepare better for your upcoming interview. While the Java concepts are quite large in number, it is difficult to remember them, especially if you are a beginner.

    By going through the frequently asked Java 8 interview questions along with their answers, you will be able to refresh your memory pertaining to Java concepts and get mentally prepared for the interview.

    Learn about more Java interview questions by purchasing the course up here .

    People are also reading:

    FAQs


    Java 8 is a major feature release for the Java programming language that comes with new features and improvements and bug fixes. With the release of Java 8, Java started supporting functional programming. Also, it provides a new JavaScript engine, new streaming APIs, and new APIs for date and time manipulation.

    You should learn Java 8 because it is the latest release for Java, which comprises cutting-edge features. Also, it has evolved JVM, libraries, and the Java language itself. The features it provides are intended for improving productivity, security, ease of use, performance, and polyglot programming.

    As a Java developer, you must be proficient in OOPs concepts, system design and architecture, Java build tools, JVM internals, web technologies, Java testing tools, Java EE components, DevOps, and the SOLID principle.

    Yes, you have to be proficient in Java 8 as a Java developer. It is the responsibility of every Java developer to have an in-depth understanding of Java 8 and its features.

    The features of Java 8 that every Java developer should know are Lambda Expressions, Stream API, Method Reference, Default Methods, and Optional Class.

    Leave a Comment on this Post

    0 Comments