Blog Details

img
Java

Java 8 Interview Questions and Answers 2024

Administration1HJ5654$%^#$ / 18 Apr, 2024

Q1. What are functional or SAM interfaces?

Functional Interfaces are an interface with only one abstract method.

Due to which it is also known as the Single Abstract Method (SAM)

interface. It is known as a functional interface because it wraps a

function as aninterface or in other words a function is represented

by a single abstract method of the interface.Functional interfaces

can have any number of default, static,and overridden methods.

For declaring Functional Interfaces @FunctionalInterface annotation

is optional to use. If this annotation is used for interfaces with more

than one abstract method, it will generate a compiler error.

package java8;

 

interface inj{

           

default public void display()

            {

            System.out.println("hello");          

            }

           

           

static public void disp()

            {

                        System.out.println("static");

            }

           

void m1();

 

}

 

public class funct01 {

 

            public static void main(String[] args) {

 

            inj i=()->System.out.println("lambda expression");

            i.m1();

            i.display();

            inj.disp();

 

            }

 

}

 

Q2. What are the features of Java 8 and Java 11?

Java 8 was a major release of the Java programming language and platform,

and itintroduced several new features and improvements. Some of the most

notable features of Java 8 include:

 

Lambda expressions: A way to define and pass around blocks of code as if they were

objects, which allows for more concise, functional-style code.

Functional interfaces: Interfaces that have exactly one abstract method, which allows

for behavior parameterization and the ability to pass behavior as a method argument.

Streams: A new API for processing collections of data that allows for operations such

as filtering, mapping, and reducing to be performed in a more functional and readable

way.Date and time API: A new API for working with date and time, which replaces the legacy

java.util.Date and java.util.Calendar classes.Concurrent Accumulators: A set of classes

designed for use with parallel streams, which allow for the efficient accumulation of values.

Java 11, released in 2018, is a long-term support release and it brings several important

changes and improvements over Java 8. Some of the most notable features of Java 11 include:

Local-variable type inference: A new syntax that allows you to infer the type of a variable

from the value being assigned to it, which can make your code more readable and concise.

 

Q3. What is lambda expression?

Lambda Expression is just an anonymous (nameless) function. That means the function which

doesn’t have the name, return type and access modifiers.

Lambda Expression also known as anonymous functions or closures.

 

 

Q4.  Why are default methods needed in the interface?

Default methods let you add new functionality to your libraries’ interfaces and ensure

binary compatibility with older code written for the interfaces.

 

Q5. What is a collection, and how is it different from a stream?

A collection is an in-memory database that records all the values according to the

current data structure. So, before adding you add it to the collection, it’s important to

compute each of them. Whereas a stream is a visually fixed data structure where we

can compute the elements according to our needs.

 

Q6.  Explain the ‘Functional Interface’.

An interface with only one abstract is called a functional interface. It is also known as

the Single Abstract Method or SAM. However, the annotation @FunctionalInterface is

optional and can be used even if it is not there. It extends to the other interface if it

doesn’t have any abstract.

 

Q7. Can you explain the syntax of Lambda expression?

The structure of a lambda expression can be divided into three parts:


1. Argument list or parameters

 

Lambda expression can have zero or more arguments.

()->{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

 

 

 

You can omit the declaration of argument types, as they can be inferred from the context.

 

          ( a,b)->{a+b};//two argument, will return sum of these two numbers

 

You cannot declare the type for one argument and omit it for another; types must

be consistently declared or inferred for all arguments.

 

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

 

When there is a single parameter and its type is inferred, parentheses are not mandatory.

   

a->{System.out.println(a)}; // Will print value of number a

 

2. Array token (->)

3. Body

  • The body can contain either an expression or statements.
  • If the body contains only one statement, curly braces are not needed, and the return
  • type of the anonymous function matches that of the body expression.
  • If there are multiple statements, they must be enclosed in curly braces, and the return
  • type of the anonymous function corresponds to the value returned from the code
  • block, or void if nothing is returned.

 

Q8. Differentiate between a predicate and a function in Java

Predicate Function

Predicate Function

To implement conditional checks

We should go for predicate

To perform certain operation And to

return some result we Should go for

function.

Predicate can take one type

Parameter which represents

Input argument type

Predicate<T>

Function can take 2 type Parameters.

First one represent Input argument

type and Second one represent returnType.

Function<T,R>

Predicate interface defines only one method called test()

 

 

Function interface defines only one

Method called apply().

public boolean test(T t)

public R apply(T t)

Predicate can return only

boolean value.

Function can return any type of value

 

Q9. How can you create custom functional interfaces in Java 8?

We can create custom functional interfaces by adding the @FunctionalInterface

annotation to any interface with a single abstract method. It can contain default and

static methods too. This allows leveraging lambda expressions for desired functionality.
For example:

 

@FunctionalInterface

 

interface CustomFI

{

void customMethod();

 

default void defaultMethod()

{

 

// default implementation

}

}


Q10. How to find and remove duplicate elements from a stream?

Duplicate elements can be eliminated from a stream by using distinct() or collecting

results into a set, which removes duplicates by design.
For example:

 

list.stream().distinct().collect(Collectors.toList());


Q11.  What is the syntax of a predicate interface in Java 8?

Predicate is a functional interface used in Java to take in an object and return a Boolean value.

The following is the syntax of a predicate function:

 

public boolean test(T object)

{

 

return boolean;

 

}


Q12. What Is a Stream? How Does It Differ From a Collection?

In simple terms, a stream is an iterator whose role is to accept a set of

actions to apply on each of the elements it contains.The stream 

represents a sequence of objects from a source such as a

collection, which supports aggregate operations. They were designed

to make collection processing simple and concise. Contrary to the collections,

the logic of iteration is implemented inside the stream, so we can use methods

like map and flatMap for performing a declarative processing.

Additionally, the Stream API is fluent and allows pipelining:

int sum = Arrays.stream(new int[]{1, 2, 3})

  .filter(i -> i >= 2)

  .map(i -> i * 3)

  .sum();

 

Q13. What are the main components of a Stream?

Components of the stream are:

·         A data source

·         Set of Intermediate Operations to process the data source

·         Single Terminal Operation that produces the result

 

 

 

Q14.  What is the most common type of Terminal operations?

·                     collect() - Collects single result from all elements of the stream sequence.

·               reduce() - Produces a single result from all elements of the stream sequence

o         count() - Returns the number of elements on the stream.

o         min() - Returns the min element from the stream.

o         max() - Returns the max element from the stream.



Q15.  How are Collections different from Stream?

Collections are the source for the Stream. Java 8 collection API is enhanced with

the default methods returning Stream<T> from the collections.

Collections

Streams

Data structure holds all the data elements

No data is stored. Have the capacity to process an infinite number of elements on demand

External Iteration

Internal Iteration

Can be processed any number of times

Traversed only once

Elements are easy to access

No direct way of accessing specific elements

Is a data store

Is an API to process the data

 

Q16. What is the default method and its uses?

 

A default method is a method defined in an interface that has a default implementation.

Default methods were introduced in Java 8 to allow interfaces to be extended without

breaking existing implementations.


Before Java 8, interfaces could only contain method signatures, which meant that any

class that implemented an interface was required to provide an implementation for all

of its methods. This could be problematic when you want to add new methods to an

existing interface because it would break all of the existing implementations.

With default methods, you can provide a default implementation for a method in an

interface, which means that classes that implement the interface are not required to

provide their own implementation. If a class does not provide its own implementation

for a default method, it will use the default implementation defined in the interface.

Default methods are useful for extending existing interfaces without breaking existing

implementations. They can also be used to provide a common implementation for a

method that is applicable to all classes that implement the interface.

For example, consider an interface for a collection of items:

public interface Collection<T> {
void add(T item);
boolean contains(T item);
int size();
default boolean isEmpty() {
return size() == 0;
}
}

This interface defines three methods for adding items to the collection, checking

if an item is contained in the collection, and getting the size of the collection.It

also defines a default method, isEmpty(), that returns true if the size of the collection is 0.

Classes that implement this interface are not required to provide their own implementation

for isEmpty(), because a default implementation is already provided in the interface.

However, they can override the default implementation if they need to provide a different behavior.

 

Q17.  Why are Static methods needed in Java 8?

Static method reference is referred to as a utility or helper method, which is linked

with an interface. It is also a class that is not linked to any object. Here are reasons

for using the Static method in Java:Useful for maintaining and extending the API.

  • Entails a clear and concise share of responsibilities, and you don’t need to have one
  • utility class to have the utility collections.Useful for keeping all the interfaces in a common
  • interface rather than specific interfaces.

 

Q18. Write down a Java 8 program that can find a Stream’s minimum and maximum number.

import java.util.Arrays;

import java.util.stream.IntStream;

public class MinMaxExample {

    public static void main(String[] args) {

        int[] numbers = {9, 3, 8, 1, 5, 7, 2, 6, 4};

        int min = IntStream.of(numbers).min().getAsInt();

        int max = IntStream.of(numbers).max().getAsInt();

        System.out.println("Minimum number: " + min);

        System.out.println("Maximum number: " + max);

    }

}

Output:

Minimum number: 1

Maximum number: 9

 

Q19. What is the best alternative to lambda expressions in Java 8?

In general, we utilize lambda expressions to create anonymous methods that help

get desired output. However, there are instances where lambda expressions fail to

work and use an existing method only.

So, to avoid this, you can use method reference that can help in getting the desired

output. The method reference is depicted using the: (double colon) symbol.

 

Q20. What is a Stream API? Why do we require the Stream API?

Answer: Stream API is a new feature added in Java 8. It is a special class that is used

for processing objects from a source such as Collection. We require the Stream API because,

  • It supports aggregate operations which makes the processing simple. It supports
  • Functional-Style programming.It does faster processing. Hence, it is apt for better performance.
  • It allows parallel operations.

 

Predicate Programs:

 

1> Write a program to check whether the given number is prime number or not

 

 package java8;

 

import java.util.function.Predicate;

 

public class predicate2 {

 

            public static void main(String[] args) {

                        Predicate<Integer> p=I->{

                                    int flag=1;

                                   

                                   

                                                for(int j=2;j<=I/2;j++)

                                                {

                                                            if(I%j==0)

                                                            {

                                                                        flag=0;

                                                            }

                                                }

                                               

                                               

                                                if(flag==1)

                                                {

                                                            System.out.println(I);

                                                            return true;

                                                           

                                                }

                                                else {

                                                            return false;

                                               

                                    }

                                   

                        };

System.out.println(p.test(4));

            }

}

 

2>  Write a program to check whether the given String is Empty or not

 

package java8;

 

import java.util.function.Predicate;

 

public class predicate3 {

 

            public static void main(String[] args) {

                        Predicate<String> p=S->{

                                    if(S.isEmpty())

                                    {

                                                System.out.println("NO String available");

                                                return true;

                                    }

                                    else {

                                                return false;

                                    }

                        };

                       

                       

                        System.out.println(p.test(""));

                        System.out.println(p.test("hello"));

 

            }

 

}

 

Function  Programs:

 

1>Write a program to return list of ASCII values for a given String.

 

import java.util.ArrayList;

import java.util.List;

import java.util.function.Function;

 

public class function02 {

 

            public static void main(String[] args) {

                        Function<String,List<Integer>> f=S->{

                                    List<Integer> list=new ArrayList<>();

                                   

                       

                                                char c[]=S.toCharArray();

                                               

                                               

                                                for(int j=0;j<c.length;j++) {

                                                           

                                                            int arr=(int)c[j];

                                                           

                                                            list.add(arr);

                                                           

 

                                               

                                               

                                               

                                    }

                                    return list;

                        };

                       

                        System.out.println(f.apply("hello"));

                       

            }

 

}

 

2>Write a program to calculate the number of words from given String

 

package java8;

 

import java.util.function.Function;

 

public class function03 {

 

            public static void main(String[] args) {

                        // TODO Auto-generated method stub

Function<String,Integer> f=S->

{

            int word=1;

            for(int i=0;i<S.length();i++)

            {

                        char c=S.charAt(i);

                        if(c==' ')

                        {

                                    ++word;

                        }

            }

            return word;

};

 

System.out.println(f.apply("hello i am a java"));

            }

 

}

 

Stream API|:

 

Program:

Write a program to sort the list in descending order .

 

import java.util.*;

import java.util.stream.Collectors;

 

public class stream01 {

 

            public static void main(String[] args) {

                       

                        ArrayList<Integer> list=new ArrayList<>();

                        list.add(10);

                        list.add(17);

                        list.add(26);

                        list.add(7);

                        list.add(6);

                       

                        List<Integer> l1=list.stream().sorted((I1,I2)->I2.compareTo(I1)).collect(Collectors.toList());

                        System.out.println(l1);

                       

            long c=list.stream().count();

                        System.out.println(c);

                       

                       

                       

                       

}

 

}

 

2>Write a program  for stream API

 

package java8;

 

import java.util.ArrayList;

import java.util.List;

import java.util.stream.Collectors;

 

public class stream02 {

 

            public static void main(String[] args) {

                        ArrayList<String> list=new ArrayList<>();

                        list.add("hello");

                        list.add("bye");

                        list.add("good");

                        list.add("bye");

                       

                        List<String> l=list.stream().map(String::toUpperCase).collect(Collectors.toList());

                        System.out.println(l);

                       

                       

                        List<String> l1=list.stream().distinct().collect(Collectors.toList());

                        System.out.println(l1);

                       

 

                        List<String> l2=list.stream().filter(S->S.startsWith("h")).collect(Collectors.toList());

                        System.out.println(l2);

            }

 

}

 

Default and Static methods:

 

Program:

 

package java8;

 

interface int66{

            public default void display()

            {

                        System.out.println("hello1");

            }

            public static void m1()

            {

                        System.out.println("good morning");

            }

}

 

 

 

public class demp12 implements int66{

public void display()

{

            int66.super.display();

            System.out.println("main method");

}

public static void m1()

{

            System.out.println("bye");

}

            public static void main(String[] args) {

            demp12 d=new demp12();

            d.display();

            d.m1();

int66.m1();

            }

 

}

 

 

 

 

 

Lambda Function:

 

Program:

 

package java8;

 

 

 

interface Fun{

            int m1(int a,int b);

}

public class first {

 

            public static void main(String[] args) {

                        // TODO Auto-generated method stub

Fun f=(a,b)->{return(a+b);};

System.out.println(f.m1(2,4));

            }

 

}

 

0 comments