Java 8 brought exciting new ways to write code & significant features lambdas, making code more concise and readable. The Stream API made working with collections way easier, especially for parallel processing. Default methods were a lifesaver for evolving interfaces without causing chaos in existing code. And the new java.time package fixed a bunch of headaches with handling dates and times. Basically, Java 8 made programming in Java more modern, expressive, and just plain better.
Our Java 8 Interview Questions section helps you understand these cool features, making you ready for Java 8 interviews. In this article,we will discuss some of the most asked java 8 interview questions, like as : what is java 8? or what is java 8 features orStream Api java 8 Interview Questions | Java 8 Interview Questions | Java 8 Interview Questions For 10 Years Experience| Stream Api In Java 8 Interview Questions | Core Java 8 Interview Questions .
Table of Contents
Toggle
1). Why Java 8 Introduced ? Or what is the Purpose of java 8 ? (Most Imp Question)
There is 3 reasons (or Intentions) for Java 8:
I). To reduce the code size (Concise and Minimal Code)
II). Introduce Functional programming or Declarative programming benefit with OOPs language. Therefore, we are using Functional programming language.
III). To enable Parallel programming: Now multi core processors in market so we can run multi programs or tasks parallelly with help of these core processors.
2). What is Java 8 ? (Imp Question)
The release date of Java 8 was March 14, 2014. This major release changed the way developers write code and create application with a number of revolutionary additions and improvements.
The features of Java 8 were designed to increase developer productivity, promote cleaner, more maintainable code, and support contemporary programming paradigms like functional programming.
3). What is the Features of Java 8 ? (Most Imp Question)
These are the main features of Java 8:
a) Functional Interfaces
b) Lambda Expression
c) Method References
c) Default method
d) Static method
e) Stream API
f) Date Time API
g) Optional
h) Nashorn, JavaScript Engine
4). What are the advantages of Java 8? (Most Imp Question)
These are the main advantanges of Java 8 :
. Compact, readable, and reusable code.
. Less boilerplate code.
. Users can write parallel code and execution.
. Users can write database-like operations
. High stability.
. Stable environment.
. Code is far more productive
5). What is the functional Programming? (Imp Question)
Functional Programming:
In functional programming, We are focusing to writing the code in the form of “pure functions.” A pure function is one that acts just on its inputs and does not produce any outputs. The output is independent of any conditions other than those specified by the inputs. This makes it simpler to understand the function’s behaviour and reduces the likelihood of making mistakes.
Key Principles of Functional Programming:
Pure Functions: They generate regular outputs for the identical inputs, devoid of aspect outcomes, and do no longer regulate outside states.
Immutability: Data remains unchanged once created, necessitating the advent of recent information systems for changes.
Higher-Order Functions: Functions can receive different capabilities as arguments or return them as outputs, facilitating flexible and modular code layout.
Recursion: Iteration is completed through recursion, where features call themselves for repetitive tasks in place of the usage of traditional looping constructs.
Avoidance of Mutable State: Encourages the usage of immutable data structures to save you unintentional aspect results and enhance code comprehension.
Referential Transparency: Allows replacing a characteristic’s result with its price with out affecting application conduct, helping code reasoning, testing, and debugging.
Application /Languages using funtional programming:
Functional programming languages like Haskell, Lisp, Scala, and Erlang are built on these principles. Additionally, modern-day languages such as Java, JavaScript, Python, and others.
Benefits and Usage: It specifically shines in eventualities related to parallelism, concurrency, and mathematical computations. This paradigm’s established approach fosters clearer code architecture and aids in constructing scalable and green packages.
6). What is Functional-Interface or SAM interface ? (Most Imp Question)
Functional Interface or SAM interface:
Till java 7 you can write only abstract mehtod (or declare method) within a interface and that time interface was 100 % abstract but after java 8 you can write the non abstract method (or define the body of interface) as a default and static methods.
Java 8 functional interface is an interface which contains One abstract method and Number of(or any number of) of static and default methods.
Note: It is annotated by @FunctionalInterface annotation.
7). What is a Lambda Expression? (Most Imp Question)
Basically Lambda Expression use to implementation of functional interface.
Lambda Expression is a Anonymous function (Without Name function), which have No method-Name, not any return type and no modifier. Just like below picture example :
Suppose that we are writing a method like this in java 7 :
Private void sayHello() {
System.out.Println(“This is simple java 7 method”);
}
But in Java 8 Lambda Expression, we will write Like as:
() -> { System.out.Println(“This is Lambda expression method”); }
Example:
@FunctionalInterface
interface Addition {
public int divide(int a, int b)
}
public class Lambda_Example {
public static void main(String[] args) {
Addition add = (a, b) -> (a / b);
System.out.println(add.divide(20, 10));
}}
8). What is the difference between Lambda Expression and Anonymous Inner Class ? (Imp Question)
The main differences between Lambda Expression and Anonymous Inner Class are:
. No. |
Anonymous Inner Class |
Lambda Expression |
1. |
An anonymous class implements interfaces and |
Lambda |
2. |
Anonymous class contains multiple abstract methods (or multiple |
functional |
9). What is a default (or defender) method in Java 8? When to use it? (Most Imp Question)
The default method is also known as defender methods or virtual extension methods. It is a non-abstract method which have a body, which can be declared inside the interface.
So what is benefit of Default method:
a). We can define the body of method in a interface
b). Resolve the multiple inheritance problem
c). The default method is introduced in Java 8 for backward compatibility. That is if you add a new abstract method to the interface, all the implementing classes shall break. Implementing classes need to implement the added abstract method.
This problem is solved by the default method of java 8.
Example:
@FunctionalInterface
interface xyz {
public void show();
public default void show1() {
System.out.println(“It is default method and body of thid mehtod already defined”);
}}
public class Default implements xyz {
@Override
public void show() {
System.out.println(“this is abstract mehtod of XYZ interface”);
}
public static void main(String[] args) {
Default d1 = new Default();
d1.show();
d1.show1();
}}
11). What is Method Reference Java 8? (Imp Question)
It is alternate or replace of Lambda expression. It is compact and easy form of lambda expression.
For Example: If the Lambda Expression looks like: num -> System.out.println(num)
Then the corresponding Method Reference would be: System.out::println
Example:
interface Hi{
void say();
}
public class MethodReferenceDemo {
public static void saySomething(){
System.out.println(“Hello, this is static method.”);
}
public static void main(String[] args) {
// Referring static method
Hi hi = MethodReferenceDemo::saySomething;
// Calling interface method
hi.say();
}}
12). What is the Optional class in java 8 ? (Most Imp Question)
Optional class is a special wrapper class and It is used to avoid NullPointerException. This Optional class concept is inspired by Haskell and Scala.
Java SE 8 introduces a new class in the util package i.e java.util.Optional.
Example:
public class Optional_Exam {
public static Optional<String> getName(int id) {
String name =null; // value is coming null from DB
return Optional.ofNullable(name);
}
public static void main(String[] args) {
Optional<String> name = getName(1);
if (name.isPresent()) {
System.out.println(name.get());
}
name.ifPresent(System.out::println);
}}
13). What is the difference between PermGenSpace and MetaSpace ?
Now PermGenSpace is removed from Java8. Earlier PermGenSpace is used for storing the metadata. Metadata means storing information about classes like bytecodes, names, and JIT information.Java classes metadata now stored in a native heap and this space is called MetaSpace. Metaspace grows automatically by default and will be garbage collected.
So the major difference between PermGenSpace and MetaSpace is that PermGenSpace was fixed in size
and did not grow automatically, but MetaSpace does not have any size constraints.
14). What are Standard Java 8 Pre-Defined Functional Interfaces? What are the different functional interfaces in Java 8 ? (Most Imp Question)
In Java, several pre-defined functional interfaces exist in the java.util.function package:
a) Predicate<T> : Represents a boolean-valued function of one argument.
or
it is Boolean functional interface & just hold a condition and which is return a Boolean value (true or false).Predicate just hold a condition. This condition may be true or false. It is alternate of If or if else loop.
Example:
import java.util.function.Predicate;
public class Predicate_exam {
public static void main(String[] args) {
Predicate<Integer> pr = a -> (a > 18);
System.out.println(pr.test(20));
}}
b) Consumer<T> : Represents an operation that accepts a single input argument and returns no result.
Example:
import java.util.function.Consumer;
public class Cosumer_Exam {
public static void main(String[] args) {
Consumer<String> print = x -> System.out.println(x);
print.accept(“java”);
}}
c) Function<T, R> : Represents a function that takes one argument and returns a result.
d) Supplier<T> : Represents a supplier of results.
e) UnaryOperator<T> : Represents an operation on a single operand that produces a result of the same type as its operand.
Example:
import java.util.function.UnaryOperator;
public class UnaryOperator_Exam {
public static void main(String[] args) {
UnaryOperator<Integer> unaryOperator=x->x+x;
System.out.println(unaryOperator.apply(5));
}}
f) BinaryOperator<T> : Represents an operation upon two operands of the same type, producing a result of the same type as the operands.
Example:
import java.util.function.BinaryOperator;
public class BinaryOperator_Exam {
public static void main(String[] args) {
BinaryOperator<String> binaryOperator=(str1,str2)->str1+str2;
System.out.println(binaryOperator.apply(“Aryan”, “Poona”));
}}
15). What is java 8 Date and Time api ? What are the issues of the old Date and Time APIs ?
Java 8 Date and Time Api: The java.time, java.util, java.sql and java.text packages contains classes for representing date and time. Following classes are important for dealing with date in Java.
Java 8 to overcome the following drawbacks of old date-time API :
a). Not thread safe , Less operations.
b). Local : Simplified date-time API with no complexity of timezone handling.
c). Zoned : Specialized date-time API to deal with various timezones.
Example:
import java.time.LocalDate;
public class Date {
public static void LocalDateTimeApi() {
LocalDate date = LocalDate.now();
System.out.println(date);
System.out.println(“the current date in Local “ + date.getDayOfWeek());
System.out.println(“Current Month :” + date.getDayOfMonth());
System.out.println(“Current Month :” + date.getDayOfYear());
}
public static void main(String[] args) {
LocalDateTimeApi();
}}}
16). What is the Intermediate Operations in java 8 ? (Most Imp Question)
Intermediate Operations : Those operations, which is return another Streams as a result.
Note: they are Lazy. All intermediate operations are lazy, so they’re not executed until a result of a processing is actually needed.
Example: filter(),map(),skip(),sorted(),limit() extra
17). What is the Terminal Operations in java 8 ?
Terminal Operations: Those operations which is returns non stream values.
Example: forEach(),findfirst(), reduce(),min(), max(),average(), sum(),collect() extra
18). What is Stream API in Java 8? Why do we need it? or Java Stearms api ? (Most Imp Question)
Stream API: Stream means processing the data.
Streams api, read the collection objects and perform different functional operations.
Like as: Employee max salary, min salary, average salary, sorting and filters the employee List.
Types of Stream api:
java.util stream: it deal with data Operations.
java.io .steams: it deal with file and file- Stearms
We require the Stream API because:
a). It supports aggregate operations which makes the processing simple.
b). It supports Functional-Style programming.
c). It does faster processing. Hence, it is apt for better performance.
d). It allows parallel operations.
Example:
import java.util.Array
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
class Employee {
int id;
String empName;
float salary;
public Employee(int id, String empName, float salary) {
this.id = id;
this.empName = empName;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
@Override
public String toString() {
return “Employee [id=” + id + “, empName=” + empName + “, salary=” + salary + “]”;
}}
public class Second_highest_salaried_Employee {
public static void main(String[] args) {
List<Employee> employeeList = Arrays.asList(new Employee(100, “Shekher”, 500000),
new Employee(101, “Trilok”, 300000), new Employee(102, “Aryan”, 200000),
new Employee(104, “Sanjay”, 100000));
// second Highest Salary of Employee
Optional<Employee> secondHisghestSalary = employeeList.stream()
.sorted(Comparator.comparing(Employee::getSalary).reversed()).skip(1).findFirst();
System.out.println(“Second Highest Salary of Employee” + secondHisghestSalary.get());
}}
People also ask : Stream Api java 8 Interview Questions | Java 8 Interview Questions | Java 8 Interview Questions For 10 Years Experience| Stream Api In Java 8 Interview Questions | Core Java 8 Interview Questions