Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

What is the use of JJS in Java 8?

Answer»

As part of Java 8, JJS is a command-line tool that helps to execute the JavaScript CODE in the console. Below is the example of CLI commands:

JAVA>jjs
jjs> print("Hello, Java 8 - I am the new JJS!")
Hello, Java 8 - I am the new JJS!
jjs> quit()
>>

Conclusion

All in all, Java is a prevalent programming language securing the second rank in popularity in both TIOBE and PYPL programming language ranking. The world's leading tech giants like Twitter, LinkedIn, Amazon, PayPal, etc., use Java to build their web apps and backend web systems. Java is also one of the primary languages used to develop Android apps; an operating system backed and promoted by Google.

As of today, there are 1,751,661 questions AROUND Java on StackOverflow and 123,776 Java public repositories on GitHub and continuously increasing. Considering Java 8 to be one of the most stable versions, there are immense CAREER opportunities and scope in the same. Just understand the concepts, implement them and get ready for the interviews!

Additional Resources

  • Practice Coding
  • Java MCQ
  • Java Tutorials
  • Spring Boot Interview Questions
  • Hibernate Interview Questions
  • How To Become A Java Developer
  • Online Java Compiler
  • Features of Java
  • Java 9 Features
  • Java IDEs
  • Java Frameworks
  • Highest Paying Jobs In India (IT Sector)
2.

Define Nashorn in Java 8

Answer»

NASHORN is a JavaScript processing engine that is bundled with JAVA 8. It provides better compliance with ECMA (European COMPUTER MANUFACTURERS Association) normalized JavaScript specifications and better performance at run-time than older versions.

3.

Explain with example, LocalDate, LocalTime, and LocalDateTime APIs.

Answer»

LocalDate

  • Date with no TIME component
  • Default format - yyyy-MM-dd (2020-02-20)
  • LocalDate today = LocalDate.now();  // gives today’s date
  • LocalDate aDate = LocalDate.of(2011, 12, 30); //(year, month, date)

LocalTime

  • Time with no date with nanosecond precision
  • Default format - hh:mm:ss:zzz (12:06:03.015) nanosecond is optional
  • LocalTime now = LocalTime.now();  // gives time now
  • LocalTime aTime2 = LocalTime.of(18, 20, 30); // (HOURS, min, SEC)

LOCALDATETIME

  • Holds both Date and Time
  • Default format - yyyy-MM-dd-HH-mm-ss.zzz (2020-02-20T12:06:03.015)
  • LocalDateTime TIMESTAMP = LocalDateTime.now(); // gives timestamp now
  • //(year, month, date, hours, min, sec)
  • LocalDateTime dt1 = LocalDateTime.of(2011, 12, 30, 18, 20, 30);
4.

What are the important packages for the new Data and Time API?

Answer»
  • java.time
  • Java.time.format
  • Java.time.temporal
  • java.time.zone
5.

What is the feature of the new Date and Time API in Java 8?

Answer»
  • Immutable CLASSES and Thread-safe 
  • Timezone support
  • Fluent methods for OBJECT CREATION and arithmetic
  • Addresses I18N issue for earlier APIs
  • Influenced by POPULAR joda-time package
  • All packages are based on the ISO-8601 CALENDAR system
6.

How are Collections different from Stream?

Answer»

Collections are the SOURCE for the Stream. Java 8 collection API is enhanced with the default methods RETURNING Stream<T&GT; from the collections.

CollectionsStreams
Data structure holds all the data elementsNo data is stored. Have the capacity to process an infinite number of elements on demand
External IterationInternal Iteration
Can be PROCESSED any number of timesTraversed only once
Elements are easy to accessNo direct way of accessing specific elements
Is a data storeIs an API to process the data
7.

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

Answer»
FINDFIRST()findAny()
RETURNS the first element in the StreamReturn any element from the Stream
Deterministic in NATURENon-deterministic in nature
8.

What is the most common type of Terminal operations?

Answer»
  • collect() - Collects single result from all elements of the stream sequence.
  • reduce() - PRODUCES a single result from all elements of the stream sequence
    • count() - Returns the number of elements on the stream.
    • min() - Returns the min ELEMENT from the stream.
    • max() - Returns the max element from the stream.
  • Search/Query operations
    • anyMatch() , noneMatch() , allMatch() , ... - Short-circuiting operations.
    • Takes a Predicate as input for the match condition.
    • Stream processing will be STOPPED, as and when the result can be determined.
  • Iterative operations
    • forEach() - Useful to do something with each of the Stream elements. It accepts a consumer.
    • forEachOrdered() - It is helpful to maintain order in PARALLEL streams.
9.

What is the stateful intermediate operation? Give some examples of stateful intermediate operations.

Answer»

To complete some of the intermediate operations, some state is to be MAINTAINED, and such intermediate operations are called stateful intermediate operations. PARALLEL execution of these types of operations is complex.

For Eg: sorted() , DISTINCT() , limit() , skip() etc. 

Sending data elements to further steps in the pipeline stops TILL all the data is sorted for sorted() and stream data elements are stored in temporary data structures.

10.

What are the most commonly used Intermediate operations?

Answer»

Filter(Predicate<T>) - Allows selective processing of Stream elements. It returns elements that are satisfying the supplied condition by the predicate.

map(Funtion<T, R>) - Returns a new Stream, transforming each of the elements by applying the supplied MAPPER function.= SORTED() - Sorts the input elements and then passes them to the next stage.

distinct() - Only pass on elements to the next stage, not PASSED yet.

limit(long maxsize) - Limit the stream size to maxsize.

skip(long start) - Skip the initial elements till the start.

peek(Consumer) - Apply a consumer WITHOUT MODIFICATION to the stream.

flatMap(mapper) - Transform each element to a stream of its constituent elements and flatten all the streams into a single stream.

11.

What are Intermediate and Terminal operations?

Answer»

Intermediate Operations:

  • Process the stream elements.
  • Typically transforms a stream into another stream.
  • Are lazy, i.e., not executed TILL a terminal operation is invoked.
  • Does internal iteration of all source elements.
  • Any number of operations can be chained in the processing pipeline.
  • Operations are applied as per the DEFINED order.
  • Intermediate operations are mostly lambda functions.

Terminal Operations:

  • Kick-starts the Stream pipeline.
  • used to COLLECT the processed Stream data.
int count = Stream.of(1, 2, 3, 4, 5).filter(i -&GT; i &LT;4) // Intermediate Operation filter.count(); // Terminal Operation count
12.

What are the sources of data objects a Stream can process?

Answer»

A Stream can process the following data:

  • A COLLECTION of an Array.
  • An I/O channel or an input device.
  • A REACTIVE source (e.g., COMMENTS in social MEDIA or tweets/re-tweets) 
  • A stream generator function or a static factory.
13.

What are the main components of a Stream?

Answer»

COMPONENTS of the STREAM are:

Components of Stream
14.

What are Java 8 streams?

Answer»

A stream is an ABSTRACTION to express data processing queries in a declarative way. 

A Stream, which represents a sequence of data objects & series of operations on that data is a data pipeline that is not related to Java I/O Streams does not hold any data permanently.
The key interface is java.util.stream.Stream<T>. It accepts Functional INTERFACES so that lambdas can be passed. Streams SUPPORT a fluent interface or chaining. Below is the basic stream timeline MARBLE diagram:

Java 8 Streams
15.

What are the advantages of using the Optional class?

Answer»

Below are the main advantage of using the Optional CLASS

It encapsulates optional values, i.e., null or not-null values, which helps in avoiding null checks, which results in better, READABLE, and robust code It acts as a WRAPPER around the object and RETURNS an object instead of a value, which can be used to avoid run-time NullPointerExceptions.

16.

What is an Optional class?

Answer»

Optional is a container type which MAY or may not contain value i.e. zero(null) or one(not-null) value. It is PART of java.util package. There are pre-defined methods like isPresent(), which returns true if the value is present or ELSE false and the method get(), which will return the value if it is present.

static Optional<String&GT; changeCase(String WORD) {if (name != null && word.startsWith("A")) { return Optional.of(word.toUpperCase()); }else {return Optional.ofNullable(word); // someString can be null}}Optional Class
17.

What does the String::ValueOf expression mean?

Answer»

It is a static METHOD reference to method Valueof() of class STRING. It will return the string representation of the ARGUMENT passed.

18.

In Java 8, what is Method Reference?

Answer»

Method reference is a compact way of referring to a method of FUNCTIONAL interface. It is USED to refer to a method without invoking it. :: (DOUBLE colon) is used for describing the method reference. The syntax is class::methodName

For e.g.: 

Integer::parseInt(str) \\ method reference

str -> Integer.ParseInt(str); \\ EQUIVALENT lambda

19.

What are the types and common ways to use lambda expressions?

Answer»

A lambda expression does not have any specific type by itself. A lambda expression RECEIVES type once it is assigned to a functional INTERFACE. That same lambda expression can be assigned to different functional interface types and can have a different type.

For eg consider expression s -> s.isEmpty() :

PREDICATE<String> stringPredicate = s -> s.isEmpty(); 
Predicate<List> listPredicate = s -> s.isEmpty();
Function<String, Boolean> func = s -> s.isEmpty();
Consumer<String> stringConsumer = s -> s.isEmpty();

Common ways to USE the expression

Assignment to a functional Interface —> Predicate<String> stringPredicate = s -> s.isEmpty();
Can be passed as a parameter that has a functional type —> stream.filter(s -> s.isEmpty())
Returning it from a function —> RETURN s -> s.isEmpty()
Casting it to a functional type —> (Predicate<String>) s -> s.isEmpty()

20.

What is a type interface?

Answer»

Type INTERFACE is available even in earlier versions of JAVA. It is used to infer the type of argument by the compiler at the compile TIME by LOOKING at method INVOCATION and corresponding declaration.

21.

What are the features of a lambda expression?

Answer»

Below are the two SIGNIFICANT features of the METHODS that are defined as the lambda expressions: 

  • Lambda expressions can be passed as a parameter to ANOTHER METHOD
  • Lambda expressions can be standalone without belonging to any class.
22.

What is the basic structure/syntax of a lambda expression?

Answer»

FunctionalInterface fi = (String name) -> { System.out.println("Hello "+name); RETURN "Hello "+name; }

Lambda expression can be divided into three distinct parts as below:

1. List of Arguments/PARAMS:

(String name) 

A list of params is PASSED in () round brackets. It can have zero or more params. Declaring the type of PARAMETER is optional and can be inferred for the context. 

2. Arrow Token:

-> 
Arrow token is known as the lambda arrow operator. It is used to separate the parameters from the body, or it points the list of arguments to the body. 3. Expression/Body:

{ System.out.println("Hello "+name); return "Hello "+name; }

A body can have expressions or statements. {} curly BRACES are only required when there is more than one line. In one statement, the return type is the same as the return type of the statement. In other cases, the return type is either inferred by the return keyword or void if nothing is returned.