Converting between java.time.LocalDateTime and java.util.Date

Short answer: Explanation: (based on this question about LocalDate) Despite its name, java.util.Date represents an instant on the time-line, not a “date”. The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC). The equivalent class to java.util.Date in JSR-310 is Instant, thus there are convenient methods to provide the conversion to and fro: … Read more

Reason for the exception java.lang.VerifyError: Bad type on operand stack

The problem arises because your lambda expression does not reference this or a member of this but a member of the outer this. Had you written class B like the compiler rejected it without any doubts as accessing innerData implies accessing this. The point about the outer instance is that it is a constant which is even available when the inner instance has not been fully … Read more

:: (double colon) operator in Java 8

Usually, one would call the reduce method using Math.max(int, int) as follows: That requires a lot of syntax for just calling Math.max. That’s where lambda expressions come into play. Since Java 8 it is allowed to do the same thing in a much shorter way: How does this work? The java compiler “detects”, that you want to implement a method … Read more

How to install Java 8 on Mac

Oracle has a poor record for making it easy to install and configure Java, but using Homebrew, the latest OpenJDK (Java 14) can be installed with: For the many use cases depending on an older version (commonly Java 8), the AdoptOpenJDK project makes it possible with an extra step. Existing users of Homebrew may encounter Error: Cask adoptopenjdk8 exists … Read more

What does the arrow operator, ‘->’, do in Java?

That’s part of the syntax of the new lambda expressions, to be introduced in Java 8. There are a couple of online tutorials to get the hang of it, here’s a link to one. Basically, the -> separates the parameters (left-side) from the implementation (right side). The general syntax for using lambda expressions is (Parameters) -> { Body } where … Read more

typeof in Java 8

You can use the getClass() method to get the type of the object you are using: This will generate the following output: As you see it will show the type of the object which is referenced by the variable, which might not be the same as the type of the variable (Object in this case). For primitive types … Read more

Java 8 Iterable.forEach() vs foreach loop

The better practice is to use for-each. Besides violating the Keep It Simple, Stupid principle, the new-fangled forEach() has at least the following deficiencies: Can’t use non-final variables. So, code like the following can’t be turned into a forEach lambda: Can’t handle checked exceptions. Lambdas aren’t actually forbidden from throwing checked exceptions, but common functional … Read more