Java is a widely used programming language, known for its simplicity, portability, and robustness. Writing your first Java program is an exciting step in learning to code. Here’s a step-by-step guide:
Create a Java Program File
1. Open your text editor or IDE.
2. Create a new file named HelloWorld.java. The file name must match the class name (case-sensitive) to avoid compilation errors.
// This is a simple Java program
public class HelloWorld {
public static void main(String[] args) {
// Print a message to the console
System.out.println("Hello, World!");
}
}
Explanation:
public class HelloWorld: Defines a public class named HelloWorld.
public static void main(String[] args): The entry point of the program.
System.out.println(“Hello, World!”);: Prints “Hello, World!” to the console.
Compile the Program
1. Open a terminal or command prompt.
2. Navigate to the directory where you saved HelloWorld.java
3. Run the following command to compile the program:
javac HelloWorld.java
4. If there are no errors, this will generate a file named HelloWorld.class.
Run the Program
1. In the same directory, execute the following command:
java HelloWorld
2. You should see the output
Hello, World!
Writing Your First Java Program – Interview Questions
Q 1: What is the extension of Java source file?
Ans: .java
Q 2: Why is the main method important?
Ans: It is the entry point of Java program execution.
Q 3: What does public static void main mean?
Ans: It allows JVM to call the method without creating an object.
Q 4: How do you display output in Java?
Ans: Using System.out.println().
Q 5: Can a Java program run without compilation?
Ans: No, Java code must be compiled before execution.
Writing Your First Java Program – Objective Questions (MCQs)
Q1. What is the entry point of a Java program?
Q2. Which method signature is correct for main()?
Q3. Which statement is used to print output on the console?
Q4. What does the Java compiler generate?
Q5. Which keyword is used to define a class in Java?