Preguntas de la entrevista de Java 8 (+ respuestas)

Este artículo es parte de una serie: • Preguntas de la entrevista sobre las colecciones de Java

• Preguntas de la entrevista del sistema de tipo Java

• Preguntas de la entrevista de simultaneidad de Java (+ respuestas)

• Preguntas de la entrevista de inicialización y estructura de clases de Java

• Preguntas de la entrevista de Java 8 (+ respuestas) (artículo actual) • Gestión de la memoria en las preguntas de la entrevista de Java (+ respuestas)

• Preguntas de la entrevista de Java Generics (+ Respuestas)

• Preguntas de la entrevista de control de flujo de Java (+ respuestas)

• Preguntas de la entrevista sobre excepciones de Java (+ respuestas)

• Preguntas de la entrevista de anotaciones de Java (+ respuestas)

• Preguntas principales de la entrevista del Spring Framework

1. Introducción

En este artículo, vamos a explorar algunas de las preguntas relacionadas con JDK8 que pueden surgir durante una entrevista.

Java 8 es una versión de plataforma repleta de nuevas funciones de lenguaje y clases de biblioteca. La mayoría de estas nuevas funciones están orientadas a lograr un código más limpio y compacto, y algunas agregan nuevas funciones que nunca han sido compatibles con Java.

2. Conocimientos generales de Java 8

Q1. ¿Qué nuevas funciones se agregaron en Java 8?

Java 8 incluye varias características nuevas, pero las más importantes son las siguientes:

  • Expresiones Lambda : una nueva función de lenguaje que permite tratar las acciones como objetos
  • Referencias de métodos : habilite la definición de expresiones Lambda haciendo referencia a los métodos directamente usando sus nombres
  • Opcional : clase contenedora especial utilizada para expresar opcionalidad
  • Interfaz funcional : una interfaz con un máximo de un método abstracto, la implementación se puede proporcionar mediante una expresión Lambda
  • Métodos predeterminados : nos dan la capacidad de agregar implementaciones completas en interfaces además de métodos abstractos.
  • Nashorn, JavaScript Engine : motor basado en Java para ejecutar y evaluar código JavaScript
  • Stream API : una clase de iterador especial que permite procesar colecciones de objetos de manera funcional
  • API de fecha : una API de fecha mejorada e inmutable inspirada en JodaTime

Junto con estas nuevas características, se realizan muchas mejoras de características bajo el capó, tanto a nivel de compilador como de JVM.

3. Referencias de métodos

Q1. ¿Qué es una referencia de método?

Una referencia de método es una construcción de Java 8 que se puede usar para hacer referencia a un método sin invocarlo. Se utiliza para tratar métodos como expresiones lambda. Solo funcionan como azúcar sintáctico para reducir la verbosidad de algunas lambdas. De esta forma, el siguiente código:

(o) -> o.toString();

puede llegar a ser:

Object::toString();

Una referencia a un método se puede identificar con dos puntos dobles que separan el nombre de una clase o de un objeto y el nombre del método. Tiene diferentes variaciones como la referencia del constructor:

String::new;

Referencia de método estático:

String::valueOf;

Referencia del método de instancia enlazada:

str::toString;

Referencia de método de instancia independiente:

String::toString;

Puede leer una descripción detallada de las referencias de métodos con ejemplos completos siguiendo este enlace y este.

Q2. ¿Cuál es el significado de String :: Valueof Expression?

Es una referencia de método estático al método valueOf de la clase String .

4. Opcional

Q1. ¿Qué es opcional ? ¿Como puede ser usado?

Opcional es una nueva clase en Java 8 que encapsula un valor opcional, es decir, un valor que está ahí o no. Es una envoltura alrededor de un objeto, y puedes pensar en él como un contenedor de cero o un elemento.

Opcional tiene un valor especial Optional.empty () en lugar de un valor nulo envuelto . Por lo tanto, se puede usar en lugar de un valor anulable para deshacerse de NullPointerException en muchos casos.

Puede leer un artículo dedicado sobre Opcional aquí.

El propósito principal de Optional , tal como lo diseñaron sus creadores, era ser un tipo de retorno de métodos que anteriormente devolverían null . Dichos métodos requerirían que escribiera código repetitivo para verificar el valor de retorno y, a veces, podría olvidarse de hacer una verificación defensiva. En Java 8, un tipo de retorno opcional requiere explícitamente que maneje los valores envueltos nulos o no nulos de manera diferente.

Por ejemplo, el método Stream.min () calcula el valor mínimo en una secuencia de valores. Pero, ¿y si el arroyo está vacío? Si no fuera para Opcional , el método devolvería nulo o lanzaría una excepción.

Pero devuelve un valor opcional que puede ser Optional.empty () (el segundo caso). Esto nos permite manejar fácilmente dicho caso:

int min1 = Arrays.stream(new int[]{1, 2, 3, 4, 5}) .min() .orElse(0); assertEquals(1, min1); int min2 = Arrays.stream(new int[]{}) .min() .orElse(0); assertEquals(0, min2); 

Vale la pena señalar que Optional no es una clase de propósito general como Option en Scala. No se recomienda su uso como valor de campo en clases de entidad, lo cual se indica claramente al no implementar la interfaz serializable .

5. Interfaces funcionales

Q1. Describa algunas de las interfaces funcionales de la biblioteca estándar.

Hay muchas interfaces funcionales en el paquete java.util.function , las más comunes incluyen pero no se limitan a:

  • Función : toma un argumento y devuelve un resultado
  • Consumidor : toma un argumento y no devuelve ningún resultado (representa un efecto secundario)
  • Proveedor : no acepta argumentos y devuelve un resultado
  • Predicado : toma un argumento y devuelve un valor booleano
  • BiFunction : toma dos argumentos y devuelve un resultado
  • BinaryOperator : es similar a BiFunction , toma dos argumentos y devuelve un resultado. Los dos argumentos y el resultado son todos del mismo tipo
  • UnaryOperator : es similar a una función , toma un solo argumento y devuelve un resultado del mismo tipo

Para obtener más información sobre interfaces funcionales, consulte el artículo "Interfaces funcionales en Java 8".

Q2. ¿Qué es una interfaz funcional? ¿Cuáles son las reglas para definir una interfaz funcional?

A functional interface is an interface with no more, no less but one single abstract method (default methods do not count).

Where an instance of such interface is required, a Lambda Expression can be used instead. More formally put: Functional interfaces provide target types for lambda expressions and method references.

The arguments and return type of such expression directly match those of the single abstract method.

For instance, the Runnable interface is a functional interface, so instead of:

Thread thread = new Thread(new Runnable() { public void run() { System.out.println("Hello World!"); } });

you could simply do:

Thread thread = new Thread(() -> System.out.println("Hello World!"));

Functional interfaces are usually annotated with the @FunctionalInterface annotation – which is informative and does not affect the semantics.

6. Default Method

Q1. What Is a Default Method and When Do We Use It?

A default method is a method with an implementation – which can be found in an interface.

We can use a default method to add a new functionality to an interface while maintaining backward compatibility with classes that are already implementing the interface:

public interface Vehicle { public void move(); default void hoot() { System.out.println("peep!"); } }

Usually, when a new abstract method is added to an interface, all implementing classes will break until they implement the new abstract method. In Java 8, this problem has been solved by the use of default method.

For example, Collection interface does not have forEach method declaration. Thus, adding such method would simply break the whole collections API.

Java 8 introduces default method so that Collection interface can have a default implementation of forEach method without requiring the classes implementing this interface to implement the same.

Q2. Will the Following Code Compile?

@FunctionalInterface public interface Function2 { public V apply(T t, U u); default void count() { // increment counter } }

Yes. The code will compile because it follows the functional interface specification of defining only a single abstract method. The second method, count, is a default method that does not increase the abstract method count.

7. Lambda Expressions

Q1. What Is a Lambda Expression and What Is It Used for

In very simple terms, a lambda expression is a function that can be referenced and passed around as an object.

Lambda expressions introduce functional style processing in Java and facilitate the writing of compact and easy-to-read code.

Because of this, lambda expressions are a natural replacement for anonymous classes as method arguments. One of their main uses is to define inline implementations of functional interfaces.

Q2. Explain the Syntax and Characteristics of a Lambda Expression

A lambda expression consists of two parts: the parameter part and the expressions part separated by a forward arrow as below:

params -> expressions

Any lambda expression has the following characteristics:

  • Optional type declaration – when declaring the parameters on the left-hand side of the lambda, we don't need to declare their types as the compiler can infer them from their values. So int param -> … and param ->… are all valid
  • Optional parentheses – when only a single parameter is declared, we don't need to place it in parentheses. This means param -> … and (param) -> … are all valid. But when more than one parameter is declared, parentheses are required
  • Optional curly braces – when the expressions part only has a single statement, there is no need for curly braces. This means that param – > statement and param – > {statement;} are all valid. But curly braces are required when there is more than one statement
  • Optional return statement – when the expression returns a value and it is wrapped inside curly braces, then we don't need a return statement. That means (a, b) – > {return a+b;} and (a, b) – > {a+b;} are both valid

To read more about Lambda expressions, follow this link and this one.

8. Nashorn Javascript

Q1. What Is Nashorn in Java8?

Nashorn is the new Javascript processing engine for the Java platform that shipped with Java 8. Until JDK 7, the Java platform used Mozilla Rhino for the same purpose. as a Javascript processing engine.

Nashorn provides better compliance with the ECMA normalized JavaScript specification and better runtime performance than its predecessor.

Q2. What Is JJS?

In Java 8, jjs is the new executable or command line tool used to execute Javascript code at the console.

9. Streams

Q1. 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.

Another difference is that 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();

And yet another important distinction from collections is that streams are inherently lazily loaded and processed.

Q2. What Is the Difference Between Intermediate and Terminal Operations?

Stream operations are combined into pipelines to process streams. All operations are either intermediate or terminal.

Intermediate operations are those operations that return Stream itself allowing for further operations on a stream.

These operations are always lazy, i.e. they do not process the stream at the call site, an intermediate operation can only process data when there is a terminal operation. Some of the intermediate operations are filter, map and flatMap.

Terminal operations terminate the pipeline and initiate stream processing. The stream is passed through all intermediate operations during terminal operation call. Terminal operations include forEach, reduce, Collect and sum.

To drive this point home, let us look at an example with side effects:

public static void main(String[] args) { System.out.println("Stream without terminal operation"); Arrays.stream(new int[] { 1, 2, 3 }).map(i -> { System.out.println("doubling " + i); return i * 2; }); System.out.println("Stream with terminal operation"); Arrays.stream(new int[] { 1, 2, 3 }).map(i -> { System.out.println("doubling " + i); return i * 2; }).sum(); }

The output will be as follows:

Stream without terminal operation Stream with terminal operation doubling 1 doubling 2 doubling 3

As you can see, the intermediate operations are only triggered when a terminal operation exists.

Q3. What Is the Difference Between Map and flatMap Stream Operation?

There is a difference in signature between map and flatMap. Generally speaking, a map operation wraps its return value inside its ordinal type while flatMap does not.

For example, in Optional, a map operation would return Optional type while flatMap would return String type.

So after mapping, one needs to unwrap (read “flatten”) the object to retrieve the value whereas, after flat mapping, there is no such need as the object is already flattened. The same concept is applied to mapping and flat mapping in Stream.

Both map and flatMap are intermediate stream operations that receive a function and apply this function to all elements of a stream.

The difference is that for the map, this function returns a value, but for flatMap, this function returns a stream. The flatMap operation “flattens” the streams into one.

Here's an example where we take a map of users' names and lists of phones and “flatten” it down to a list of phones of all the users using flatMap:

Map
    
      people = new HashMap(); people.put("John", Arrays.asList("555-1123", "555-3389")); people.put("Mary", Arrays.asList("555-2243", "555-5264")); people.put("Steve", Arrays.asList("555-6654", "555-3242")); List phones = people.values().stream() .flatMap(Collection::stream) .collect(Collectors.toList());
    

Q4. What Is Stream Pipelining in Java 8?

Stream pipelining is the concept of chaining operations together. This is done by splitting the operations that can happen on a stream into two categories: intermediate operations and terminal operations.

Each intermediate operation returns an instance of Stream itself when it runs, an arbitrary number of intermediate operations can, therefore, be set up to process data forming a processing pipeline.

There must then be a terminal operation which returns a final value and terminates the pipeline.

10. Java 8 Date and Time API

Q1. Tell Us About the New Date and Time API in Java 8

A long-standing problem for Java developers has been the inadequate support for the date and time manipulations required by ordinary developers.

The existing classes such as java.util.Date and SimpleDateFormatter aren’t thread-safe, leading to potential concurrency issues for users.

Poor API design is also a reality in the old Java Data API. Here's just a quick example – years in java.util.Date start at 1900, months start at 1, and days start at 0 which is not very intuitive.

These issues and several others have led to the popularity of third-party date and time libraries, such as Joda-Time.

In order to address these problems and provide better support in JDK, a new date and time API, which is free of these problems, has been designed for Java SE 8 under the package java.time.

11. Conclusion

In this article, we've explored a few very important questions for technical interview questions with a bias on Java 8. This is by no means an exhaustive list but only contains questions that we think are most likely to appear in each new feature of Java 8.

Even if you are just starting up, ignorance of Java 8 isn't a good way to go in an interview, especially when Java appears strongly on your resume. It is, therefore, important that you take some time to understand the answers to these questions and possibly do more research.

Good luck in your interview.

Siguiente » Preguntas de la entrevista sobre administración de memoria en Java (+ Respuestas) « Preguntas anteriores de la entrevista sobre estructura e inicialización de clases Java