EzDevInfo.com

java-8 interview questions

Top java-8 frequently asked interview questions

:: (double colon) operator in Java 8

I was exploring the Java 8 source and found this particular part of code very surprising:

//defined in IntPipeline.java
@Override
public final OptionalInt reduce(IntBinaryOperator op) {
    return evaluate(ReduceOps.makeInt(op));
}

@Override
public final OptionalInt max() {
    return reduce(Math::max); //this is the gotcha line
}

//defined in Math.java
public static int max(int a, int b) {
    return (a >= b) ? a : b;
}

Is Math::max something like a method pointer? How does a normal static method get converted to IntBinaryOperator?


Source: (StackOverflow)

Is it possible to use Java 8 for Android development?

Searching the web, it is not clear if Java 8 is supported for Android development or not.

Before I download/setup Java 8, can some one point me at any "official" documentation that say Java 8 is or is not supported for Android development.


Source: (StackOverflow)

Advertisements

Maven is not working in Java 8 when JavaDoc tags are incomplete

Since I use Maven I have been able to build and install in my local repository projects that have incomplete java doc tags (for example, a missing parameter).

However, since I migrated to Java 8 (1.8.0-ea-b90) Maven is absolutely strict about missing documentation tags and show me lots of JavaDoc errors related to JavaDoc problems when I try to build or install a project where the JavaDoc is not "perfect". Some of the projects I am trying to compile and install in my local repository are third party projects from which I do not have control. So the workaround of just fixing all the javadocs in all these projects does not seem to be feasable in my scenario.

This is a small part of the output I see when I execute mvn clean package install in my project:

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 9.026s
[INFO] Finished at: Mon Apr 08 21:06:17 CEST 2013
[INFO] Final Memory: 27M/437M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:2.9:jar (attach-javadocs) on project jpc: MavenReportException: Error while creating archive:
[ERROR] Exit code: 1 - /Users/sergioc/Documents/workspaces/heal/jpc/src/main/java/org/jpc/engine/prolog/PrologDatabase.java:10: error: @param name not found
[ERROR] * @param terms the terms to assert
[ERROR] ^
[ERROR] /Users/sergioc/Documents/workspaces/heal/jpc/src/main/java/org/jpc/engine/prolog/PrologDatabase.java:11: warning: no description for @return
[ERROR] * @return
[ERROR] ^

The JavaDoc plugin is configured like this in my POM:

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.9</version>
        <executions>
            <execution>
                <id>attach-javadocs</id>
                <goals>
                    <goal>jar</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

As I said before, everything is working fine if I go back to Java 7. Maybe is this a bug related to Maven running in Java 8 ? How could I make it work (i.e., being able to build the Javadoc of the project and install its code in my local repository) with Java 8 ? I have tested with both Maven 3.0.3 and 3.0.5 in OSX.

UPDATE:

If I change my JavaDoc plugin configuration with <failOnError>false</failOnError> (thanks Martin):

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.9</version>
        <executions>
            <execution>
                <id>attach-javadocs</id>
                <goals>
                    <goal>jar</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

Then the project is installed in my local repository. However, the javadoc jar is still not generated:

A fragment of the output I see in the console with this new configuration is:

[ERROR] MavenReportException: Error while creating archive: Exit code: 1 - /Users/....java:18: warning: no @param ... Command line was: /Library/Java/Home/bin/javadoc @options @packages

Refer to the generated Javadoc files in '/Users/sergioc/Documents/workspaces/heal/minitoolbox/target/apidocs' dir.

at org.apache.maven.plugin.javadoc.AbstractJavadocMojo.executeJavadocCommandLine(AbstractJavadocMojo.java:5043) at org.apache.maven.plugin.javadoc.AbstractJavadocMojo.executeReport(AbstractJavadocMojo.java:1990) at org.apache.maven.plugin.javadoc.JavadocJar.execute(JavadocJar.java:181) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59) at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196) at org.apache.maven.cli.MavenCli.main(MavenCli.java:141) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:491) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)

Any workaround about how to build the sources, install the project and generate the Java doc jar in one step as it was working with Java 7 ?


Source: (StackOverflow)

Interface with default methods vs Abstract class in Java 8

As Java 8 allows for default implementation of methods in interface called Default Methods, there seems to be a confusion between when would I use a abstract class.

So when should interface with default methods be used and when should an abstract class be used? Are the abstract classes still useful in that scenario?


Source: (StackOverflow)

Why is "final" not allowed in Java 8 interface methods?

One of the most useful features of Java 8 are the new default methods on interfaces. There are essentially two reasons (there may be others) why they have been introduced:

From an API designer's perspective, I would have liked to be able to use other modifiers on interface methods, e.g. final. This would be useful when adding convenience methods, preventing "accidental" overrides in implementing classes:

interface Sender {

    // Convenience method to send an empty message
    default final void send() {
        send(null);
    }

    // Implementations should only implement this method
    void send(String message);
}

The above is already common practice if Sender were a class:

abstract class Sender {

    // Convenience method to send an empty message
    final void send() {
        send(null);
    }

    // Implementations should only implement this method
    abstract void send(String message);
}

Now, default and final are obviously contradicting keywords, but the default keyword itself would not have been strictly required, so I'm assuming that this contradiction is deliberate, to reflect the subtle differences between "class methods with body" (just methods) and "interface methods with body" (default methods), i.e. differences which I have not yet understood.

At some point of time, support for modifiers like static and final on interface methods was not yet fully explored, citing Brian Goetz:

The other part is how far we're going to go to support class-building tools in interfaces, such as final methods, private methods, protected methods, static methods, etc. The answer is: we don't know yet

Since that time in late 2011, obviously, support for static methods in interfaces was added. Clearly, this added a lot of value to the JDK libraries themselves, such as with Comparator.comparing().

Question:

What is the reason final (and also static final) never made it to Java 8 interfaces?


Source: (StackOverflow)

Java 8 Iterable.forEach() vs foreach loop

Which of the following is better practice in Java 8?

Java8:

joins.forEach((join) -> mIrc.join(mSession, join));

Java7:

for (String join : joins) {
    mIrc.join(mSession, join);
}

I have lots of for loops that could be "simplified" with lambdas, but is there really any advantage of using them including performance and readability?

EDIT

I'll also extend this question to longer methods - I know that you cant return or break the parent function from a lambda and this should be mentioned to if they are compared, but is there anything else to be considered?


Source: (StackOverflow)

Retrieving a List from a java.util.stream.Stream in Java8

I was playing around with Java 8 lambdas to easily filter collections. But I did not find a concise way to retrieve the result as a new list within the same statement. Here is my most concise approach so far:

List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
List<Long> targetLongList = new ArrayList<>();
sourceLongList.stream().filter(l -> l > 100).forEach(targetLongList::add);

Examples on the net did not answer my question because they stop without generating a new result list. There must be a more concise way. I would have expected, that the Stream class has methods as toList(), toSet(), ...

Is there a way that the variables targetLongList can be directly be assigned by the third line?


Source: (StackOverflow)

Java 8 List into Map

I want to translate a List of objects into a Map using Java 8's streams and lambdas.

This is how I would write it in Java 7 and below.

private Map<String, Choice> nameMap() {
        final Map<String, Choice> hashMap = new HashMap<>();
        for (final Choice choice : choices) {
            hashMap.put(choice.getName(), choice);
        }
        return hashMap;
}

I can accomplish this easily using Java 8 and Guava but I would like to know how to do this without Guava.

In Guava:

private Map<String, Choice> nameMap() {
    return Maps.uniqueIndex(choices, new Function<Choice, String>() {

        @Override
        public String apply(final Choice input) {
            return input.getName();
        }
    });
}

And Guava with Java 8 lambdas.

private Map<String, Choice> nameMap() {
    return Maps.uniqueIndex(choices, c -> c.getName());
}

Source: (StackOverflow)

What is the reason why “synchronized” is not allowed in Java 8 interface methods?

In Java 8, I can easily write:

interface Interface1 {
    default void method1() {
        synchronized (this) {
            // Something
        }
    }

    static void method2() {
        synchronized (Interface1.class) {
            // Something
        }
    }
}

I will get the full synchronisation semantics that I can use also in classes. I cannot, however, use the synchronized modifier on method declarations:

interface Interface2 {
    default synchronized void method1() {
        //  ^^^^^^^^^^^^ Modifier 'synchronized' not allowed here
    }

    static synchronized void method2() {
        // ^^^^^^^^^^^^ Modifier 'synchronized' not allowed here
    }
}

Now, one can argue that the two interfaces behave the same way except that Interface2 establishes a contract on method1() and on method2(), which is a bit stronger than what Interface1 does. Of course, we might also argue that default implementations should not make any assumptions about concrete implementation state, or that such a keyword simply wouldn't pull its weight.

Question:

What is the reason why the JSR-335 expert group decided not to support synchronized on interface methods?


Note, before this question is eagerly closed: To fit Stack Overflow's Q&A format: I'm looking for authoritative citations only, not speculation. An authoritative answer to this question will likely help many future visitors of this question, so please do not close it eagerly.


Source: (StackOverflow)

Why is Cloneable not deprecated?

It is commonly understood that Cloneable interface in Java is broken. There are many reasons for this, which I will not mention; others already did it. It is also the position of Java architects themselves.

My question is therefore: why has is not been deprecated yet? If the core Java team have decided that it is broken, then they must also have considered deprecation. What are their reasons against doing so (in Java 8 it is still not deprecated)?


Source: (StackOverflow)

Custom thread pool in Java 8 parallel stream

Is it possible to specify a custom thread pool for Java 8 parallel stream? I can not find it anywhere.

Imagine that I have a server application and I would like to use parallel streams. But the application is large and multi-threaded so I want to compartmentalize it. I do not want a slow running task in one module of the applicationblock tasks from another module.

If I can not use different thread pools for different modules, it means I can not safely use parallel streams in most of real world situations.

Try the following example. There are some CPU intensive tasks executed in separate threads. The tasks leverage parallel streams. The first task is broken, so each step takes 1 second (simulated by thread sleep). The issue is that other threads get stuck and wait for the broken task to finish. This is contrived example, but imagine a servlet app and someone submitting a long running task to the shared fork join pool.

public class ParallelTest {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService es = Executors.newCachedThreadPool();

        es.execute(() -> runTask(1000)); //incorrect task
        es.execute(() -> runTask(0));
        es.execute(() -> runTask(0));
        es.execute(() -> runTask(0));
        es.execute(() -> runTask(0));
        es.execute(() -> runTask(0));


        es.shutdown();
        es.awaitTermination(60, TimeUnit.SECONDS);
    }

    private static void runTask(int delay) {
        range(1, 1_000_000).parallel().filter(ParallelTest::isPrime).peek(i -> Utils.sleep(delay)).max()
                .ifPresent(max -> System.out.println(Thread.currentThread() + " " + max));
    }

    public static boolean isPrime(long n) {
        return n > 1 && rangeClosed(2, (long) sqrt(n)).noneMatch(divisor -> n % divisor == 0);
    }
}

Source: (StackOverflow)

Convert java.util.Date to java.time.LocalDate

What is the best way to convert a java.util.Date object to the new JDK 8/JSR-310 java.time.LocalDate?

Date input = new Date();
LocalDate date = ???

Source: (StackOverflow)

PermGen elimination in JDK 8

I have installed JDK 8 and trying to run Eclipse. I am getting following warning message:

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512m;
support was removed in 8.0 

What are the reasons of ignoring this argument?


Source: (StackOverflow)

Difference between final and effectively final

I'm playing with lambdas in Java 8 and I came across warning local variables referenced from a lambda expression must be final or effectively final. I know that when I use variables inside anonymous class they must be final in outer class, but still - what is the difference between final and effectively final?


Source: (StackOverflow)

Java 8 stream's .min() and .max(): why does this compile?

Note: this question originates from a dead link which was a previous SO question, but here goes...

See this code (note: I do know that this code won't "work" and that Integer::compare should be used -- I just extracted it from the linked question):

final ArrayList <Integer> list 
    = IntStream.rangeClosed(1, 20).boxed().collect(Collectors.toList());

System.out.println(list.stream().max(Integer::max).get());
System.out.println(list.stream().min(Integer::min).get());

According to the javadoc of .min() and .max(), the argument of both should be a Comparator. Yet here the method references are to static methods of the Integer class.

So, why does this compile at all?


Source: (StackOverflow)