Writing the main() Method and the First Java Program
Course: Core Java Training
Topic: Writing the main() Method and the First Java Program
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy Official Website
1. Introduction to the First Java Program
Writing the first Java program is an important step in learning Core Java. It introduces the basic structure of a Java application, including classes, methods, statements, curly braces, and output commands.
Most traditional Java applications begin execution through a special method called main(). The Java launcher locates an appropriate entry-point method and starts the program from there. The main() method can then call other methods to perform the application's tasks.
A beginner usually starts with a simple program that displays a message such as Hello, Java! This example helps learners understand how to write source code, save it with the correct file name, compile it, and execute it.
Learning Objectives
- Understand the structure of a basic Java application.
- Learn the purpose of the
main() method.
- Understand the keywords
public, static, and void.
- Understand the parameter
String[] args.
- Learn how to display output using
System.out.println().
- Create, compile, and run a Java program.
- Identify common beginner mistakes and correct them.
2. What Is the main() Method?
The main() method is the conventional entry point for a traditional Java application launched by the Java command. It provides the starting point from which the application begins executing its instructions.
A standard main method is written as follows:
public static void main(String[] args) {
// Program statements go here
}
Each part of this declaration has a specific meaning. Understanding these keywords and the parameter helps beginners write Java applications correctly.
Why Is main() Important?
- It provides the entry point for a conventional Java application.
- It contains statements that execute when the application starts.
- It can call other methods to divide a program into smaller tasks.
- It can receive command-line arguments through the
args parameter.
- It helps connect the Java launcher with the application's code.
3. Understanding Each Part of the main() Method
3.1 The public Keyword
public is an access modifier. It allows the method to be accessed from outside its class, subject to Java's access rules. The conventional main method is public so that the Java launcher can invoke it.
public static void main(String[] args)
3.2 The static Keyword
static means that the method belongs to the class rather than to an individual object. The Java launcher can invoke a static main method without first creating an instance of the class.
public static void main(String[] args)
Inside a static method, instance fields and instance methods cannot be accessed directly without an object. They can still be used by creating an appropriate instance of the class.
3.3 The void Keyword
void specifies that the method does not return a value to its caller.
public static void main(String[] args)
A main method can display output, perform calculations, call other methods, or coordinate application tasks without returning a value through its method declaration.
3.4 The main Method Name
main is the conventional method name recognized as the entry point when launching a traditional Java application. Java is case-sensitive, so main and Main are different identifiers.
public static void main(String[] args)
Writing Main instead of main does not declare the conventional entry-point method.
3.5 The String[] args Parameter
String[] args declares a parameter that receives command-line arguments as an array of strings.
String represents text.
[] indicates an array.
args is the parameter name chosen by the programmer.
The parameter can use another valid identifier, such as arguments, because the name is not fixed by Java.
public static void main(String[] arguments) {
System.out.println(arguments.length);
}
This example prints the number of command-line arguments passed to the program.
3.6 The Opening and Closing Braces
The curly braces { and } mark the body of the method. Statements inside the braces belong to that method.
public static void main(String[] args) {
System.out.println("Program started");
}
Missing or mismatched braces can prevent the compiler from understanding the program structure.
4. Understanding the Complete First Java Program
Consider the following simple Java application:
public class HelloJava {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
Output:
Hello, Java!
This program defines a class named HelloJava. Inside that class, the main method contains a statement that prints a message to standard output.
Line-by-Line Explanation
| Code |
Explanation |
public class HelloJava |
Declares a public class named HelloJava. |
{ |
Begins the body of the class. |
public static void main(String[] args) |
Declares the conventional main method. |
System.out.println("Hello, Java!"); |
Prints the message followed by a line break. |
} |
Closes the method or class body, depending on its position. |
5. Understanding the class Keyword
In Java, a class is a blueprint that defines a type and can contain fields, constructors, methods, and other declarations. A conventional Java application places its main method inside a class.
Example
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Core Java");
}
}
Here, Welcome is the class name. Since the class is public, the source file should be saved as Welcome.java.
Class Naming Rules
- Class names are case-sensitive.
- Names cannot contain spaces.
- Java identifiers cannot begin with a digit.
- Meaningful names make code easier to understand.
- By convention, class names usually use PascalCase, such as
StudentRecord.
- A public top-level class must match its source file name.
6. Displaying Output with System.out.println()
System.out.println() is commonly used to display text and values in the console. It prints the supplied value and then moves to a new line.
Example 1: Printing Text
public class MessageDemo {
public static void main(String[] args) {
System.out.println("Learning Java is interesting.");
}
}
Output:
Learning Java is interesting.
Example 2: Printing Multiple Lines
public class MultipleLines {
public static void main(String[] args) {
System.out.println("My name is Alex.");
System.out.println("I am learning Core Java.");
System.out.println("This is my first program.");
}
}
Output:
My name is Alex.
I am learning Core Java.
This is my first program.
Example 3: Printing Numbers
public class NumberDemo {
public static void main(String[] args) {
System.out.println(100);
System.out.println(25 + 15);
}
}
Output:
100
40
The expression 25 + 15 is evaluated before the result is printed.
7. Difference Between print() and println()
Java provides both System.out.print() and System.out.println() for console output.
| Feature |
print() |
println() |
| Purpose |
Displays the supplied value. |
Displays the supplied value and ends the line. |
| Moves to a new line automatically? |
No. |
Yes. |
| Typical use |
Displaying multiple values on the same line. |
Displaying separate lines of output. |
Example
public class PrintDemo {
public static void main(String[] args) {
System.out.print("Hello ");
System.out.print("Java");
System.out.println();
System.out.println("Welcome!");
}
}
Output:
Hello Java
Welcome!
8. Creating the First Java Program Step by Step
Step 1: Install the JDK
Install a JDK compatible with your course and project requirements. The JDK provides the tools needed to compile and run Java applications.
You can explore official Java downloads at Oracle Java Downloads.
Step 2: Check Java Installation
Open Command Prompt, PowerShell, or Terminal and run:
java -version
javac -version
Both commands should display version information for the selected Java runtime and compiler.
Step 3: Create a Source File
Open a text editor or IDE and enter this program:
public class FirstProgram {
public static void main(String[] args) {
System.out.println("My first Java program!");
}
}
Step 4: Save the File
Save the file as:
FirstProgram.java
Ensure the file name matches the public class name, including capitalization.
Step 5: Open a Terminal in the Correct Directory
Navigate to the folder containing FirstProgram.java. You can use the terminal's directory-change command to reach that folder.
Step 6: Compile the Source Code
javac FirstProgram.java
If the source code compiles successfully, a file named FirstProgram.class is normally generated in the current directory.
Step 7: Run the Program
java FirstProgram
Output:
My first Java program!
9. How the Java Program Executes
A Java program passes through a sequence of steps from source code to output.
- Writing: The programmer writes the Java source code in a
.java file.
- Compilation: The
javac compiler checks the source code and generates bytecode.
- Class loading: The JVM loads the required compiled classes.
- Entry-point discovery: The Java launcher locates an appropriate main method.
- Execution: The JVM executes the program's instructions.
- Output: The program displays messages or performs other operations.
Execution Flow
FirstProgram.java
|
v
javac FirstProgram.java
|
v
FirstProgram.class
|
v
java FirstProgram
|
v
JVM Executes the Program
|
v
My first Java program!
10. Understanding Command-Line Arguments
The String[] args parameter allows a program to receive information from the command line. Each argument is passed as a string and can be accessed using an array index.
Example: Displaying Arguments
public class ArgumentDemo {
public static void main(String[] args) {
System.out.println("Number of arguments: " + args.length);
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}
Compile the program:
javac ArgumentDemo.java
Run the program with three arguments:
java ArgumentDemo Java Core Programming
Output:
Number of arguments: 3
Java
Core
Programming
The arguments are separated by spaces. If an argument contains spaces and should be treated as a single argument, enclose it in quotation marks according to your shell's rules.
Important Points About args
- The array contains command-line arguments as strings.
- Array indexing starts at zero.
args.length returns the number of arguments.
- Using an invalid index can cause an
ArrayIndexOutOfBoundsException.
- Numeric arguments must be converted to numeric types before arithmetic operations can be performed.
11. Calling Other Methods from main()
The main method can call other methods to organize the program into smaller, reusable tasks. This makes code easier to read, test, and maintain.
Example
public class MethodDemo {
public static void main(String[] args) {
displayWelcome();
displayCourse();
}
public static void displayWelcome() {
System.out.println("Welcome to Java!");
}
public static void displayCourse() {
System.out.println("Course: Core Java");
}
}
Output:
Welcome to Java!
Course: Core Java
Both methods are static, so the main method can call them directly through their names. A non-static method can also be called after creating an instance of its class.
12. Common Rules and Syntax for main()
- For the conventional entry point, use
public static void main(String[] args).
- The method name must be written as lowercase
main.
- Use matching opening and closing braces.
- Statements such as
System.out.println() generally end with a semicolon.
- The source file name must match the public top-level class name.
- Java identifiers are case-sensitive.
- Command-line arguments are available through the String array.
- When launching a compiled class, normally specify the class name without the
.class extension.
Note: Modern Java releases support additional main-method forms for certain source code and launch scenarios. This course topic uses the conventional public static void main(String[] args) form because it is widely compatible and appropriate for learning Core Java fundamentals.
13. Common Errors When Writing the First Java Program
| Error |
Cause |
Solution |
| Public class name does not match the file name |
The source file uses a different name or capitalization. |
Rename the file to match the public class name. |
main method not found |
The method name or declaration is incorrect for the launch mode. |
Use the conventional main method declaration. |
| Missing semicolon |
A statement is not terminated correctly. |
Add the required semicolon. |
| Unclosed braces |
A class or method body is missing a closing brace. |
Check every opening and closing brace. |
| Java command not recognized |
The JDK is missing or PATH is not configured correctly. |
Install a JDK and verify PATH. |
| Compiler command not recognized |
The JDK compiler is unavailable through PATH. |
Check the JDK installation and its bin directory. |
| Could not find or load main class |
The classpath, working directory, package name, or class name is incorrect. |
Run from the correct directory and use the correct class name and classpath. |
| Unexpected output |
The statements or values differ from the intended logic. |
Review the source code and compile it again after changes. |
14. Writing Comments in the First Java Program
Comments explain the purpose of code and are ignored as executable statements by the compiler. Java supports single-line, multi-line, and documentation comments.
Single-Line Comment
// This program prints a welcome message.
Multi-Line Comment
/*
This is a simple Java program.
It demonstrates the main method.
*/
Documentation Comment
/**
* Displays a welcome message.
*/
Complete Example with Comments
/**
* A simple program that welcomes the user.
*/
public class WelcomeUser {
public static void main(String[] args) {
// Display a message on the console.
System.out.println("Welcome to Core Java!");
}
}
Comments should explain the purpose of code where necessary. Clear class and method names can reduce the need for excessive comments.
15. Best Practices for Writing Your First Java Program
- Choose descriptive class names such as
WelcomeUser or StudentDemo.
- Use consistent indentation to make the code easier to read.
- Match the file name with the public top-level class name.
- Use the conventional main method declaration while learning Java fundamentals.
- End statements with semicolons where required.
- Keep braces properly balanced.
- Use meaningful output messages.
- Compile the source file before running it when following the traditional javac workflow.
- Read compiler errors carefully and fix the earliest relevant error first.
- Practice small programs before moving to larger applications.
16. Practical Exercises
Exercise 1: Print Your Introduction
Write a Java program that prints your name, your learning goal, and the course you are studying on separate lines.
Exercise 2: Print a Course Welcome Message
Create a class named CourseWelcome and display the message Welcome to Core Java Training!.
Exercise 3: Print Multiple Values
Use System.out.println() to display three numbers and one text message.
Exercise 4: Compare print() and println()
Write a program using both methods and observe how the output is arranged on the console.
Exercise 5: Display Command-Line Arguments
Create a program that prints every value in args using a loop. Run the program with at least three arguments.
Exercise 6: Call Another Method
Create a static method named showMessage() and call it from the main method.
Exercise 7: Fix Compilation Errors
Intentionally remove a semicolon or closing brace from a program. Compile it, inspect the error message, correct the source code, and compile again.
17. Mini Project: Personal Introduction Program
Create a small application that displays a person's name, course, and learning goal. This project reinforces class declarations, the main method, output statements, and source file naming.
Source Code
public class PersonalIntroduction {
public static void main(String[] args) {
System.out.println("Personal Introduction");
System.out.println("--------------------");
System.out.println("Name: Alex");
System.out.println("Course: Core Java");
System.out.println("Goal: Become a Java Developer");
}
}
Compile the Program
javac PersonalIntroduction.java
Run the Program
java PersonalIntroduction
Expected Output
Personal Introduction
--------------------
Name: Alex
Course: Core Java
Goal: Become a Java Developer
Try replacing the sample name and goal with your own practice values, then compile and run the program again.
18. Interview Questions and Answers
Q1. What is the main() method in Java?
Answer: The main method is the conventional entry point through which a traditional Java application starts execution when launched by the Java command.
Q2. What is the standard main method declaration?
Answer: public static void main(String[] args).
Q3. Why is main() declared public?
Answer: The conventional entry-point method is public so it can be accessed by the launcher under the usual Java access rules.
Q4. Why is main() static?
Answer: A static method belongs to the class, allowing the launcher to invoke it without creating an instance of that class first.
Q5. What does void mean?
Answer: It means the method does not return a value.
Q6. What is String[] args?
Answer: It is an array of strings used to receive command-line arguments passed to the program.
Q7. Can the parameter name args be changed?
Answer: Yes. It can be replaced with another valid identifier, such as arguments.
Q8. What does System.out.println() do?
Answer: It prints a value to standard output and then terminates the current output line.
Q9. What is the difference between print() and println()?
Answer: print() does not automatically end the line, whereas println() prints the value and then moves to a new line.
Q10. What is the correct file name for public class HelloJava?
Answer: The source file should be named HelloJava.java.
Q11. How do you compile a Java program?
Answer: Use the command javac FileName.java from a terminal where the source file can be found.
Q12. How do you run a compiled Java class?
Answer: Use java ClassName, normally without the .class extension.
Q13. Can the main method call other methods?
Answer: Yes. It can call static methods directly and instance methods through an object.
Q14. What happens if the main method is misspelled as Main?
Answer: Java is case-sensitive. Main is a different identifier and does not declare the conventional main entry-point method.
19. Quick Revision Checklist
- Understand the purpose of the main method.
- Remember the conventional declaration:
public static void main(String[] args).
- Understand public, static, void, and String array parameters.
- Know how to declare a class and use curly braces.
- Use System.out.println() to display output.
- Save the source file with the correct name and .java extension.
- Compile the program using javac.
- Run the compiled class using java.
- Understand how command-line arguments work.
- Recognize common syntax and launch errors.
- Practice calling other methods from main().
20. Conclusion
Writing the main method and creating the first Java program establish the foundation for learning Core Java. The main method serves as the conventional entry point for a traditional Java application, while class declarations and output statements provide the structure needed to create a working program.
By understanding each part of public static void main(String[] args), practicing console output, compiling source files, and resolving common errors, learners can develop the confidence needed to move on to variables, data types, operators, conditions, loops, methods, and object-oriented programming.
For structured learning resources, visit the JustAcademy Core Java Training Course, register for a course demo, or explore the JustAcademy official website.