How to you use a specific version of Java in Azure Devops Agent without downloading?

You can now also use the JavaToolInstaller task to activate one of the pre-installed Java versions, e.g.

- task: JavaToolInstaller@0
  inputs:
    versionSpec: '11'
    jdkArchitectureOption: 'x64'
    jdkSourceOption: 'PreInstalled'

See documentation at: https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/tool/java-tool-installer?view=azure-devops

It will also set JAVA_HOME and prepend the PATH, see source: https://github.com/microsoft/azure-pipelines-tasks/blob/46cca412451ac4418d6332114fca8ef8c3095de1/Tasks/JavaToolInstallerV0/javatoolinstaller.ts#L80


Add the following script before you run Maven for Unix based agents

- script: |
    echo "##vso[task.setvariable variable=JAVA_HOME]$(JAVA_HOME_11_X64)"
    echo "##vso[task.setvariable variable=PATH]$(JAVA_HOME_11_X64)/bin:$(PATH)"
  displayName: "Set java version"

For Windows based agents

- script: |
    echo "##vso[task.setvariable variable=JAVA_HOME]$(JAVA_HOME_11_X64)"
    echo "##vso[task.setvariable variable=PATH]$(JAVA_HOME_11_X64)\bin;$(PATH)"
  displayName: "Set java version"

This part of the pipeline code shows how the JAVA_HOME value is selected: https://github.com/microsoft/azure-pipelines-tasks/blob/master/Tasks/Common/java-common/java-common.ts


The Java version to be used can be set via env field of the task for Linux or macOS:

- script: |
    java -version
  env:
    JAVA_HOME: $(JAVA_HOME_8_X64)
    PATH: $(JAVA_HOME_8_X64)/bin:$(PATH)

and for Windows, change the colon in PATH to semicolon:

- script: |
    java -version
  env:
    JAVA_HOME: $(JAVA_HOME_8_X64)
    PATH: $(JAVA_HOME_8_X64)/bin;$(PATH)

Alternatives of Java version include:

  • JAVA_HOME_7_X64
    • Available on Windows: vs2017-win2016, windows-2019
    • Avaiable on macOS: macos-10.14, macos-10.15
    • Available on Linux: ubuntu-16.04, ubuntu-18.04
  • JAVA_HOME_8_X64
    • Available on Windows: vs2017-win2016, windows-2019
    • Available on macOS: macos-10.14, macos-10.15
    • Available on Linux: ubuntu-16.04, ubuntu-18.04, ubuntu-20.04
  • JAVA_HOME_11_X64
    • Available on Windows: vs2017-win2016, windows-2019
    • Available on macOS: macos-10.14, macos-10.15
    • Available on Linux: ubuntu-16.04, ubuntu-18.04, ubuntu-20.04
  • JAVA_HOME_12_X64
    • Available on macOS: macos-10.14, macos-10.15
    • Available on Linux: ubuntu-16.04, ubuntu-18.04
  • JAVA_HOME_13_X64
    • Available on Windows: vs2017-win2016, windows-2019
    • Available on macOS: macos-10.14, macos-10.15
  • JAVA_HOME_14_X64
    • Available on macOS: macos-10.14, macos-10.15