BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to Compile and Run your First Java Program

Last Updated: May 26, 2024 by Chaitanya Singh | Filed Under: java

In this tutorial, you will find step by step guide to write, compile and run your first java program. We will also write a java program to print “Hello World” message on the screen.

Let’s start with a simple java program.

Simple Java Program

This is a very basic java program that prints a message “This is my first program in java”.

public class FirstJavaProgram {
  public static void main(String[] args){
    System.out.println("This is my first program in java");
  }//End of main
}//End of FirstJavaProgram Class

Output:

This is my first program in java

Java “Hello, World!” Program

This is the most commonly asked question. Whenever someone starts learning java, the first program they write is to print “Hello World!” message on screen. This program is same as the program we have seen above.

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!"); 
    }
}

Output:

Hello World!

How to compile and run your first java 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 or 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.

javac FirstJavaProgram.java

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.

set path=C:\Program Files\Java\jdk1.8.0_121\bin

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.

export JAVA_HOME=/Library/Java/Home

Type the following command on terminal to confirm the path.

echo $JAVA_HOME

That’s it.

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. To set path permanently, refer this guide.

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:

java FirstJavaProgram

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

How the First Java Program works?

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

public class FirstJavaProgram {

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.

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.

public static void main(String[] args)  {

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.

System.out.println("This is my first program in java");

This method prints the string inside the double quotes on the console and inserts a newline after. I have covered this in detail in my guide regarding System.out.println().

Next Step: Practice the following java programs before going through the next tutorial:

  • Java Program to read number (entered by user)
  • Java Program to check if a number is positive or negative
  • Java Program to add two numbers
❮ PreviousNext ❯

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. as says

    February 10, 2015 at 4:23 AM

    I am new to java. I have a question, shouldn’t the method printmessage have a return type void as its not a constructor?

    Reply
    • Ram says

      March 14, 2016 at 6:41 AM

      yes , it should have a return type … else it will throw an compilation error.

      Reply
  2. Aryaa says

    June 18, 2015 at 8:07 PM

    What is Stand-alone program?

    Reply
    • srikanth says

      July 15, 2015 at 5:49 PM

      which are not connected to network that application are stand alone
      example in desktop calculator

      Reply
  3. Rajan Biswas says

    November 24, 2015 at 1:34 PM

    printMessage()
    this method will void: public void printMessage()

    Reply
  4. divya says

    December 10, 2015 at 7:14 AM

    where does the Package creates the folder FirstCode ?

    Reply
    • Yusuf says

      December 26, 2015 at 4:51 PM

      At the same location from where you’re compiling your Java program.

      Reply
  5. Pyrom says

    February 8, 2016 at 8:34 AM

    For those of who see errors try this one.

    package //After type your current package name in here, Delete slashes//;
    import java.lang.*;
    class WelcomeMessage
    {
    public static void printMessage()
    {
    System.out.println(“Hello World”);
    }
    }
    class //After type your current class name in here, Delete slashes//
    {
    public static void main(String[] args)
    {
    WelcomeMessage obj = new WelcomeMessage();
    obj.printMessage();
    }
    }

    Reply
    • Gauravendra Pratap Singh says

      June 26, 2016 at 9:41 PM

      class WelcomeMessage
      {
      public static void printMessage()
      {
      System.out.println(“Hello World”);
      }
      }
      class Myclass
      {
      public static void main(String []args)
      {
      // WelcomeMessage obj=new WelcomeMessage ();
      printMessage();
      }
      }

      /* In this program ,you need not to create object because for static method you no need to create object for that class.
      run this program happly..*/

      Reply
      • Rajani Kanth says

        February 14, 2017 at 7:15 PM

        Compilation fails, you will have error message MyClass cannot find the pringMessage() method which is in WelcomeMessage and thier is no connection between these two classes:
        error message would be:
        Myclass.java:13: error: cannot find symbol

        Reply
  6. noreen says

    January 6, 2017 at 6:20 AM

    i am getting an error that says

    Error: Main method not found in class welcomemessage.WelcomeMessage, please define the main method as:
    public static void main(String[] args)
    or a JavaFX application class must extend javafx.application.Application

    what should i do

    Reply
  7. learner says

    August 4, 2017 at 3:56 PM

    Microsoft Windows [Version 10.0.15063]
    (c) 2017 Microsoft Corporation. All rights reserved.

    C:\Users\asus>set path=C:\Program Files\Java\jdk1.8.0_131\bin

    C:\Users\asus>java FirstJavaProgram
    Error: Could not find or load main class FirstJavaProgram

    C:\Users\asus>

    what did i do wrong?

    Reply
    • Chaitanya Singh says

      August 5, 2017 at 6:32 AM

      You have to compile the program first then you can run it. After setting up the path, compile the program by typing “javac FirstJavaProgram” without quotes in command prompt and hit enter then type “java FirstJavaProgram” without quotes.

      Reply
      • Malcolm says

        September 14, 2017 at 2:38 PM

        Microsoft Windows [Version 10.0.15063]
        (c) 2017 Microsoft Corporation. All rights reserved.

        C:\Users\lemzod30>set path=C:\Program Files\Java\jdk1.8.0_144\bin

        C:\Users\lemzod30>javac FirstJavaProgram
        error: Class names are only accepted if annotation processing is explicitly requested
        1 error

        C:\Users\lemzod30>

        What’s wrong?

        Reply
        • Chaitanya Singh says

          September 14, 2017 at 3:38 PM

          You need to include .java extension while compiling the program. Note that the “j” in .java is in lowercase, if you use the uppercase then you will get the same error.

          Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap