Open In App

How to Run the Java Code in Git Bash?

Last Updated : 23 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Git Bash is a command-line interface that provides a Unix-like environment on Windows. You can use it to compile and run Java programs just as you would in traditional terminals on Linux or macOS.

Step to Run Java Code in Git Bash:

1. Install Java

Make sure you have Java installed on your Windows computer. You can download and install Java from the official Oracle website or use OpenJDK which is an open-source alternative.

Verify the installation by running the following command in your Git Bash terminal to see if it displays the installed Java version.

$ java -version

2. Write Your Java Code

Create a Java source code file using the text editor or an Integrated Development Environment (IDE) like Visual Studio Code, Eclipse, or IntelliJ IDEA.

  • Save the file with a .java extension.
  • For example, you can create a file named MyProgram.java.

Java




// Testing Code
public class MyProgram {
    public static void main (String[] args) {
        System.out.println("Hello, World!");
    }
}


3. Open Git Bash

Launch Git Bash on your Windows machine. You can find it in Start menu if you have it installed.

4. Navigate to the Directory with Your Java Code

Use the cd command to navigate to directory where your Java source code file is located.

For example, if your code is in the C:\Users\YourUsername\Projects directory.

cd /c/Users/terminals/Projects

Replace YourUsername and Projects with your actual directory path.

5. Compile Your Java Code

In Git Bash, we can compile your Java code using javac command as follows:

javac MyProgram.java

If after successful compilation a .class file with same name as your Java class.

6. Run Your Java Program

After successfully compiling your code you can run it using java command followed by the name of the class containing the main method.

For example:

java MyProgram

If your code contains a main method this command will be execute your Java program and you should see the output in the Git Bash terminal.

7. Output for Your Java Code

A complete overview of command and their output is shown below:
Screenshot-2023-10-02-114234


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads