First Java Program
First Java Program | Hello World Example
The "Hello, World!" program is the simplest program you can write in any programming language, and it serves as a great introduction to Java. This program will print "Hello, World!" on the screen. Let's walk through the steps to create, compile, and run this basic Java program.
Step 1: Writing the Code
Open your text editor or Integrated Development Environment (IDE) and type the following code:
Explanation of the Code:
public class HelloWorld: This defines a class named
HelloWorld
. In Java, every program must have at least one class.public static void main(String[] args): This is the main method, the entry point of any Java program. When you run the program, the code inside this method is executed.
System.out.println("Hello, World!");: This line prints "Hello, World!" to the console.
System.out
is used to print text, andprintln
adds a new line after printing the text.
Step 2: Saving the Code
Save the file with the name HelloWorld.java
. The filename must match the class name (in this case, HelloWorld
) and have a .java
extension.
Step 3: Compiling the Code
To compile your Java program, follow these steps:
Open a command prompt or terminal.
Navigate to the directory where you saved your
HelloWorld.java
file.Run the following command to compile the program:
If the code is correct, this command will create a file named HelloWorld.class
. This file contains the bytecode, which can be executed by the Java Virtual Machine (JVM).
Step 4: Running the Code
After compiling the code, you can run the program using the following command:
This will execute the compiled bytecode, and you should see the following output on your screen:
Conclusion
Congratulations! You've just written, compiled, and executed your first Java program. The "Hello, World!" example demonstrates the basic structure of a Java program, including classes, the main method, and printing output to the console. From here, you can start exploring more advanced concepts and building more complex programs.
For more examples and tutorials, visit codeswithpankaj.com.
Last updated