1. What is a 'method reference' in Java 8?
The interviewer may ask this question in the initial phase of the interview to test your knowledge of Java 8. Being able to speak eloquently on specific features of Java 8 is important for you to showcase you possess the skill set to be a good programmer. To answer this question, describe a method reference using adequate detail in a simple format that is clear and easy to understand.
Example: "A method reference in Java 8 is a feature that allows for the definition of Lambda Expressions. This is done by referring to methods using their names."
Related: How to Prepare for a Job Interview
2. Explain 'functional interfaces'.
The interviewers ask this question to check if you have the foundational knowledge required to perform certain tasks with Java 8 that might be necessary for the job. To answer this question, briefly explain the concept and mention any applications you know of.
Example: "A functional interface is an interface that has only one abstract method. These interfaces provide the target for Lambda expressions that implement them."
3. What is a 'SAM interface'?
Sometimes, it's necessary to show you understand basic technical concepts that might be important to the position. To answer this question, briefly explain the concept and add any relevant information you know to highlight your understanding of the concept.
Example: "A Single Abstract Method interface or SAM interface reflects an interface with one abstract method. A SAM interface is also known as a functional interface and both these terms can be used interchangeably."
4. In Java 8, what does 'stream pipelining' mean?
This question tests your understanding of the foundational concepts. To answer this question, restate the concept and then offer a concise definition.
Example: "Stream operations often return themselves for pipelining. When this occurs, an intermediate operation takes them in, processes them and outputs again. At the end of the stream, a collect method usually occurs."
5. What are 'collectors' and 'statistic collectors'?
The interviewers ask this question to check your knowledge on two subjects, collectors and statistic collectors. To answer this question, compare the two briefly.
Example: "On a string of code, collectors work to combine all results from processing. Statistic collectors calculate statistics while processes occur."
6. Explain 'Optional' in Java 8?
This is a concept-based question. When asked to explain a concept, you should describe it in your own words so the interviewer can see how you speak to others in a professional setting. It's an opportunity for you to show a little personality besides strong communication skills.
Example: "Optional is a form of containerisation that holds non-null objects. The Optional object that remains is defined as null with absent value."
7. How does Java 8 achieve platform independence?
The interviewers may ask you this question to check how much you know about Java 8 and if you know the difference between Java 8 and dependent programming languages like C/C++. The recommended way for you to answer this question is by explaining the features that provide platform independence to Java.
Example: “Java achieves platform independence due to features like class files, bytecode and Java Virtual Machine (JVM). Since all Java programs run on JVM, there is no dependence on a particular platform.”
8. How do the 'interface' and 'abstract' classes differ in Java 8?
This is a popular Java 8 interview question. To answer this question, mention the differences between the two classes. You may also mention how Java 8 allows non-abstract methods on the interface.
Example: “'Abstract' is a class that can be modified by non-abstract methods, but the 'interface' cannot have instance variables because it cannot have a state. Another difference between the two is that you can define constructors inside an 'abstract' class, but the same is not possible in the 'interface'.”
Related: Top 16 Interview Questions and Answers
9. Explain the difference between 'transient' and 'volatile' variables.
The interviewers ask this question to check your knowledge about variables in Java. To answer this question, briefly explain the differences between the two types of variables.
Example: “The major difference between these two types of variables is that 'transient' variables are not serialised during the serialisation process, whereas 'volatile' variables are special and get their value from multiple threads within a Java application. A volatile variable's value should always be read from the main memory instead of cached values.”
10. What is the difference between 'wait' and 'sleep' methods in Java 8?
This is a prevalent question often asked in Java 8 interviews. The interviewers ask this question to test your knowledge of the different methods in Java 8. To answer this question well, briefly explain the differences between the two functions.
Example: “Both 'wait' and 'sleep' methods are used to put a thread in a waiting state, but their applications and nature are different. The 'wait' method puts a thread in a waiting state, while the 'sleep' method is used to pause an entire Java application.”
11. How can you override a static method in Java 8?
The interviewers may ask this question to confuse you. The trick here is that you cannot override the static method in Java 8. Interviewers ask you such questions to check your presence of mind and how much attention you pay to details. To answer this question, state clearly that it's not possible to override a static method in Java 8 and explain the reason for it.
Example: “You cannot override a static method in Java because method overriding happens at runtime due to dynamic binding and static methods are bonded using static binding at compile time. Static methods are resolved before the creations of objects, making it impossible to override static methods.”
12. In Java 8, what's the difference between 'this' and 'super' keywords?
This question tests your knowledge of the basic Java 8 concepts. To answer this question, briefly explain the two keywords along with their applications.
Example: “this() represents the current instance of a class and super() represents the current instance of the parent class.”
13. Does Java 8 support multiple inheritances?
The interviewers ask this question to test your knowledge of inheritance. To confidently answer such a question, pause and think for a moment. The important thing here is to understand the language of the question. Once you are clear about the concept being tested, you can answer such questions easily.
Example: “No, Java 8 does not support multiple inheritances. The reason behind this is to avoid ambiguity in cases where multiple child classes may inherit similar properties, making it unclear for the compiler to know which method should be invoked.”
14. Is it possible to access the 'private' method in Java 8?
The interviewers ask this question to check how much you know about access-restriction and encapsulation in Java 8. To answer this question, answer in the affirmative and name the condition that needs to be satisfied for this operation.
Example: “Yes, we can access the 'private' method in Java 8. However, it needs to be in the same class and not outside it.”
15. What are the similarities and differences between 'ArrayList' and 'LinkedList'?
The interviewers ask this question to test your working knowledge of how data structures work in Java 8. To answer this question well, briefly explain the similarities and differences between the two. You may get some follow-up questions about how different methods behave for these two data structures and so it would be a good idea to read up on this.
Example: “If we talk about the similarities, both 'ArrayList' and 'LinkedList' are ordered, index-based and allow duplication. Both these lists are not synchronised, which means you need external synchronisation to share them between multiple threads. Speaking of the differences, the 'ArrayList' depends on an array and 'LinkedList' depends on the linked list data structure, which makes methods like add, remove and contain perform differently for each of the two.
1) What are new features which got introduced in Java 8?
There are lots of new features which were added in Java 8. Here is the list of important features:
- Lambda Expression
- Stream API
- Default methods in the interface
- Functional Interface
- Optional
- Method reference
- Date API
- Nashorn, JavaScript Engine
2) What are main advantages of using Java 8?
- More compact code
- Less boiler plate code
- More readable and reusable code
- More testable code
- Parallel operations
3) What is lambda expression?
Lambda expression is anonymous function which have set of parameters and a lambda (->) and a function body .You can call it function without name.
Structure of Lambda Expressions
1 2 3 4 | (Argument List) ->{expression;} or (Argument List) ->{statements;} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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(); } } |
You can refer to lambda expression in java for more details.
4) Can you explain the syntax of Lambda expression?

1 2 3 4 5 | ()->{System.out.println("Hello")}; //Without argument, will print hello (int a)->{System.out.println(a)} //; One argument, will print value of a (int a,int b)-> {a+b};//two argument, will return sum of these two integers |
1 2 3 | (a,b)->{a+b};//two argument, will return sum of these two numbers |
1 2 3 | (int a,b)->{a+b};//Compilation error |
1 2 3 | a->{System.out.println(a)}; // Will print value of number a |
3. Body
- Body can have expression or statements.
- If there is only one statement in body,curly brace is not needed and return type of the anonymous function is same as of body expression
- If there are more than one statements, then it should be in curly braces and return type of anonymous function is same as value return from code block, void if nothing is returned.
5) What are functional interfaces?
Functional interfaces are those interfaces which can have only one abstract method.It can have static method, default methods or can override Object’s class methods.
There are many functional interfaces already present in java such as Comparable, Runnable.
As we have only one method in Runnable, hence it is considered as functional interface.
You can read more about the functional interface.
Lambda expressions can only be applied to abstract method of functional interface.
For example
Runnable has only one abstract method called run, so it can be used as below:
1 2 3 4 5 6 | // Using lambda expression Thread t1=new Thread( ()->System.out.println("In Run method") ); |
Here we are using Thread constructor which takes Runnable as parameter. As you can see we did not specify any function name here, as Runnable has only one abstract method, java will implicitly create anonymous Runnable and execute run method.
It will be as good as below code.
1 2 3 4 5 6 7 8 | Thread t1=new Thread(new Runnable() { @Override public void run() { System.out.println("In Run method"); } }); |
7) Can you create your own functional interface?
Yes, you can create your own functional interface. Java can implicitly identify functional interface but you can also annotate it with @FunctionalInterface.
Example:
Create interface named "Printable" as below
1 2 3 4 5 6 7 8 9 10 11 12 | package org.arpit.java2blog; public interface Printable { void print(); default void printColor() { System.out.println("Printing Color copy"); } } |
Create main class named "FunctionalIntefaceMain"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package org.arpit.java2blog.constructor; public class FunctionalIntefaceMain { public static void main(String[] args) { FunctionalIntefaceMain pMain=new FunctionalIntefaceMain(); pMain.printForm(() -> System.out.println("Printing form")); } public void printForm(Printable p) { p.print(); } } |
When you run above program, you will get below output:
As you can see, since Printable has only one abstract method called print(), we were able to call it using lambda expression.
8) What is method reference in java 8?
Method reference is used refer method of functional interface. It is nothing but compact way of lambda expression.You can simply replace lambda expression with method reference.
Syntax:
class::methodname
9) What is Optional? Why and how can you use it?
Java 8 has introduced new class Called Optional. This class is basically introduced to avoid NullPointerException in java.
Optional class encapsulates optional value which is either present or not.
It is a wrapper around object and can be use to avoid NullPointerExceptions.
Let’s take a simple example
You have written below function to get first non repeated character in String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public static Character getNonRepeatedCharacter(String str) { Map<Character, Integer> countCharacters = new LinkedHashMap<Character, Integer>(); for (int i = 0; i < str.length() - 1; i++) { Character c = str.charAt(i); if (!countCharacters.containsKey(c)) { countCharacters.put(c, 1); } else { countCharacters.put(c, countCharacters.get(c) + 1); } } // As LinkedHashMap maintains insertion order, first character with // count 1 should return first non repeated character for (Entry<Character, Integer> e : countCharacters.entrySet()) { if (e.getValue() == 1) return e.getKey(); } return null; } |
You call above method as below.
1 2 3 4 | Character c=getNonRepeatedCharacter("SASAS"); System.out.println("Non repeated character is :"+c.toString()); |
Do you see the problem, there is no non repeating character for getNonRepeatedCharacter("SASAS") hence it will return null and we are calling c.toString()
, so it will obviously throw NullPointerException.
You can use Optional to avoid this NullPointerException.
Let’s change the method to return Optional object rather than String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public static Optional<Character> getNonRepeatedCharacterOpt(String str) { Map<Character, Integer> countCharacters = new LinkedHashMap<Character, Integer>(); for (int i = 0; i < str.length(); i++) { Character c = str.charAt(i); if (!countCharacters.containsKey(c)) { countCharacters.put(c, 1); } else { countCharacters.put(c, countCharacters.get(c) + 1); } } // As LinkedHashMap maintains insertion order, first character with // count 1 should return first non repeated character for (Entry<Character, Integer> e : countCharacters.entrySet()) { if (e.getValue() == 1) return Optional.of(e.getKey()); } return Optional.ofNullable(null); } |
When above method returned Optional, you are already aware that it can return null value too.
You can call Optional’s isPresent method to check if there is any value wrapped in Optional.
1 2 3 4 5 6 7 8 9 | Optional<Character> opCh=getNonRepeatedCharacterOpt("SASAS"); if(opCh.isPresent()) System.out.println("Non repeated character is :"+opCh.toString()); else { System.out.println("No non repeated character found in String"); } |
If there is no value present in Optional, it will simply print "No non repeated character found in String".
10) What are defaults methods?
Default method are those methods in interface which have body and use default keywords.Default method are introduced in Java 8 mainly because of backward compatibility.
You can refer to default method in java for more details.
11) What is the difference between Predicate and Function?
Both are functional interfaces.
Predicate<T> is single argument function and either it returns true or false.This can be used as the assignment target for a lambda expression or method reference.
Function<T,R> is also single argument function but it returns an Object.Here T denotes type of input to the function and R denotes type of Result.
This can also be used as the assignment target for a lambda expression or method reference.
12) Are you aware of Date and Time API introduced in Java 8? What the issues with Old Date and time API?
Issues with old Date and TIme API:
Thread Safety: You might be already aware that java.util.Date is mutable and not thread safe. Even java.text.SimpleDateFormat is also not Thread-Safe. New Java 8 date and time APIs are thread safe.
Performance: Java 8 ‘s new APIs are better in performance than old Java APIs.
More Readable: Old APIs such Calendar and Date are poorly designed and hard to understand. Java 8 Date and Time APIs are easy to understand and comply with ISO standards.
13) Can you provide some APIs of Java 8 Date and TIme?
LocalDate, LocalTime, and LocalDateTime are the Core API classes for Java 8. As the name suggests, these classes are local to context of observer. It denotes current date and time in context of Observer.
14) How will you get current date and time using Java 8 Date and TIme API?
You can simply use now method of LocalDate to get today’s date.
1 2 3 4 | LocalDate currentDate = LocalDate.now(); System.out.println(currentDate); |
It will give you output in below format:
You can use now method of LocalTime to get current time.
1 2 3 4 | LocalTime currentTime = LocalTime.now(); System.out.println(currentTime); |
It will give you output in below format:
15) Do we have PermGen in Java 8? Are you aware of MetaSpace?
Until Java 7, JVM used an area called PermGen to store classes. It got removed in Java 8 and replaced by MetaSpace.
Major advantage of MetaSpace over permgen:
PermGen was fixed in term of mazimum size and can not grow dynamically but Metaspace can grow dynamically and do not have any size constraint.
Next 7 questions will be based on below class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | package org.arpit.java2blog; public class Employee { private String name; private int age; public Employee(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString() { return "Employee Name: "+name+" age: "+age; } } |
16) Given a list of employees, you need to filter all the employee whose age is greater than 20 and print the employee names.(Java 8 APIs only)
Answer:
You can simply do it using below statement.
1 2 3 4 5 6 | List<String> employeeFilteredList = employeeList.stream() .filter(e->e.getAge()>20) .map(Employee::getName) .collect(Collectors.toList()); |
Complete main program for above logic.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | package org.arpit.java2blog; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class MaximumUsingStreamMain { public static void main(String args[]) { List<Employee> employeeList = createEmployeeList(); List<String> employeeFilteredList = employeeList.stream() .filter(e->e.getAge()>20) .map(Employee::getName) .collect(Collectors.toList()); employeeFilteredList.forEach((name)-> System.out.println(name)); } public static List<Employee> createEmployeeList() { List<Employee> employeeList=new ArrayList<>(); Employee e1=new Employee("John",21); Employee e2=new Employee("Martin",19); Employee e3=new Employee("Mary",31); Employee e4=new Employee("Stephan",18); Employee e5=new Employee("Gary",26); employeeList.add(e1); employeeList.add(e2); employeeList.add(e3); employeeList.add(e4); employeeList.add(e5); return employeeList; } } |
17) Given the list of employees, count number of employees with age 25?
Answer:
You can use combination of filter and count to find this.
1 2 3 4 5 6 7 | List<Employee> employeeList = createEmployeeList(); long count = employeeList.stream() .filter(e->e.getAge()>25) .count(); System.out.println("Number of employees with age 25 are : "+count); |
18) Given the list of employees, find the employee with name “Mary”.
Answer:
It is again very simple logic, change the main function in above class as following.
1 2 3 4 5 6 7 8 | List<Employee> employeeList = createEmployeeList(); Optional<Employee> e1 = employeeList.stream() .filter(e->e.getName().equalsIgnoreCase("Mary")).findAny(); if(e1.isPresent()) System.out.println(e1.get()); |
19)Given a list of employee, find maximum age of employee?
Answer:
It is again very simple logic, change the main function in above class as following.
1 2 3 4 5 6 7 8 | List<Employee> employeeList = createEmployeeList(); OptionalInt max = employeeList.stream(). mapToInt(Employee::getAge).max(); if(max.isPresent()) System.out.println("Maximum age of Employee: "+max.getAsInt()); |
20) Given a list of employees, sort all the employee on the basis of age? Use java 8 APIs only
You can simply use sort method of list to sort the list of employees.
1 2 3 4 5 | List<Employee> employeeList = createEmployeeList(); employeeList.sort((e1,e2)->e1.getAge()-e2.getAge()); employeeList.forEach(System.out::println); |
21) Join the all employee names with “,” using java 8?
Answer:
1 2 3 4 5 6 7 8 9 | List<Employee> employeeList = createEmployeeList(); List<String> employeeNames = employeeList .stream() .map(Employee::getName) .collect(Collectors.toList()); String employeeNamesStr = String.join(",", employeeNames); System.out.println("Employees are: "+employeeNamesStr); |
Output:
22) Given the list of employee, group them by employee name?
Answer:
You can use Collections.groupBy() to group list of employees by employee name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | package org.arpit.java2blog; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class MaximumUsingStreamMain { public static void main(String args[]) { List<Employee> employeeList = createEmployeeList(); Map<String, List<Employee>> map = employeeList.stream() .collect(Collectors.groupingBy(Employee::getName)); map.forEach((name,employeeListTemp)->System.out.println("Name: "+name+" ==>"+employeeListTemp)); } public static List<Employee> createEmployeeList() { List<Employee> employeeList=new ArrayList<>(); Employee e1=new Employee("John",21); Employee e2=new Employee("Martin",19); Employee e3=new Employee("Mary",31); Employee e4=new Employee("Mary",18); Employee e5=new Employee("John",26); employeeList.add(e1); employeeList.add(e2); employeeList.add(e3); employeeList.add(e4); employeeList.add(e5); return employeeList; } } |
Output:
23) Difference between Intermediate and terminal operations in Stream?
Answer:
Java 8 Stream supports both intermediate and terminal operation.
Intermediate operations are lazy in nature and do not get executed immediately. Terminal operations are not lazy, they are executed as soon as encountered. Intermediate operation is memorized and is called when terminal operation is called.
All Intermediate operations return stream as it just transforms stream into another and terminal operation don’t.
Example of Intermediate operations are:
Example of terminal operations are :
24) Given the list of numbers, remove the duplicate elements from the list.
Answer:
You can simply use stream and then collect it to set using Collections.toSet() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | package org.arpit.java2blog; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public class RemoveDuplicatesFromListMain { public static void main(String[] args) { Integer[] arr=new Integer[]{1,2,3,4,3,2,4,2}; List<Integer> listWithDuplicates = Arrays.asList(arr); Set<Integer> setWithoutDups = listWithDuplicates.stream().collect(Collectors.toSet()); setWithoutDups.forEach((i)->System.out.print(" "+i)); } } |
You can use distinct as well to avoid duplicates as following.
change main method of above program as below.
1 2 3 4 5 6 | Integer[] arr=new Integer[]{1,2,3,4,3,2,4,2}; List<Integer> listWithDuplicates = Arrays.asList(arr); List<Integer> listWithoutDups = listWithDuplicates.stream().distinct().collect(Collectors.toList()); listWithoutDups.forEach((i)->System.out.print(" "+i)); |
25) Difference between Stream’s findFirst() and findAny()?
findFirst will always return the first element from the stream whereas findAny is allowed to choose any element from the stream.
findFirst has deterministic behavior whereas findAny is nondeterministic behavior.
26) Given a list of numbers, square them and filter the numbers which are greater 10000 and then find average of them.( Java 8 APIs only)
Answer:
You can use the map function to square the number and then filter to avoid numbers which are less than 10000.We will use average as terminating function in this case.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package org.arpit.java2blog; import java.util.Arrays; import java.util.List; import java.util.OptionalDouble; public class RemoveDuplicatesFromListMain { public static void main(String[] args) { Integer[] arr=new Integer[]{100,24,13,44,114,200,40,112}; List<Integer> list = Arrays.asList(arr); OptionalDouble average = list.stream() .mapToInt(n->n*n) .filter(n->n>10000) .average(); if(average.isPresent()) System.out.println(average.getAsDouble()); } } |
output:
27) What is use of Optional in Java 8?
Answer:
Java 8 optional can be used to avoid NullPointerException.You can read about the detailed tutorial.
28) What is predicate function interface?
Answer:
Predicate is single argument function which returns true or false. It has test method which returns boolean.
When we are using filter in above example, we are actually passing Predicate functional interface to it.
29) What is consumer function interface?
Answer:
Consumer is single argument functional interface which does not return any value.
When we are using foreach in above example, we are actually passing Consumer functional interface to it.
30) What is supplier function interface?
Answer:
Supplier is function interface which does not take any parameter but returns the value using get method.
No comments:
Post a Comment