Search code examples
javacmdjavac

Can't run a java file using javac


I've got the same problem as the user who posted this question. I am trying to run a Java file on a Windows machine using Command Prompt, but I'm having no success using any of the information I've gleaned from the linked question, nor from WikiHow, nor from this user on another site with the same problem.

Here are the steps I've taken.

  1. I've created a Java file using Notepad, called HelloWorld.java, and saved it in a folder called "Java". The file directory is C:\Users\[myname]\Google Drive\Java. The code in the file is a simple Hello World as below:

    class HelloWorld {
        public static void main(String[] args) {
            System.out.println("Hello World!");
        }
    }
    
  2. I've downloaded Java version 8, and the latest version of the Java JDK (14.0.1) from the website. I previously had the JDK 12.x.x installed, so I uninstalled that.

  3. I've opened System Properties > Advanced > Environment Variables, gone to the "Path" variable in "System variables", clicked "Edit" and added a new environment variable, which was the path to the JDK bin: C:\Program Files\Java\jdk-14.0.1\bin. I then clicked "Move Up" until this variable was at the top.

  4. After clicking OK and closing this window, I've opened Command Prompt, typed set path=C:\Users\[myname]\Google Drive\Java in order to (I imagine) set the path to where my HelloWorld.java file is. I've typed in path to confirm that this has worked.

  5. I've typed in Command Prompt javac HelloWorld.java. When I hit Enter, I get the output:

    'javac' is not recognized as an internal or external command,
    operable program or batch file.
    

I'm honestly not sure what steps are left to take. Is there a simple fix to get this file to run?


Solution

  • Steps

    1. Setup the environment variables properly. In the Path System variable, you should add the path to bin directory. Something like C:\Program Files\Java\jdk-11.0.5\bin and then, you need to define a new system variable with name JAVA_HOME and point it to the java installation directory, not the bin directory. Something like C:\Program Files\Java\jdk-11.0.5
    2. You need NOT use the Set command, as of now environment variables are set. Open up a new powershell or command prompt and type java -version. If this prints the java version, then you are good to go with the next steps.
    3. Go to your directory where your java class resides. Open up a powershell window there, with shift + right click and open Powershell window here option. Then type javac HelloWorld.java
    4. To run programme, java HelloWorld