1

I am trying to work with jshell of Java 9. So for that i installed the JDK 9 on my Mac, where i already had the JDK 8 installed.

All my projects, workspaces, Hadoop, Spark and dependent APIs are using JDK 8. So for the current scenario, i can not move all my projects to work with JDK 9.

So what i want is a small utility or a smart way to switch between JDK 8 and JDK 9 on demand basis.

For the time being, what i am doing is:

  1. Open a terminal.

    kv:micro-tab karan.verma$ echo $JAVA_HOME
    /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home
    
  2. Set the JAVA_HOME temporarily to jdk 9

    kv:Home karan.verma$ export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home
    
  3. start the jshell

    kv:Home karan.verma$ jshell
       |  Welcome to JShell -- Version 9.0.1
       |  For an introduction type: /help intro
    
  4. close the terminal when done. That means, the global JAVA_HOME works now.

    kv:micro-tab karan.verma$ echo $JAVA_HOME
    /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home
    

So, my question is, Is there is any better approach to do it? Or this is the a good practice to do such kind of things? Please suggest.

KayV
  • 12,987
  • 11
  • 98
  • 148
  • Read https://stackoverflow.com/questions/26252591/mac-os-x-and-multiple-java-versions? If yes, please explain why is this not a duplicate? – Naman Dec 18 '17 at 07:46
  • But this question will always run on either on 8 or on 9. But what i want is to change to jdk 9 only when i want to run the jshell – KayV Dec 18 '17 at 09:35
  • The linked question is not a duplicate, since it assumes you use Mac, while this question is OS-agnostic and I would be helped by an answer working on Windows. – Benjamin Aug 11 '18 at 12:05

2 Answers2

0

You can write a script. Reset the env and start jshell in your path.

screen snap

#!/bin/sh

# path
export PATH=/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin

# java
export JAVA_HOME=/opt/jdk-11
export PATH=$JAVA_HOME/bin:$PATH

$JAVA_HOME/bin/jshell $@
wibeasley
  • 5,000
  • 3
  • 34
  • 62
徐志鹏
  • 121
  • 1
  • 3
0

Here is how i solved the issue:

  1. Uninstall JDK 9, install jdk 8 and then install jdk 9.

  2. Add the corresponding JAVA_HOME paths for version 8 and 9. Set alias for both of them and set Java 8 as the default JDK.

    export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8)
    export JAVA_9_HOME=$(/usr/libexec/java_home -v1.9)
    
    alias java8='export JAVA_HOME=$JAVA_8_HOME'
    alias java9='export JAVA_HOME=$JAVA_9_HOME'
    
    #default java8
    export JAVA_HOME=$JAVA_8_HOME
    
  3. Now simply set the java 8 or java 9 using the alias to switch between the versions as follows:

    java8
    java9
    
KayV
  • 12,987
  • 11
  • 98
  • 148