Basic Program Structure
Part of the Fundamentals section of Coddy's Java journey — lesson 4 of 73.
In Java, every line of code that runs must be inside a class. A class is like a blueprint for creating objects, which are instances of the class. In our lessons, we will name the main class Main, but it can be named anything.
The main method is a crucial part of a Java program because it serves as the starting point of execution. When you run a Java program, the Java Virtual Machine (JVM) looks for the main method to begin executing the code. Without a main method, the JVM wouldn't know where to start.
Here's a simple breakdown of a basic Java program:
public class Main { // Class declaration
public static void main(String[] args) { // Main method
System.out.println("Hello, Coddy!"); // Output statement
}
}Important note: In Java, each statement must end with a semicolon (;). The semicolon is mandatory and tells Java that you've reached the end of a statement. Forgetting to add a semicolon will result in a compilation error.
However, note that code blocks enclosed in curly braces {} (like class and method declarations) don't need semicolons.
Challenge
BeginnerCreate a Java program with a class named Main that contains the main method. Inside the main method, write code to output the following text:
This is my first Java program!Cheat sheet
In Java, every line of code must be inside a class. The main method serves as the starting point of execution.
Basic Java program structure:
public class Main { // Class declaration
public static void main(String[] args) { // Main method
System.out.println("Hello, Coddy!"); // Output statement
}
}Important: Each statement must end with a semicolon (;). Code blocks with curly braces {} don't need semicolons.
To output text, use System.out.println():
System.out.println("Your text here");Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else