Java / 6 of 6 / 15 dilihat
Understanding Your First Java Program
A Java program may look intimidating at first, but every part has a clear purpose. In this tutorial, we will examine a simple Java program line by line until every keyword, symbol, and statement makes sense.
In the previous tutorial, we learned how Java source code is compiled and executed.
We followed this process:
.java source file
│
│ javac
▼
.class bytecode
│
│ java
▼
JVM executionNow we will focus on the source code itself.
Our first program will be small, but it introduces several important Java concepts:
- classes;
- methods;
- the application entry point;
- statements;
- strings;
- method calls;
- braces;
- indentation;
- comments.
Series Navigation
Previous: How Java Compilation Works
Current: Understanding Your First Java Program
Next: Java Syntax and Code Structure
Learning Goals
After completing this tutorial, you should be able to:
- write a simple Java program;
- explain the purpose of a class;
- understand the
mainmethod; - describe the role of
String[] args; - explain how
System.out.printlnworks; - identify statements, braces, and semicolons;
- use comments correctly;
- understand basic indentation and naming rules;
- compile and run the program from the terminal;
- solve common beginner mistakes.
1. The Complete Program
Create a file named:
HelloPilkupil.javaAdd this code:
public class HelloPilkupil {public static void main(String[] args) {
System.out.println(
"Hello from Pilkupil Lab!"
);
}
}
```
Compile it:
javac HelloPilkupil.javaRun it:
java HelloPilkupilExpected output:
Hello from Pilkupil Lab!The program contains only a few lines, but each part has an important role.
2. The Program Structure
A simplified view looks like this:
public class HelloPilkupil
│
├── class declaration
│
└── public static void main(String[] args)
│
├── application entry point
│
└── System.out.println(...)
└── prints text to the consoleThe outer structure is a class.
Inside the class is a method.
Inside the method is a statement.
Class
└── Method
└── StatementThis pattern will appear in nearly every Java program.
3. public class HelloPilkupil
The first line is:
public class HelloPilkupil {It declares a class named HelloPilkupil.
Let us break it into parts:
public
class
HelloPilkupil
{public
public is an access modifier.
It means the class can be accessed from other parts of the program.
For now, remember:
public
└── accessible from outside its own class or package contextWe will discuss access modifiers more deeply in a later object-oriented programming tutorial.
class
The class keyword tells Java that we are declaring a class.
A class can contain:
- fields;
- constructors;
- methods;
- nested classes;
- initialization logic.
In this example, the class contains only one method:
mainA class can be viewed as a container for related data and behavior.
HelloPilkupil class
└── main methodHelloPilkupil
HelloPilkupil is the class name.
Java class names normally use PascalCase.
Examples:
HelloPilkupil
StudentAccount
TutorialProgress
BankTransactionPascalCase means:
- each word begins with an uppercase letter;
- spaces are removed.
This is a convention rather than a special compiler requirement, but it makes Java code consistent and easier to read.
The Opening Brace {
The opening brace starts the class body.
public class HelloPilkupil {The matching closing brace appears at the end:
}Everything between those braces belongs to the class.
public class HelloPilkupil {
┌───────────────────────────┐
│ class content goes here │
└───────────────────────────┘
}Braces group code into blocks.
4. Why Must the File Name Match the Class Name?
The class is declared as:
public class HelloPilkupilTherefore, the source file must be named:
HelloPilkupil.javaCorrect:
Class: HelloPilkupil
File : HelloPilkupil.javaIncorrect:
Class: HelloPilkupil
File : Main.javaWhen the names do not match, javac reports an error similar to:
class HelloPilkupil is public,
should be declared in a file named HelloPilkupil.javaThis rule keeps public top-level classes easy for Java tools to locate.
5. The main Method
The next line is:
public static void main(String[] args) {This is the traditional entry point of a Java application.
When we run:
java HelloPilkupilthe JVM looks for a method with this form:
public static void main(String[] args)A simplified process is:
java HelloPilkupil
│
▼
Load class HelloPilkupil
│
▼
Find main(String[] args)
│
▼
Execute the method bodyNow let us examine each part.
6. public in the Main Method
The main method is declared:
publicThe Java launcher must be able to access it.
For now, remember:
public main
└── the launcher can access the method7. static
The next keyword is:
staticA static method belongs to the class itself rather than to an object created from that class.
An instance method normally requires an object:
Course course = new Course();
course.showProgress();The JVM needs an entry point it can call before creating an application object.
That is why main is static.
Without static
└── create an object before calling the methodWith static
└── call the method through the class
```
A simplified idea is:
HelloPilkupil.main(args);We will study static members more deeply in a later tutorial.
8. void
The keyword:
voidmeans the method does not return a value.
Compare:
static int getNumber() {
return 10;
}That method returns an integer.
The main method is different:
public static void main(String[] args)It performs the application's work but does not return a Java value.
int
└── returns an integerString
└── returns text
void
└── returns no value
```
9. main
main is the method name.
Java uses this specific name for the traditional application entry point.
Method names normally use camelCase.
Examples:
main
showProgress
calculateTotal
sendNotificationcamelCase means:
- the first word begins with a lowercase letter;
- later words begin with uppercase letters;
- spaces are removed.
The JVM expects the correct main method signature, not an arbitrary method.
10. String[] args
The text inside the parentheses is:
String[] argsThis is the parameter accepted by the main method.
It can receive command-line arguments.
String[]
String[] means an array of strings.
A string represents text.
Examples:
"Java"
"Pilkupil Lab"
"25"
"--help"The square brackets indicate an array:
String
└── one text valueString[]
└── multiple text values
```
args
args is the parameter name.
It is short for:
argumentsThe name is conventional but not mandatory.
This is also valid:
public static void main(
String[] commandLineArguments
)Most examples use args because it is short and familiar.
11. Using Command-Line Arguments
Update the program:
public class HelloPilkupil {public static void main(String[] args) {
System.out.println(
"Argument count: " + args.length
);
}
}
```
Compile:
javac HelloPilkupil.javaRun:
java HelloPilkupil Java PilkupilExpected output:
Argument count: 2The values are stored as:
args[0] = "Java"
args[1] = "Pilkupil"You can print the first argument:
System.out.println(
"First argument: " + args[0]
);Running the program without arguments would cause an error because args[0] would not exist.
A safer version is:
public class HelloPilkupil {public static void main(String[] args) {
if (args.length > 0) {
System.out.println(
"Hello, " + args[0] + "!"
);
} else {
System.out.println(
"Hello from Pilkupil Lab!"
);
}
}
}
```
12. System.out.println
The main statement is:
System.out.println(
"Hello from Pilkupil Lab!"
);It prints text to standard output, usually the terminal.
Let us break it down:
System
.
out
.
println
(...)System
System is a class from the Java standard library.
It belongs to the java.lang package.
Classes in java.lang are available automatically, so we do not need to import System.
out
out is a static field inside System.
It represents the standard output stream.
System
└── out
└── output destinationprintln
println means:
print lineIt prints a value and then moves the cursor to the next line.
System.out.println("First");
System.out.println("Second");Output:
First
Secondprint vs println
print does not automatically add a new line.
System.out.print("Java ");
System.out.print("Tutorial");Output:
Java Tutorialprintln adds a line break:
System.out.println("Java");
System.out.println("Tutorial");Output:
Java
Tutorialprintf
Java also provides formatted output.
String name = "Alya";
int lessons = 3;System.out.printf(
"%s completed %d lessons.%n",
name,
lessons
);
```
Output:
Alya completed 3 lessons.For now, println is enough for most beginner programs.
13. The String Literal
The text:
"Hello from Pilkupil Lab!"is a string literal.
String literals are written between double quotation marks.
"Java"
"Hello"
"Learning with Pilkupil Lab"Single quotation marks are used for one character:
'J'
'A'
'7'This is a string:
"J"This is a character:
'J'They are different Java types.
14. The Semicolon ;
The statement ends with:
;The semicolon marks the end of many Java statements.
System.out.println("Hello");Other examples:
int lessonCount = 5;
String title = "Java Fundamentals";
lessonCount++;Missing a semicolon usually causes a compile-time error.
Incorrect:
System.out.println("Hello")Correct:
System.out.println("Hello");Class and method declarations do not use a semicolon after their opening braces.
15. Braces and Code Blocks
The program contains two pairs of braces.
public class HelloPilkupil { // Class startspublic static void main(
String[] args
) { // Method starts
System.out.println(
"Hello from Pilkupil Lab!"
);
} // Method ends
} // Class ends
```
The braces form nested blocks:
Class block
└── Method block
└── StatementsA missing or misplaced brace can change how the compiler interprets the program.
16. Indentation and Whitespace
Java generally ignores extra whitespace between tokens.
These programs are technically similar:
public class Example {
public static void main(String[] args) {
System.out.println("Hello");
}
}public class Example{public static void main(String[]args){System.out.println("Hello");}}The second version is difficult to read.
Good indentation shows the program structure.
Class level
Method level
Statement levelConsistent formatting matters because code is read more often than it is written.
17. Comments
Comments allow developers to add explanations that the compiler ignores.
Single-Line Comment
// Print a greeting
System.out.println("Hello");Multi-Line Comment
/*
* This program prints
* a simple greeting.
*/
System.out.println("Hello");Documentation Comment
/**
* Prints a welcome message.
*/
public static void showMessage() {
System.out.println("Welcome");
}Documentation comments can be processed by the javadoc tool.
Useful comments explain:
- why a decision was made;
- a non-obvious rule;
- an important limitation;
- the purpose of a public API.
Avoid comments that merely repeat obvious code.
18. Java Is Case-Sensitive
Java treats uppercase and lowercase letters as different.
These names are different:
HelloPilkupil
hellopilkupil
helloPilkupil
HELLOPILKUPILThis class:
public class HelloPilkupil {
}must be run with the correct capitalization:
java HelloPilkupilnot:
java hellopilkupilThe same rule applies to methods and variables.
19. Statements and Expressions
A statement performs an action.
Examples:
int total = 10;
System.out.println(total);
total++;An expression produces a value.
Examples:
10 + 5
name.toUpperCase()
args.length > 0Expressions can appear inside statements.
int total = 10 + 5;Here:
10 + 5
└── expressionint total = 10 + 5;
└── statement
```
This distinction becomes more important when we study operators, conditions, and methods.
20. Improve the First Program
Let us create a slightly more useful version.
public class HelloPilkupil {public static void main(String[] args) {
String learnerName = "Java Learner";
int completedTutorials = 7;
System.out.println(
"Welcome, " + learnerName + "!"
);
System.out.println(
"Completed tutorials: "
+ completedTutorials
);
}
}
```
Output:
Welcome, Java Learner!
Completed tutorials: 7This introduces variables.
learnerName
└── stores textcompletedTutorials
└── stores an integer
```
The + operator combines strings with other values.
21. Common Beginner Errors
File Name Does Not Match the Class
Class:
public class HelloPilkupilRequired file:
HelloPilkupil.javaIncorrect Capitalization
Incorrect:
system.out.println("Hello");Correct:
System.out.println("Hello");Missing Semicolon
Incorrect:
System.out.println("Hello")Correct:
System.out.println("Hello");Single Quotes Used for Text
Incorrect:
System.out.println('Hello');Correct:
System.out.println("Hello");Missing Closing Brace
Make sure every opening brace has a matching closing brace.
Incorrect Main Method
Incorrect:
public void main(String[] args)Correct:
public static void main(String[] args)Running the File Name
Incorrect:
java HelloPilkupil.classCorrect:
java HelloPilkupil22. Compilation Checklist
[ ] The file ends with .java
[ ] The public class matches the file name
[ ] Java keywords use the correct spelling
[ ] System begins with uppercase S
[ ] Strings use double quotation marks
[ ] Statements end with semicolons
[ ] Every opening brace has a closing brace
[ ] main is public static void
[ ] Compilation completes without errors
[ ] The class is run without .java or .class23. Mini Exercise
Create:
LearningProfile.javaThe program should print:
Name: Alya
Current topic: First Java Program
Tutorial number: 7Use:
String name;String currentTopic;int tutorialNumber.
Suggested Solution
public class LearningProfile {public static void main(String[] args) {
String name = "Alya";
String currentTopic =
"First Java Program";
int tutorialNumber = 7;
System.out.println(
"Name: " + name
);
System.out.println(
"Current topic: " + currentTopic
);
System.out.println(
"Tutorial number: "
+ tutorialNumber
);
}
}
```
Compile:
javac LearningProfile.javaRun:
java LearningProfileExpected output:
Name: Alya
Current topic: First Java Program
Tutorial number: 724. Knowledge Check
- What is the purpose of a class?
- Why must
HelloPilkupilbe stored inHelloPilkupil.java? - Why is the
mainmethod static? - What does
voidmean? - What is stored in
String[] args? - What does
System.out.printlndo? - What is the difference between
printandprintln? - Why do many statements end with a semicolon?
- What do braces represent?
- Why is indentation important if Java mostly ignores whitespace?
Suggested Answers
- A class groups related fields, methods, and behavior.
- A public top-level class must match its source file name.
- The JVM can call it through the class without first creating an object.
- The method does not return a Java value.
- Command-line arguments passed to the application.
- It prints a value to standard output and adds a new line.
printstays on the same line;printlnadds a line break.- The semicolon marks the end of many Java statements.
- They define code blocks such as class and method bodies.
- Indentation makes the program structure easier for humans to understand.
Key Takeaways
public class HelloPilkupil
│
├── public
│ └── accessible class
├── class
│ └── declares a class
└── HelloPilkupil
└── class namepublic static void main(String[] args)
│
├── public
│ └── launcher can access it
├── static
│ └── called without creating an object
├── void
│ └── returns no value
├── main
│ └── application entry point
└── String[] args
└── command-line arguments
System.out.println(...)
│
├── System
│ └── standard Java class
├── out
│ └── standard output
└── println
└── print and move to the next line
```
The most important points are:
- Java application code is organized inside classes.
- A public class name must match its file name.
- The traditional entry point is
public static void main(String[] args). String[] argscontains command-line arguments.System.out.printlnprints a line to standard output.- Double quotation marks define strings.
- Semicolons end many statements.
- Braces define code blocks.
- Java is case-sensitive.
- Indentation improves readability.
- Comments should explain useful context.
- Compile with
javacand run the class withjava.
What's Next?
The next tutorial will focus on the rules that shape Java source code:
Java Syntax and Code Structure
We will study:
identifiers
keywords
literals
statements
expressions
code blocks
naming conventions
whitespace
source-file structureOfficial Sources and Further Reading
- Java Language Specification — Program Structure
- Java Language Specification — Classes
- Java Language Specification — Methods
- The
javaCommand — JDK 25 - The
javacCommand — JDK 25 - Dev.java — Getting Started with Java
This article is part of the Java tutorial series on Pilkupil Lab.