First Java Program
Write, compile, and run your first Java program. Learn how source files, classes, the main method, statements, comments, compilation, bytecode, the JVM, and program execution work together.
Introduction
Now that Java is installed and configured, it is time to write your first complete Java program. This lesson will take you through every part of the program, from creating the source file to seeing the final output.
A first program may contain only a few lines of code, but those lines introduce several fundamental Java concepts: classes, methods, statements, strings, compilation, bytecode, the JVM, and program execution.
Instead of only copying a Hello World program, you will understand what every important part means and how Java transforms your source code into a running application.
WRITE SOURCE CODE
│
▼
SAVE AS .java FILE
│
▼
COMPILE WITH javac
│
▼
GENERATE .class FILE
│
▼
RUN WITH java
│
▼
JVM EXECUTES BYTECODE
│
▼
OUTPUT APPEARS- How to create your first Java source file.
- How to write a complete Java program.
- What a class declaration means.
- Why the class name matters.
- What curly braces represent.
- What the main method is.
- Why main is the program entry point.
- What public means in the main method.
- What static means in the main method.
- What void means in the main method.
- Why the method is named main.
- What String[] args represents.
- How System.out.println() works.
- What System represents.
- What out represents.
- What println() does.
- What a string literal is.
- Why statements use semicolons.
- How to compile a Java program.
- What compilation produces.
- What a .class file contains.
- How to run a Java program.
- How source code becomes output.
- Why Java is case-sensitive.
- How Java filenames and class names are related.
- Why indentation improves readability.
- How whitespace affects Java code.
- How to write multiple statements.
- The difference between print() and println().
- How to print text, numbers, and calculations.
- How escape sequences work.
- How Java comments work.
- How command-line arguments work.
- The difference between compile-time, runtime, and logical errors.
- How to solve common first-program errors.
Your First Java Program
The traditional first program in almost every programming language displays a simple message. In Java, we will begin by printing Hello, World! to the console.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Hello, World!- Create the source file.
- Write the program.
- Compile the source code.
- Run the compiled program.
- See Hello, World! in the terminal.
Create a Project Folder
Create a separate folder for your first Java program. Keeping source files organized makes compilation and execution easier.
JavaCourse
└── FirstProgram
└── HelloWorld.javaOpen your terminal inside the folder where the Java source file will be stored.
CURRENT DIRECTORY
FirstProgram
│
▼
CONTAINS
HelloWorld.java- The compiler must be able to find the source file.
- The Java launcher must be able to find the compiled class.
- Many beginner errors happen because commands are executed from the wrong directory.
Create the Source File
Create a new file named HelloWorld.java. Java source files use the .java extension.
HelloWorld.javaHelloWorld.txt
HelloWorld.java.txt
helloworld.java
Hello.java- Some operating systems hide known file extensions.
- A file that appears as HelloWorld.java may actually be HelloWorld.java.txt.
- Make sure the real filename ends with .java.
Write the Complete Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Save the file before compiling it. The compiler reads the saved contents of the source file.
public class HelloWorld
│
▼
CLASS DECLARATION
public static void main(String[] args)
│
▼
MAIN METHOD
System.out.println("Hello, World!");
│
▼
OUTPUT STATEMENTUnderstanding the Program
The first program contains several pieces of Java syntax. Each part has a specific role.
public class HelloWorld {
// └──────── Class Name
public static void main(String[] args) {
// └── Main Method
System.out.println("Hello, World!");
// └── Output Statement
}
}CLASS
└── METHOD
└── STATEMENTAt this stage, focus on recognizing the structure. Later lessons will explain classes, methods, objects, access modifiers, arrays, and strings in greater depth.
The Class Declaration
public class HelloWorld {
}Java programs are organized using classes. The class keyword declares a class, and HelloWorld is the name of this class.
public class HelloWorld
│ │ │
│ │ └── Class Name
│ │
│ └────────── Class Keyword
│
└───────────────── Access Modifier- Think of a class as a container for program code.
- The main method is written inside the class.
- Later lessons will explain classes in detail.
The Class Name
HelloWorldHelloWorld is an identifier chosen as the class name. Java naming conventions usually begin class names with an uppercase letter and use PascalCase for multiple words.
GOOD CONVENTION
HelloWorld
Student
BankAccount
EmployeeManagementSystem
POOR CONVENTION
helloworld
student_data
BANKACCOUNT- Begin each word with an uppercase letter.
- Do not normally use spaces.
- Use meaningful names.
- Use PascalCase for multiple words.
Curly Braces
{
}Curly braces define blocks of code. An opening brace begins a block, and a closing brace ends it.
public class HelloWorld { // Class block starts
public static void main(String[] args) { // Method block starts
System.out.println("Hello!");
} // Method block ends
} // Class block endsCLASS BLOCK
{
METHOD BLOCK
{
STATEMENTS
}
}- Every opening brace should have a matching closing brace.
- Missing braces can cause compilation errors.
- Indentation helps you see which braces belong together.
The main Method
public static void main(String[] args) {
}The main method is the traditional entry point of a standalone Java application. When you run the class, the Java launcher looks for an appropriate main method to begin program execution.
public static void main(String[] args)
│ │ │ │ │
│ │ │ │ └── Parameter Name
│ │ │ │
│ │ │ └─────────── String Array Parameter
│ │ │
│ │ └───────────────── Method Name
│ │
│ └──────────────────────── Return Type
│
└─────────────────────────────── ModifiersThe public Keyword
public static void main(String[] args)The public keyword is an access modifier. In the traditional main method declaration, it allows the Java launcher to access the method when starting the application.
- You will learn access modifiers in later lessons.
- For now, recognize public as part of the standard main method declaration.
The static Keyword
public static void main(String[] args)The static keyword allows the main method to belong to the class itself rather than requiring an object of the class to be created before the method can be called.
PROGRAM STARTS
│
▼
NO HelloWorld OBJECT EXISTS YET
│
▼
main IS static
│
▼
JVM CAN START EXECUTION- Static members will be explained in detail later.
- For now, remember that the traditional main method is static.
The void Keyword
public static void main(String[] args)The void keyword is the return type of the main method. It means the method does not return a value.
METHOD EXECUTES
│
▼
PERFORMS STATEMENTS
│
▼
RETURNS NO VALUE
│
▼
voidThe main Method Name
mainThe method name is main. The Java launcher recognizes this method name as part of the traditional application entry-point signature.
- main is correct.
- Main is different.
- MAIN is different.
- Changing capitalization changes the identifier.
Understanding String[] args
String[] argsString[] args is the parameter of the main method. It allows the program to receive command-line arguments as an array of strings.
String[] args
│ │
│ └── Variable Name
│
└────────── Array of StringsThe name args is conventional but not mandatory. The parameter can use another valid variable name.
public static void main(String[] values) {
}- Most Java programs use the name args.
- Following common conventions makes code easier for other developers to understand.
The Program Entry Point
An entry point is the location where program execution begins. In the traditional Java application structure, execution begins from the main method.
RUN
java HelloWorld
│
▼
JAVA LAUNCHER LOADS CLASS
│
▼
LOCATES main METHOD
│
▼
STARTS EXECUTING STATEMENTS
│
▼
PROGRAM ENDSpublic class HelloWorld {
public static void main(String[] args) {
// Execution starts inside this method
System.out.println("Hello, World!");
}
}Understanding System.out.println()
System.out.println("Hello, World!");This statement displays text in the console and then moves the cursor to a new line.
System.out.println("Hello, World!");
│ │ │ │
│ │ │ └── Semicolon
│ │ │
│ │ └───────────── Method Call
│ │
│ └──────────────────── Output Stream
│
└────────────────────────── System ClassThe System Class
SystemSystem is a class provided by Java. It provides access to system-related resources and utilities.
- You do not need to understand the complete System class yet.
- Recognize that System is the class used at the beginning of the output statement.
The out Object
System.outout represents the standard output stream. It is commonly connected to the terminal or console where program output is displayed.
JAVA PROGRAM
│
▼
System.out
│
▼
STANDARD OUTPUT
│
▼
TERMINAL / CONSOLEThe println Method
println("Hello, World!")println is a method used to print a value and then move to the next line.
System.out.println("Java");
System.out.println("Programming");
System.out.println("Course");Java
Programming
CourseString Literal
"Hello, World!"Text written directly inside double quotation marks is called a string literal.
"Java"
"Hello, World!"
"My name is Alex"
"12345"- Text literals use double quotation marks.
- Removing the quotation marks changes how Java interprets the content.
- Opening and closing quotation marks must match.
The Semicolon
System.out.println("Hello, World!");Many Java statements end with a semicolon. The semicolon marks the end of the statement.
System.out.println("First");
System.out.println("Second");
System.out.println("Third");- A missing required semicolon causes a compilation error.
- The compiler usually reports the location near the problem.
- The reported location may not always be the exact character where the mistake began.
Compile the Program
Open a terminal in the folder containing HelloWorld.java and run the Java compiler.
javac HelloWorld.javaFirstProgram
└── HelloWorld.javaFirstProgram
├── HelloWorld.java
└── HelloWorld.class- The command may display no message.
- A HelloWorld.class file should be created.
- No compiler error should appear.
What Compilation Does
The Java compiler reads the source code, checks it for compilation errors, and translates valid code into bytecode.
HelloWorld.java
│
▼
javac COMPILER
│
├── Reads Source Code
│
├── Checks Syntax
│
├── Checks Language Rules
│
└── Generates Bytecode
│
▼
HelloWorld.classIf the source code contains compilation errors, the compiler reports them and the expected class file may not be generated.
The .class File
The .class file contains Java bytecode generated by the compiler. It is not ordinary Java source code.
HelloWorld.java
CREATED BY:
Developer
CONTAINS:
Java Source Code
HelloWorld.class
CREATED BY:
javac Compiler
CONTAINS:
Java Bytecode- Write and edit the .java source file.
- Compile the source file again after changes.
- The compiler regenerates the .class file.
Run the Program
After successful compilation, run the program using the java command followed by the class name.
java HelloWorldHello, World!- Use: java HelloWorld
- Do not use: java HelloWorld.class
- The traditional launcher command uses the class name.
Complete Execution Flow
STEP 1
WRITE
HelloWorld.java
│
▼
STEP 2
COMPILE
javac HelloWorld.java
│
▼
STEP 3
GENERATE
HelloWorld.class
│
▼
STEP 4
RUN
java HelloWorld
│
▼
STEP 5
JVM EXECUTES BYTECODE
│
▼
STEP 6
OUTPUT
Hello, World!From Source Code to Output
DEVELOPER
│
▼
WRITES SOURCE CODE
│
▼
HelloWorld.java
│
▼
javac
│
▼
BYTECODE
│
▼
HelloWorld.class
│
▼
java COMMAND
│
▼
JVM STARTS
│
▼
CLASS LOADED
│
▼
main METHOD FOUND
│
▼
STATEMENTS EXECUTED
│
▼
System.out.println()
│
▼
OUTPUT DISPLAYEDJava is Case-Sensitive
Java treats uppercase and lowercase letters as different characters.
HelloWorld
helloworld
HELLOWORLD
helloWorld
ALL ARE DIFFERENTSystem.out.println("Hello");system.out.println("Hello");- System is not system.
- String is not string.
- HelloWorld is not helloworld.
- main is not Main.
Filename Rules
When a source file contains a public top-level class, the filename must match the public class name.
PUBLIC CLASS
HelloWorld
│
▼
FILENAME
HelloWorld.javaPUBLIC CLASS
HelloWorld
│
▼
FILENAME
Hello.java
│
▼
COMPILATION ERRORClass Name Rules
- A class name is an identifier.
- It cannot contain spaces.
- It cannot begin with a digit.
- It cannot be a reserved Java keyword.
- It can contain letters, digits, underscores, and dollar signs, subject to identifier rules.
- Class names conventionally use PascalCase.
- Meaningful names are preferred.
VALID
HelloWorld
Student
BankAccount
Employee2
INVALID
2Employee
Bank Account
publicIndentation
Indentation means adding spaces before nested code to visually show the program structure.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}public class HelloWorld{
public static void main(String[] args){
System.out.println("Hello, World!");
}
}- Indent code inside classes.
- Indent code inside methods.
- Use consistent spacing.
- Let your editor or IDE format code when appropriate.
Whitespace
Whitespace includes spaces, tabs, and line breaks. Java often allows flexible whitespace between tokens, but whitespace cannot be inserted everywhere.
System.out.println("Hello");
System
.
out
.
println
(
"Hello"
)
;- Legal formatting is not always good formatting.
- Use conventional formatting.
- Do not make code unnecessarily difficult to read.
Writing Multiple Statements
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello!");
System.out.println("Welcome to Java.");
System.out.println("This is my first program.");
}
}Hello!
Welcome to Java.
This is my first program.Statements inside the main method normally execute sequentially from top to bottom unless control-flow logic changes the order.
STATEMENT 1
│
▼
STATEMENT 2
│
▼
STATEMENT 3
│
▼
PROGRAM CONTINUESThe print() Method
The print() method displays output without automatically moving to a new line afterward.
System.out.print("Hello ");
System.out.print("Java");
System.out.print("!");Hello Java!The println() Method
The println() method displays output and then moves to the next line.
System.out.println("Hello");
System.out.println("Java");
System.out.println("!");Hello
Java
!print() vs println()
print()
PRINTS VALUE
+
STAYS ON SAME LINE
println()
PRINTS VALUE
+
MOVES TO NEXT LINEprint()
Displays output without automatically adding a line break.
println()
Displays output and then adds a line break.
Printing Numbers
Numbers can be printed without quotation marks.
System.out.println(10);
System.out.println(25);
System.out.println(1000);10
25
1000- "10" is a string literal.
- 10 is a numeric literal.
- They may look similar in output but represent different kinds of values.
Printing Calculations
Java can evaluate an expression before printing the result.
System.out.println(10 + 5);
System.out.println(20 - 8);
System.out.println(6 * 4);
System.out.println(20 / 5);15
12
24
4EXPRESSION
10 + 5
│
▼
EVALUATION
15
│
▼
PRINT
15Printing Text and Numbers
System.out.println("Age: " + 25);Age: 25System.out.println(10 + 20);
System.out.println("10" + "20");
System.out.println("Result: " + 10 + 20);
System.out.println("Result: " + (10 + 20));30
1020
Result: 1020
Result: 30- Numeric addition can produce a mathematical result.
- String concatenation joins values as text.
- Parentheses can control which expression is evaluated first.
- Operators will be explained in detail in a later lesson.
Escape Sequences
Escape sequences are special character combinations beginning with a backslash. They allow certain special characters and formatting to be represented inside string literals.
\n New Line
\t Horizontal Tab
\" Double Quote
\' Single Quote
\\ Backslash
\b Backspace
\r Carriage ReturnNew Line Escape Sequence
System.out.println("Java\nProgramming\nCourse");Java
Programming
CourseTab Escape Sequence
System.out.println("Name\tAge");
System.out.println("Alex\t25");Name Age
Alex 25Printing Quotes and Backslashes
System.out.println("He said, \"Hello!\"");He said, "Hello!"System.out.println("C:\\Java\\Projects");C:\Java\ProjectsComments
Comments are notes written inside source code for developers. The compiler ignores comment content as executable program instructions.
// Single-Line
Used for a comment that continues to the end of the current line.
/* Multi-Line */
Used for comments that can span multiple lines.
/** Documentation */
Used for documentation comments that can be processed by documentation tools.
Single-Line Comments
public class HelloWorld {
public static void main(String[] args) {
// Print a welcome message
System.out.println("Welcome to Java!");
}
}System.out.println("Hello"); // Display HelloMulti-Line Comments
/*
This is a multi-line comment.
It can contain multiple lines.
*/
System.out.println("Hello");- Comments should explain useful information.
- Do not comment every obvious statement.
- Keep comments accurate when code changes.
Documentation Comments
/**
* Displays a welcome message.
*/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Welcome!");
}
}Documentation comments begin with /** and can be used by documentation tools such as Javadoc.
- Documentation comments are especially useful for classes, methods, and APIs.
- You will understand their value more clearly after learning methods and classes.
Command-Line Arguments
Command-line arguments are values supplied after the class name when starting a Java application.
java HelloWorld AlexCOMMAND
java HelloWorld Alex
│
▼
ARGUMENT
Alex
│
▼
String[] args
│
▼
args[0]Using args
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, " + args[0] + "!");
}
}javac HelloWorld.javajava HelloWorld AlexHello, Alex!- This example expects at least one command-line argument.
- Running it without an argument causes a runtime error.
- Arrays and error handling will be covered later.
Multiple Command-Line Arguments
public class ArgumentsExample {
public static void main(String[] args) {
System.out.println("First: " + args[0]);
System.out.println("Second: " + args[1]);
System.out.println("Third: " + args[2]);
}
}java ArgumentsExample Java Is PowerfulFirst: Java
Second: Is
Third: PowerfulJava Is Powerful
│ │ │
▼ ▼ ▼
args[0] args[1] args[2]Command-Line Arguments are Strings
Values received through String[] args are strings, even when they look like numbers.
java Example 10 20args[0] = "10"
args[1] = "20"- The arguments are initially strings.
- Numeric text must be converted before normal numeric calculations.
- Type conversion will be covered in later lessons.
Can You Run a Java Source File Without Traditional Compilation?
Modern Java versions support launching a single source file directly. In this mode, the source file can be provided to the java command.
java HelloWorld.javaThe Java launcher handles the required compilation steps for the source-file launch process.
- Understand javac HelloWorld.java.
- Understand the generated HelloWorld.class file.
- Understand java HelloWorld.
- The traditional process clearly teaches compilation and execution.
Traditional Compilation vs Source-File Mode
SOURCE FILE
HelloWorld.java
│
▼
javac HelloWorld.java
│
▼
HelloWorld.class
│
▼
java HelloWorld
│
▼
OUTPUTSOURCE FILE
HelloWorld.java
│
▼
java HelloWorld.java
│
▼
LAUNCHER HANDLES SOURCE EXECUTION
│
▼
OUTPUT- This course will emphasize the traditional compile-and-run model first.
- It gives you a clearer understanding of source code, bytecode, class files, and JVM execution.
Compile-Time Errors
Compile-time errors are detected while the compiler is processing source code.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello")
}
}The output statement is missing a semicolon, so the compiler reports an error.
SOURCE CODE
│
▼
javac
│
▼
ERROR FOUND
│
▼
ERROR MESSAGE
│
▼
FIX SOURCE CODE
│
▼
COMPILE AGAINRuntime Errors
Runtime errors occur while a program is executing. The source code may compile successfully, but a problem happens during execution.
public class HelloWorld {
public static void main(String[] args) {
System.out.println(args[0]);
}
}The program can compile successfully, but running it without an argument causes an error because args[0] does not exist.
SOURCE CODE
│
▼
COMPILES SUCCESSFULLY
│
▼
PROGRAM STARTS
│
▼
PROBLEM OCCURS DURING EXECUTION
│
▼
RUNTIME ERRORLogical Errors
A logical error occurs when the program runs but produces an incorrect result because the program logic is wrong.
public class Calculation {
public static void main(String[] args) {
System.out.println("10 + 20 = " + 10 + 20);
}
}10 + 20 = 1020System.out.println("10 + 20 = " + (10 + 20));10 + 20 = 30Common First Program Errors
FIRST PROGRAM ERRORS
├── Wrong Filename
├── Wrong Class Name
├── Missing Semicolon
├── Incorrect Capitalization
├── Missing Quote
├── Missing Brace
├── Wrong Directory
├── Wrong Compile Command
├── Wrong Run Command
└── Old .class FileError: Wrong Filename
public class HelloWorld {
}Hello.javaHelloWorld.java- Check the public class name.
- Rename the source file to match it exactly.
- Remember that capitalization matters.
Error: Missing Semicolon
System.out.println("Hello")System.out.println("Hello");- Check the statement reported by the compiler.
- Check the previous line as well.
- Add the missing semicolon where required.
Error: Incorrect Capitalization
system.out.println("Hello");System.out.println("Hello");- Java is case-sensitive.
- System begins with uppercase S.
- String begins with uppercase S.
- main uses lowercase letters.
Error: Unclosed String Literal
System.out.println("Hello);System.out.println("Hello");- Check the opening double quote.
- Check the closing double quote.
- Escape quotes that should appear inside the string.
Error: Missing Brace
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello");
}The method block is closed, but the class block is not closed.
OPENING BRACES
{
{
CLOSING BRACES
}
MISSING
}Error: Could Not Find or Load Main Class
This error can occur when the Java launcher cannot locate the requested class in the expected class path and directory context.
POSSIBLE CAUSES
├── Class Was Not Compiled
├── Wrong Class Name Used
├── Wrong Current Directory
├── Package Structure Mismatch
└── Classpath Problem- Confirm that HelloWorld.class exists.
- Confirm that you are in the correct directory.
- Run java HelloWorld with the exact class name.
- Do not add .class to the class name.
Error: Running Commands from the Wrong Directory
CURRENT DIRECTORY
FirstProgram
│
▼
FILES
HelloWorld.java
HelloWorld.classjavac HelloWorld.java
java HelloWorld- List the files in the current directory.
- Confirm the source file is present before compiling.
- Confirm the class file is present before traditional execution.
First Program Variations
public class Introduction {
public static void main(String[] args) {
System.out.println("Hello!");
System.out.println("My name is Alex.");
System.out.println("I am learning Java.");
}
}public class Calculation {
public static void main(String[] args) {
System.out.println("10 + 20 = " + (10 + 20));
System.out.println("10 * 20 = " + (10 * 20));
}
}public class Pattern {
public static void main(String[] args) {
System.out.println("*");
System.out.println("**");
System.out.println("***");
System.out.println("****");
System.out.println("*****");
}
}Best Practices for Your First Programs
- Use meaningful class names.
- Follow Java naming conventions.
- Match the public class name and filename.
- Use consistent indentation.
- Keep opening and closing braces easy to identify.
- Save the source file before compiling.
- Read compiler errors carefully.
- Fix one error at a time.
- Compile again after changing the source code.
- Run the newly compiled class.
- Use comments only when they add useful information.
- Practice writing programs manually instead of only copying code.
- Use the command line enough to understand compilation and execution.
- Do not depend entirely on an IDE Run button.
- Experiment with print(), println(), strings, numbers, and calculations.
First Program Execution Checklist
FIRST JAVA PROGRAM CHECKLIST
[ ] Java is installed
[ ] java -version works
[ ] javac -version works
[ ] Project folder created
[ ] HelloWorld.java created
[ ] File extension is correct
[ ] Public class is HelloWorld
[ ] Filename is HelloWorld.java
[ ] main method is present
[ ] Output statement is present
[ ] Quotes are closed
[ ] Semicolon is present
[ ] Braces are balanced
[ ] Source file is saved
[ ] Terminal is in correct directory
[ ] javac HelloWorld.java succeeds
[ ] HelloWorld.class is created
[ ] java HelloWorld runs
[ ] Expected output appearsCommon Misconceptions
- A Java source file is not the same as a class file.
- .java files contain source code.
- .class files contain compiled bytecode.
- The developer normally edits the .java file.
- The compiler generates the .class file.
- javac compiles Java source code.
- java launches Java applications.
- The traditional compile command includes the .java extension.
- The traditional run command uses the class name.
- java HelloWorld.class is not the normal traditional run command.
- Java is case-sensitive.
- System and system are different.
- String and string are different.
- main and Main are different.
- The public class name and filename must match.
- A file named HelloWorld.java.txt is not a Java source file with the expected extension.
- The main method is traditionally the program entry point.
- public, static, void, and main each have different meanings.
- String[] args is not random syntax.
- Command-line arguments are received through the main method parameter.
- Command-line arguments are strings initially.
- System.out.println() is made of multiple parts.
- println() prints a value and adds a line break.
- print() does not automatically add a line break.
- A semicolon commonly ends a Java statement.
- Curly braces define code blocks.
- Indentation improves readability even when some whitespace does not change program meaning.
- Comments are not executed as normal program statements.
- Compilation errors happen before successful execution.
- Runtime errors happen while the program is running.
- Logical errors can produce incorrect output without stopping the program.
- Successful compilation may produce no terminal message.
- Changing source code does not automatically update an old .class file in the traditional process.
- You must compile again after changing source code.
- Running from the wrong directory can prevent Java from finding the class.
- An IDE Run button does not remove the underlying compilation and execution concepts.
- Modern Java can support source-file launch mode, but understanding traditional compilation remains important.
- String concatenation and numeric addition can produce different results.
- Parentheses can change expression evaluation.
- Escape sequences are used to represent special characters inside strings.
Practice Exercises
- Create a class named HelloJava.
- Print: Hello, Java!
- Compile the program.
- Run the program.
- Create a class named AboutMe.
- Print your name.
- Print your city.
- Print the technology you are learning.
- Use separate println() statements.
- Use three print() statements.
- Display three words on the same line.
- Add spaces manually where required.
- Print the result of 50 + 25.
- Print the result of 50 - 25.
- Print the result of 50 * 25.
- Print the result of 50 / 25.
- Print three lines using one println() statement and \n.
- Print tab-separated values using \t.
- Print a sentence containing double quotation marks.
- Print a Windows-style path containing backslashes.
- Create a program that reads args[0].
- Display a welcome message containing that value.
- Run the program with your name as an argument.
- Remove a semicolon and observe the compiler error.
- Change System to system and observe the error.
- Remove a closing brace and observe the error.
- Restore the correct code after each experiment.
Common Interview Questions
What is the traditional entry point of a Java application?
The traditional entry point is the main method with the appropriate signature.
What does javac do?
javac compiles Java source code into Java bytecode.
What does the java command do?
The java command launches a Java application and starts the runtime process required to execute it.
What is a .java file?
A .java file is a source file containing Java source code.
What is a .class file?
A .class file contains Java bytecode generated by the compiler.
Why is the main method public?
In the traditional main method declaration, public allows the Java launcher to access the method.
Why is the main method static?
It allows the method to be invoked without first creating an object of the class.
What does void mean in the main method?
It means the method does not return a value.
What is String[] args?
It is an array of strings used to receive command-line arguments.
What is System.out.println()?
It is commonly used to print a value to standard output and then add a line break.
What is the difference between print() and println()?
print() does not automatically add a line break, while println() does.
Is Java case-sensitive?
Yes. Uppercase and lowercase letters are treated as different.
Why must the filename match the public class name?
A public top-level class must be declared in a source file with the corresponding class name.
What happens after javac successfully compiles a source file?
One or more .class files containing bytecode are generated.
What is a compile-time error?
It is an error detected during compilation.
What is a runtime error?
It is an error that occurs while the program is executing.
What is a logical error?
It is a mistake in program logic that causes incorrect results even though the program may compile and run.
What is a string literal?
It is text written directly inside double quotation marks.
Why are semicolons used?
Semicolons commonly mark the end of Java statements.
What do curly braces represent?
They define blocks of code such as class and method bodies.
Frequently Asked Questions
Why is Hello World usually the first program?
It provides a simple way to verify that the development environment works while introducing basic program structure and output.
Can I change HelloWorld to another class name?
Yes. Use a valid class name and make sure the filename matches the public class name.
Can I write Java without an IDE?
Yes. A text editor, JDK, and terminal are enough to write, compile, and run Java programs.
Why does javac show no output?
Successful compilation often produces no terminal message. Check whether the expected .class file was generated.
Why does my old output still appear after changing the code?
In the traditional process, you may be running an old .class file. Save the source file and compile it again.
Why should I not type java HelloWorld.class?
The traditional java launcher command uses the class name rather than the class filename.
Can I use another name instead of args?
Yes. args is a conventional parameter name, but another valid identifier can be used.
Can I remove String[] args?
For the traditional main method signature taught here, keep the command-line argument parameter.
Can main use String args[] instead?
Yes. Java permits array brackets after the type or variable name, though String[] args is the common convention.
Can I write everything on one line?
Some simple programs can be written on one line, but conventional formatting is much easier to read and maintain.
Does indentation affect Java execution?
Indentation generally does not define blocks in Java because braces do, but proper indentation is essential for readability.
Why does text use double quotes?
Double quotation marks define string literals in Java.
Can println() print numbers?
Yes. It can print numbers, strings, expressions, and many other values.
Why does "10" + "20" produce 1020?
Both values are strings, so the plus operator joins them as text.
Why does "Result: " + 10 + 20 produce Result: 1020?
Evaluation proceeds from left to right in this expression, and after string concatenation begins, the later numbers are joined as text.
How do I print 30 instead?
Use parentheses around the numeric calculation: "Result: " + (10 + 20).
Can Java run a source file directly?
Modern Java versions support source-file launch mode for suitable single-file programs, but the traditional compile-and-run process remains important to understand.
Why should I learn javac if an IDE compiles automatically?
Understanding javac teaches you what compilation does and helps you troubleshoot build and execution problems.
What happens if I run a program from the wrong folder?
The compiler or launcher may be unable to find the source file or compiled class.
Do comments appear in program output?
No. Comments are ignored as executable instructions and do not appear unless the program explicitly prints similar text.
What is the difference between \n and println()?
\n creates a newline inside string content, while println() prints its value and then adds a line break.
Can command-line arguments contain spaces?
A value containing spaces can generally be passed as one argument by quoting it appropriately in the shell.
Why does args[0] cause an error when no argument is provided?
The arguments array is empty, so there is no element at index 0.
Key Takeaways
- Java source files use the .java extension.
- A first Java program can be written in a simple text editor.
- Java programs are organized using classes.
- The class keyword declares a class.
- Class names conventionally use PascalCase.
- The public class name should match the source filename.
- HelloWorld should be stored in HelloWorld.java.
- Java is case-sensitive.
- HelloWorld and helloworld are different identifiers.
- Curly braces define code blocks.
- Opening and closing braces should match.
- The traditional Java application entry point is the main method.
- The traditional main method commonly uses public static void main(String[] args).
- public is an access modifier.
- static allows main to be used without creating an object first.
- void means the method returns no value.
- main is the method name recognized for traditional application startup.
- String[] args receives command-line arguments.
- args is a conventional parameter name.
- Command-line arguments are initially strings.
- System.out.println() prints output and adds a line break.
- System is a Java class.
- out represents the standard output stream.
- println() is a method.
- Text literals use double quotation marks.
- Many Java statements end with semicolons.
- javac compiles Java source code.
- The traditional compile command is javac HelloWorld.java.
- Successful compilation generates HelloWorld.class.
- .class files contain Java bytecode.
- The traditional run command is java HelloWorld.
- The JVM executes Java bytecode.
- The traditional execution command uses the class name, not the .class filename.
- Source code is written by the developer.
- Bytecode is generated by the compiler.
- Statements normally execute sequentially from top to bottom.
- print() does not automatically add a new line.
- println() adds a new line after output.
- Numbers can be printed without quotation marks.
- Expressions can be evaluated before printing.
- The plus operator can perform numeric addition or string concatenation.
- Parentheses can control expression evaluation.
- Escape sequences represent special characters inside strings.
- \n creates a new line.
- \t creates a horizontal tab.
- \" represents a double quote inside a string.
- \\ represents a backslash.
- Java supports single-line comments.
- Java supports multi-line comments.
- Java supports documentation comments.
- Comments are ignored as executable instructions.
- Command-line arguments are available through the main method parameter.
- Array indexing begins at 0.
- Modern Java supports source-file launch mode.
- The traditional compilation process is still important to understand.
- Compile-time errors are detected during compilation.
- Runtime errors occur during execution.
- Logical errors produce incorrect behavior or results.
- A missing semicolon can cause a compilation error.
- Incorrect capitalization can cause errors.
- Unclosed string literals cause compilation errors.
- Missing braces can cause compilation errors.
- Running from the wrong directory can prevent files or classes from being found.
- Source changes should be saved before compilation.
- In the traditional process, source changes must be recompiled.
- Successful compilation may display no message.
- Good indentation improves readability.
- Meaningful names improve code quality.
- The best way to learn the first program is to write, compile, modify, break, fix, and run it repeatedly.
Summary
Your first Java program introduces the complete development cycle: writing source code, saving it in a .java file, compiling it with javac, generating bytecode, and running the compiled class with the java command.
A Java program is organized inside a class. In the traditional application structure, execution begins from the main method. The declaration public static void main(String[] args) contains several important parts that will become clearer as you learn methods, arrays, classes, objects, and access modifiers.
The statement System.out.println() is commonly used to display output. System identifies a Java class, out provides access to standard output, and println() prints a value followed by a line break.
Java source code is stored in .java files. The javac compiler translates valid source code into bytecode stored in .class files. The Java launcher then starts the runtime environment and executes the application.
Java is case-sensitive, so capitalization matters. The public class name and source filename must match, required semicolons must be present, string quotation marks must be closed, and code blocks must use matching braces.
You also learned how print() and println() differ, how to display text and numbers, how expressions can be evaluated, how escape sequences work, and how comments can document source code.
The main method can receive command-line arguments through String[] args. These arguments are initially strings and can be accessed using array indexes.
Finally, you learned the difference between compile-time errors, runtime errors, and logical errors. Understanding these categories will make debugging easier throughout the rest of the course.
- You created your first Java source file.
- You wrote a complete Java program.
- You understand the basic class declaration.
- You understand why the class name matters.
- You understand curly braces and code blocks.
- You recognize the traditional main method.
- You understand the role of public in the main method.
- You understand the basic role of static.
- You understand what void means.
- You understand why the method is named main.
- You understand the purpose of String[] args.
- You understand the program entry point.
- You understand System.out.println().
- You understand the basic role of System.
- You understand the basic role of out.
- You understand what println() does.
- You understand string literals.
- You understand why semicolons are used.
- You know how to compile a Java source file.
- You understand what compilation does.
- You understand the purpose of the .class file.
- You know how to run a compiled Java program.
- You understand the complete source-to-output flow.
- You understand Java case sensitivity.
- You understand filename and public class name matching.
- You understand basic class naming rules.
- You understand why indentation matters.
- You understand basic whitespace behavior.
- You can write multiple statements.
- You understand print().
- You understand println().
- You know the difference between print() and println().
- You can print numbers.
- You can print calculations.
- You can combine text and values.
- You understand basic string concatenation.
- You understand basic escape sequences.
- You can create new lines and tabs inside strings.
- You can print quotes and backslashes.
- You understand Java comments.
- You can write single-line comments.
- You can write multi-line comments.
- You recognize documentation comments.
- You understand command-line arguments.
- You can access values from args.
- You understand that arguments are strings.
- You understand source-file launch mode.
- You know the difference between traditional compilation and source-file mode.
- You understand compile-time errors.
- You understand runtime errors.
- You understand logical errors.
- You can identify common first-program mistakes.
- You know how to solve filename problems.
- You know how to solve missing semicolon problems.
- You know how to identify capitalization mistakes.
- You know how to identify unclosed strings.
- You know how to identify missing braces.
- You understand basic main-class loading errors.
- You know why the current directory matters.
- You can create variations of your first program.
- You are ready to understand the detailed structure of a Java program.