How to know JDK version from within Java code
4 Answers
Since java 9
System.out.println(Runtime.version());
Prints something like 17.0.2+8-86
or if you need more
System.out.println("Java Feature Version = " + Runtime.version().feature());
System.out.println("Java Interim Version = " + Runtime.version().interim());
System.out.println("Java Update Version = " + Runtime.version().update());
System.out.println("Java Version Build = " + Runtime.version().build().map(String::valueOf).orElse("Unknown"));
System.out.println("Java Version Pre-Release Info = " + Runtime.version().pre().orElse("N/A"));
Prints
Java Feature Version = 17
Java Interim Version = 0
Java Update Version = 2
Java Version Build = 8
Java Version Pre-Release Info = N/A
Comments
Relying on the java.version string for anything else than showing to a human is fragile and will break if running on another Java implementation.
The only reliable way programatically is to use reflection to carefully ask if a given facility is available, and then select the appropriate code accordingly.
13 Comments
Jesse Barnum
Can you give an example of when this would fail?
Thorbjørn Ravn Andersen
@Jesse, I'd rather put it the other way around. What rule would you set up for analyzing the java.version string?
Thorbjørn Ravn Andersen
@Jesse, I was unaware of this property. I can, however, not see from a quick look in the JLS that it is guaranteed to be present and containing a valid number. Perhaps you know where it says so?
Thorbjørn Ravn Andersen
@Jesse, the crucial question here if this is for Hotspot-based JVM's only. I cannot immediately tell.
Mark Jeronimus
Don't use
Float.valueOf like @JesseBarnum. This failed for me because 1.8>=1.8 returned false for me, due to round-off errors. Use .compareTo("1.8")>=0 instead. |