top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Java Hello World Program

Introduction 

The Java "Hello, World!" program holds immense significance for those taking initial steps into the programming world. It serves as a fundamental starting point, acquainting individuals with the language and illustrating the core principles of writing, compiling, and executing Java code.

Overview

This tutorial teaches you how to use the System.out.println() method to display the iconic "Hello, World!" message on the console. This program acts as a stepping stone, facilitating comprehension of Java's syntax, variables, and basic program structure. It presents a straightforward yet impactful approach to gaining hands-on experience and fostering self-assurance in Java coding.

Class Definition

The class definition plays a vital role in the Java "Hello, World!" program. It serves as a blueprint or template that specifies the structure and behavior of objects in Java. The class acts as a container, holding relevant data and methods.

In the "Hello, World!" program, the class definition commences with the keyword "class," followed by the class name. It encapsulates the necessary code for program execution. Within the "Hello, World!" program's class definition, you'll find the main method, which acts as the starting point for program execution.

Syntax:

public class HelloWorld {
//rest of the program or the main() method
}

main() Method

The main() method is a crucial component in Java programs. It serves as the entry point for the program, meaning that the Java Virtual Machine (JVM) starts executing the program from this method. In the case of the “Hello, World!” program, we use the System.out.println() statement inside the main method to print the string "Hello, World!" to the console.

Syntax:

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

The requirement for Java Hello World Example

To create a Java Hello World example, you only need a few basic components, making it an ideal starting point for beginners. By fulfilling these requirements, you can easily run a Java Hello World program and observe the "Hello, World!" message appearing on the console. The requirements include the following:

  • Java Development Kit (JDK): Install the JDK, which contains the essential tools for Java development, such as the compiler and runtime environment.

  • Text Editor or Integrated Development Environment (IDE): Select a text editor or IDE to write your Java code, such as Notepad++, Visual Studio Code, Eclipse, or IntelliJ IDEA.

  • Java Source Code: Write the code using the appropriate Java syntax and follow the naming conventions to display the "Hello, World!" message.

  • Save and Compile: Save the Java source code file with the ".java" extension and compile it using the Java compiler (javac) to generate bytecode.

  • Run the Program: Execute the compiled bytecode using the Java Virtual Machine (JVM) by running the "java" command, followed by the class name.

Creating Hello World Example

Let us break down each portion of the code to understand how this program is created:

public class HelloWorld: This line defines a class named HelloWorld. The class is declared public, which means it can be accessed from other classes. The name of the class must match the name of the Java file it is defined in.

public static void main(String[] args): This is the main method declaration. It is declared public, which allows it to be accessed from anywhere. It is also declared static, meaning it belongs to the class itself and can be invoked without creating an instance of the class. The void keyword indicates that the main method does not return any value.

The main method takes a single parameter of type String array (String[] args). This parameter allows the program to receive command-line arguments when the program is run. The args parameter can be used to access and process the command-line arguments within the main method.

System.out.println("Hello, World!");: This line uses the System.out.println statement to print the string "Hello, World!" to the console. The System.out is a reference to the standard output stream, and println is a method that prints a line of text. The text enclosed in double quotes is the content to be printed.

Parameters Used in Java Programs

Java programs use various parameters to ensure their proper functioning. You can successfully create and execute your initial Java program by using these parameters effectively.

Class

The "class" keyword defines a class in Java, which acts as a blueprint for objects.

Public

The "public" modifier allows access to the class by other classes and packages.

Static

The "static" keyword denotes a method or variable as a class-level entity, enabling access without creating an instance of the class.

Void

"Void" signifies that the main method does not return any value.

Main

The "main" method serves as the starting point of execution for the Java program.

String[] args

It is a parameter of the main method that allows command-line arguments to be passed to the program.

System.out.println()

This statement outputs text to the console, printing the specified message enclosed in parentheses.

In How Many Ways Can We Write a Java Program?

A Java program can be written in multiple ways using various methods. Let us check out other alternative methods for writing the “Hello World” program using different techniques and methods.

Using Command-line Arguments

public class HelloWorld {
    public static void main(String[] args) {
        if (args.length > 0) {
            System.out.println("Hello, " + args[0] + "!");
        } else {
            System.out.println("Hello, World!");
        }
    }
}

Inside the main method of this example, there is an if statement that checks whether any command-line arguments are present. It does this by checking the length of the args array. A length greater than zero (args.length > 0) implies there are arguments.

If there are command-line arguments, the code executes the block of code within the if statement. It uses the System.out.println statement to print "Hello, " concatenated with the first argument (args[0]), followed by an exclamation mark. This creates a customized greeting message based on the provided argument.

The code executes the code block within the else statement if no command-line arguments are provided. It uses the System.out.println statement to print the default greeting "Hello, World!" to the console.

Using print Statement Without a Newline Character

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

In this alternative, we use System.out.print instead of System.out.println to print "Hello, World!" without appending a newline character. The output would be "Hello, World!" displayed on the console without a line break.

Using printf Method

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

In this alternative, we use System.out.printf method to format and print the string. The %s is a placeholder for a string value, and "World" is passed as an argument to replace the placeholder. The output would be "Hello, World!" displayed on the console.

Resolving an Error, "javac is not recognized as an internal or external command"?

The error message "javac is not recognized as an internal or external command" typically indicates that the Java compiler (javac) is not properly set up or the system environment variables are not configured correctly. To resolve this error, you can try out these steps:

  • Check Java Installation: Ensure that Java Development Kit (JDK) is installed on your system. You can download the latest JDK from the official Oracle website and follow the installation instructions specific to your operating system.

  • Set Java Home Environment Variable: Set the JAVA_HOME environment variable to point to the directory where JDK is installed.

  • Update Path Environment Variable: Add the bin directory of the JDK installation to the system's PATH environment variable. This allows the system to locate the javac command.

  • Verify Configuration: Open a new terminal or command prompt and run the javac command to verify that the error is resolved. You should see the usage and options for the javac command printed on the console.

Compiling the program 

To compile the program, you must first name the .java file correctly, depending on what you decide to name your public class. If you do not name the file correctly, you will face an error such as this:

You can run the program once you are ready with the code and the HelloWorld.java file. Once you run the program in the IDE you are using, the program will begin compiling and finally generate the output.

Conclusion 

The Java "Hello, World!" program is the foundation for beginners venturing into the programming world. By mastering this program's basic syntax and structure, you gain a solid starting point for your journey in Java development. With its simplicity and clarity, the "Hello, World!" program instills confidence and introduces you to fundamental coding concepts. 

From here, you can expand your knowledge and explore the vast possibilities of Java programming. If the Java "Hello, World!" program interests you, consider taking up a professional course offered by upGrad to upgrade your knowledge in this field. 

FAQs

1. Can the displayed message in the Java hello world program be modified?

Yes. You can change the text within the System.out.println() statement to customize the output message.

2. Why is the Java hello world program often recommended as the first program?

The Java hello world program is an introductory exercise because it familiarizes beginners with essential syntax and structure, enabling them to grasp the fundamentals of writing, compiling, and executing a basic program.

3. Is the Java hello world program relevant only for beginners?

Although the Java hello world program is typically associated with beginners, its principles are fundamental in advanced Java programming. Mastering these basics is vital for developing advanced applications.

Leave a Reply

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