Java FAQ: How to determine the Java version running your application

Java FAQ: "How can I tell what version of Java is running my program?"

Answer: Just use this line of source code to determine the version of Java that is running your program:

String javaVersion = System.getProperty("java.version");

More information

Because the capabilities of the JVM/JRE change in each Java version, it can be very important to know which Java version is currently running your program. I find this to be especially true in Swing applications, where an important bug can easily be fixed (or at least changed) in a minor version release.

Here's the source code for a complete Java program that demonstrates how to determine the Java version from within the application:

package com.devdaily;

public class JavaVersionTest
{
  public static void main(String[] args)
  {
    String javaVersion = System.getProperty("java.version");
    System.out.format("Java Version = '%s'", javaVersion);
  }
}

On my Mac OS X 10.5.7 system, this program produces the following output:

Java Version = '1.5.0_16'

Once you have this version information, you can parse that String however you want to. One simple way is to use the startsWith method of the String class, like this:

if (javaVersion.startsWith("1.5"))
{
  // do whatever you need to deal with java 1.5.x
}