Compile and run java program windows

How to Compile and Run your First Java Program

By Chaitanya Singh | Filed Under: Learn Java

In this tutorial, we will see how to write, compile and run a java program. I will also cover java syntax, code conventions and several ways to run a java program.

Simple Java Program:

Output: This is my first program in java

How to compile and run the above program

Prerequisite: You need to have java installed on your system. You can get the java from here.

Step 1: Open a text editor, like Notepad on windows and TextEdit on Mac. Copy the above program and paste it in the text editor.

You can also use IDE like Eclipse to run the java program but we will cover that part later in the coming tutorials. For the sake of simplicity, I will only use text editor and command prompt (or terminal) for this tutorial

Step 2: Save the file as FirstJavaProgram.java. You may be wondering why we have named the file as FirstJavaProgram, the thing is that we should always name the file same as the public class name. In our program, the public class name is FirstJavaProgram , that’s why our file name should be FirstJavaProgram.java.

Step 3: In this step, we will compile the program. For this, open command prompt (cmd) on Windows, if you are Mac OS then open Terminal.
To compile the program, type the following command and hit enter.

You may get this error when you try to compile the program: “javac’ is not recognized as an internal or external command, operable program or batch file“. This error occurs when the java path is not set in your system

If you get this error then you first need to set the path before compilation.

Set Path in Windows:
Open command prompt (cmd), go to the place where you have installed java on your system and locate the bin directory, copy the complete path and write it in the command like this.

Note: Your jdk version may be different. Since I have java version 1.8.0_121 installed on my system, I mentioned the same while setting up the path.

Set Path in Mac OS X
Open Terminal, type the following command and hit return.

Type the following command on terminal to confirm the path.

The steps above are for setting up the path temporary which means when you close the command prompt or terminal, the path settings will be lost and you will have to set the path again next time you use it. I will share the permanent path setup guide in the coming tutorial.

Step 4: After compilation the .java file gets translated into the .class file(byte code). Now we can run the program. To run the program, type the following command and hit enter:

Note that you should not append the .java extension to the file name while running the program.

Closer look to the First Java Program

Now that we have understood how to run a java program, let have a closer look at the program we have written above.

This is the first line of our java program. Every java application must have at least one class definition that consists of class keyword followed by class name. When I say keyword, it means that it should not be changed, we should use it as it is. However the class name can be anything.

Читайте также:  Как удалить стрелочку с ярлыков рабочего стола windows 10

I have made the class public by using public access modifier, I will cover access modifier in a separate post, all you need to know now that a java file can have any number of classes but it can have only one public class and the file name should be same as public class name.

This is our next line in the program, lets break it down to understand it:
public : This makes the main method public that means that we can call the method from outside the class.

static : We do not need to create object for static methods to run. They can run itself.

void : It does not return anything.

main : It is the method name. This is the entry point method from which the JVM can run your program.

(String[] args) : Used for command line arguments that are passed as strings. We will cover that in a separate post.

This method prints the contents inside the double quotes into the console and inserts a newline after.

Checkout these basic java programs before reading next topic:

How do I run a Java program from the command line on Windows?

I’m trying to execute a Java program from the command line in Windows. Here is my code:

I’m not sure how to execute the program — any help? Is this possible on Windows? Why is it different than another environment (I thought JVM was write once, run anywhere)?

12 Answers 12

Let’s say your file is in C:\mywork\

Run Command Prompt

This makes C:\mywork the current directory.

This displays the directory contents. You should see filenamehere.java among the files.

This tells the system where to find JDK programs.

This runs javac.exe, the compiler. You should see nothing but the next system prompt.

javac has created the filenamehere.class file. You should see filenamehere.java and filenamehere.class among the files.

This runs the Java interpreter. You should then see your program output.

If the system cannot find javac, check the set path command. If javac runs but you get errors, check your Java text. If the program compiles but you get an exception, check the spelling and capitalization in the file name and the class name and the java HelloWorld command. Java is case-sensitive!

To complete the answer :

Compile the Java File to a *.class file

  • This will create a TheJavaFile.class file

Execution of the Java File

Creation of an executable *.jar file

You’ve got two options here —

With an external manifest file :

Create the manifest file say — MANIFEST.mf

The MANIFEST file is nothing but an explicit entry of the Main Class

jar -cvfm TheJavaFile.jar MANIFEST.mf TheJavaFile.class

Executable by Entry Point:

To run the Jar File

In case your Java class is in some package. Suppose your Java class named ABC.java is present in com.hello.programs , then you need to run it with the package name.

Compile it in the usual way:

But to run it, you need to give the package name and then your java class name:

Complile a Java file to generate a class:

Execute the generated class:

Assuming the file is called «CopyFile.java», do the following:

The first line compiles the source code into executable byte code. The second line executes it, first adding the current directory to the class path (just in case).

Since Java 11, java command line tool has been able to run a single-file source-code directly. e.g.

This was an enhancement with JEP 330: https://openjdk.java.net/jeps/330

For the details of the usage and the limitations, see the manual of your Java implementation such as one provided by Oracle: https://docs.oracle.com/en/java/javase/11/tools/java.html

It is easy. If you have saved your file as A.text first thing you should do is save it as A.java. Now it is a Java file.

Читайте также:  What is windows mac and linux

Now you need to open cmd and set path to you A.java file before compile it. you can refer this for that.

Then you can compile your file using command

Then run it using

So that is how you compile and run a java program in cmd. You can also go through these material that is Java in depth lessons. Lot of things you need to understand in Java is covered there for beginners.

You can compile any java source using javac in command line ; eg, javac CopyFile.java. To run : java CopyFile. You can also compile all java files using javac *.java as long as they’re in the same directory

If you’re having an issue resulting with «could not find or load main class» you may not have jre in your path. Have a look at this question: Could not find or load main class

On Windows 7 I had to do the following:

quick way

  1. Install JDK http://www.oracle.com/technetwork/java/javase/downloads
  2. in windows, browse into «C:\Program Files\Java\jdk1.8.0_91\bin» (or wherever the latest version of JDK is installed), hold down shift and right click on a blank area within the window and do «open command window here» and this will give you a command line and access to all the BIN tools. «javac» is not by default in the windows system PATH environment variable.
  3. Follow comments above about how to compile the file («javac MyFile.java» then «java MyFile») https://stackoverflow.com/a/33149828/194872

long way

  1. Install JDK http://www.oracle.com/technetwork/java/javase/downloads/index.html
  2. After installing, in edits the Windows PATH environment variable and adds the following to the path C:\ProgramData\Oracle\Java\javapath. Within this folder are symbolic links to a handful of java executables but «javac» is NOT one of them so when trying to run «javac» from Windows command line it throws an error.
  3. I edited the path: Control Panel -> System -> Advanced tab -> «Environment Variables. » button -> scroll down to «Path», highlight and edit -> replaced the «C:\ProgramData\Oracle\Java\javapath» with a direct path to the java BIN folder «C:\Program Files\Java\jdk1.8.0_91\bin».

This likely breaks when you upgrade your JDK installation but you have access to all the command line tools now.

How to write, compile and run a hello world Java program for beginners

To start, all you need is a fresh computer without any Java software installed, a text-based editor and a good internet connection.

NOTES: This beginner tutorial is targeted for Windows environment.

1. Download and install Java Development Kit

    • JRE(Java Runtime Environment): is the core of the Java platform that enables running Java programs on your computer. The JRE includes JVM(Java Virtual Machine) that runs Java programs by translating from bytecode to platform-dependent code and executes them (Java programs are compiled into an intermediate form called bytecode), and other core libraries such as collections, File I/O, networking, etc.
    • Tools and libraries that support Java development.

The JDK ships with two powerful tools which every Java developer should be familiar with:

    • javac.exe : is Java compiler that translates programs written in Java code into bytecode form.
    • java.exe : is the Java Virtual Machine launcher that executes bytecode.

Click this link to download the latest version of JDK installer program:

Check the option “Accept License Agreement”, and choose an appropriate version for your computer from the list. Here we choose the version for Windows x64:

You would see the JDK is installed in the following directory, for example: C:\Program Files\Java\jdk1.7.0_21. The following screenshot describes the JDK’s directory structure:

Now let’s test if Java runtime is installed correctly. Open a command prompt window and type:

java -version

You would see the following result:

That shows version of the JRE, e.g. “1.7.0_21” — Congratulations! Your computer is now capable of running Java programs.

Now try to type the following command:

javac -version

You would see the following error:

That’s because Windows could not find the javac program, so we need to set some environment variables which tell the location of javac.exe .

2. Set up environment variables

Then click Advanced system settings:

The System Properties dialog appears, select Advanced tab and click Environment Variables. :

The Environment Variable dialog appears, click on the New… button under the System variables section.

That opens up the New System Variable dialog. Type the following information:

The field Variable name must be JAVA_HOME , and the field Variable value must point to JDK’s installation directory on your computer. Here it is set to c:\Program Files\Java\jdk1.7.0_21. Click OK to close this dialog.

Now back to the Environment Variables dialog, look for a variable called Path under the System Variables list, and click Edit…:

In the Edit System Variable dialog, append the following to the end of the field Variable value:

;%JAVA_HOME%\bin

Note that there is a semicolon at the beginning to separate this value from other ones. Click OK three times to close all the dialogs.

Now we have to quit the current command prompt and open a new one to see the changes takes effect. Type the following command again in the re-opened command prompt window:

javac -version

You would see the following output:

Congratulations! You have completed the setup for essential Java development environment on your computer. It’s now ready to write your first Java program.

3. Code a Java hello world program

Save the file as HelloWorld.java (note that the extension is .java ) under a directory, let’s say, C:\Java.

Don’t worry if you don’t understand everything in this simple Java code. The following picture explains it nicely:

Every Java program starts from the main() method. This program simply prints “Hello world” to screen.

4. Compile your first Java program

cd C:\Java

And type the following command:

javac HelloWorld.java

That invokes the Java compiler to compile code in the HelloWorld.java file into bytecode. Note that the file name ends with .java extension. You would see the following output:

If everything is fine (e.g. no error), the Java compiler quits silently, no fuss. After compiling, it generates the HelloWorld.class file which is bytecode form of the HelloWorld.java file. Now try to type dir in the command line, we’ll see the .class file:

So remember a Java program will be compiled into bytecode form (.class file).

5. Run your first Java program

java HelloWorld

That invokes the Java Virtual Machine to run the program called HelloWorld (note that there is no .java or .class extension). You would see the following output:

It just prints out “Hello world!” to the screen and quits. Congratulations! You have successfully run your first Java program!

6. What we have learnt so far

    • JDK is the Java SE Development Kit that contains tools and libraries for Java development.
    • JRE is the Java Runtime Environment that enables running Java programs on your computer.
    • JVM is the Java Virtual Machine that actually executes Java programs. With JVM, programs written in Java can run on multi-platforms (thus Java is called cross-platform language).
    • How to install JDK and configure environment variables.
    • javac is the Java compiler. It translates Java source code into bytecode.
    • java is the JVM launcher which we use to run our program.
    • Every Java program starts from the main() method.
    • When compiling, the compiler generates a .class file from a .java file.

You can also watch the video version of this tutorial:

Next, I recommend you to read this article: Understand Classes and Objects in Java

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Читайте также:  Linux append string to file
Оцените статью