Writing Your First Program in Java

Writing Your First Program in Java

Until now we have studied all the theoretical concepts as the basics. So now is the time to dabble your feet into actual coding. In this article, we will follow simple steps to set up Java on your PC and run our first Hello World program in Java.

Setting up the environment in Windows

  1. Go to the Java Downloads page on Oracle's website.
  2. Download the appropriate installer for your operating system.
  3. Run the installer, following the shown instructions.
  4. Add Java to System Environment Variables:
    • Open the Start menu and search for the environment variable.
    • Select the Edit the system environment variables result.
    • In the System Properties window, under the Advanced tab, click Environment Variables…
    • Under the System variables category, select the Path variable and click Edit
    • Click the New button and enter the path to the Java bin directory. The default path is usually C:\Program Files\Java\jdk-17\bin.
    • Click OK to save the changes and exit the variable editing window.
  5. Test the installation by running the java -version command in the command prompt/terminal.

How to setup Java on Mac

First Program

Open any text editor like Notepad and save the file as Hello.java. Write the following code in the file and save it.

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

Open a terminal in the same file directory and run the command javac Hello.java to compile the code and create the bytecode file Hello.class in the same directory.

Run the class file to execute the code using the command java Hello. The output will be displayed on the terminal Hello world!

A brief explanation of the code:

Every program in Java is written inside a class and the primary statements to be executed are written inside the standard main method of the class. The curly braces { } indicate the starting and end of the block of statements inside the respective class or method.

The main method must have the declaration public static void main(String args[]) for the statements inside to be executed when we run the program using java <ClassName> command. Any other variation of this method definition does not produce a compilation error, but the expected output will not be produced when it is run.

System is the pre-existing class in java that provides an interface for input and output from the console. println() method prints the given message on the current line and then moves the cursor to the next line.

The above explanation does not delve into the depth of the meaning of the keywords. They will be explored and explained in the future when we cover the respective concepts. As we have learnt how to write and execute our programs, we will continue learning further concepts like Control Statements in Java by coding them parallelly.