First Java Program
One of the first steps in learning any programming language is writing a simple program to test that everything is set up correctly. In Java, the most common first program is the "Hello, World!" program. It’s a simple program that outputs the text "Hello, World!" to the screen. Here’s how you can write and run your very first Java program.
Steps to Write and Run the First Java Program
1. Create a .java File
The first thing you need is to create a Java source file with a .java extension. Open your text editor (such as Notepad or any IDE like IntelliJ IDEA, Eclipse, etc.), and create a file named HelloWorld.java.
2. Write the Code
Here’s the code for the "Hello, World!" program:
public class HelloWorld {
public static void main(String[] args) {
// Print "Hello, World!" to the console
System.out.println("Hello, From ShikshaSanchar!");
}
}
Explanation:
- public class HelloWorld: This line defines a class named HelloWorld. In Java, every program must be written inside a class.
- public static void main(String[] args): This is the main method. It’s the entry point of every Java program. When you run a Java program, the main method is called first.
- System.out.println("Hello, From ShikshaSanchar!"); This line prints the text Hello, From ShikshaSanchar! to the console.
3. Save the File
Save the file with the name HelloWorld.java. Make sure the file
extension is
.java
.
Steps to Run the Program
-
Open Command Prompt or Terminal
- Windows: Open Command Prompt (cmd).
- macOS/Linux: Open Terminal.
-
Navigate to the Directory
Use the
cd
command to navigate to the folder where your HelloWorld.java file is saved. -
Compile the Java Code
Use the
javac
command to compile the .java file into bytecode. This will create a HelloWorld.class file.javac HelloWorld.java
If there are no errors in your code, this will generate a HelloWorld.class file.
-
Run the Program
Now, use the
java
command to run the compiled bytecode. The java command runs the HelloWorld.class file.java HelloWorld
Output:
Hello, From ShikshaSanchar!
Bonus Point:
Is empty .java source file valid?
An empty .java source file is technically valid syntax-wise in the sense that it doesn't produce any compilation errors, but it does not have any executable code and won't do anything when compiled or run. Java requires at least one class definition, and if the .java file doesn't have any code or class, there won't be any meaningful output or program execution.
Is syntactically correct, but it won't perform any action when compiled and executed.
However, if you try to compile an empty file using javac or run it using java, it won't produce any visible output or functionality because it has no methods or logic to execute.
So, while technically valid, it's essentially a non-functional source file.
Summary
- Write Code: Save as HelloWorld.java.
- Compile:
javac HelloWorld.java
- Run:
java HelloWorld