This has referred to all above answers and comments and tries to put it together as a complete guidance.
It is straight forward to have jdk installed directly in WSL2 Linux therefore we skip this option here.
It is perfectly okay to use/share the Windows JDK with WSL2 Linux, you just need to setup two things, JAVA_HOME and PATH in your Linux shell profile, in my case, ~/.bashrc.
STEP 1: check your Windows Java location
By default it is installed in here (version can be different) C:\Program Files\Java\jdk1.8.0_321
WSL2 will be able to access to this Windows file location in such format /mnt/c/Program Files/Java/jdk1.8.0_321
Therefore,
STEP 2: load this with your shell profile,
Edit this file,
$ sudo nano ~/.bashrc
by adding following to its bottom
export JAVA_HOME="/mnt/c/Program Files/Java/jdk1.8.0_321"
export PATH=$JAVA_HOME/bin:$PATH
export alias java='java.exe'
export alias javac='javac.exe'
save it by Ctrl/CMD + O then Enter
Exit nano editor by Ctrl/CMD + X
Refresh the profile to load added variables by
$ source ~/.bashrc
There you go. You can now verify it is working by
$ java -version
It will give you something similar to following,
java version "1.8.0_321"
Java(TM) SE Runtime Environment (build 1.8.0_321-b07)
Java HotSpot(TM) 64-Bit Server VM (build 25.321-b07, mixed mode)
Summary
You have done three things in total here,
- Defined your $JAVA_HOME as using the Windows installation of jdk
to verify this:
$ echo $JAVA_HOME
/mnt/c/Program Files/Java/jdk1.8.0_321
- Defined a user scope $PATH variable to let apps know where to find java compiler
to verify this:
$ echo $PATH
/mnt/c/Program Files/Java/jdk1.8.0_321/bin:...
- Set up alias to call java like you having it directly on Linux by call
java instead of java.exe
to verify this:
$ java -version
java version "1.8.0_321"
Java(TM) SE Runtime Environment (build 1.8.0_321-b07)
Java HotSpot(TM) 64-Bit Server VM (build 25.321-b07, mixed mode)
Unfortunately this will make you do something like which java. In order to do this as for native Linux software, you might want to follow further steps like in here (not verified): https://stackoverflow.com/a/64489793/3107052 You however really don't need this as this won't do anything more than telling you where is your java that was borrowed from Windows.