π What Youβll Learn
- Java program structure
- Key syntax elements: classes, methods, statements
- Naming conventions
- How Java code is organized and executed
π§± Basic Java Structure
Every Java application is made up of classes and methods. The main
method is the entry point of any standalone Java program.
Hereβs a minimal Java program:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
π Breakdown
public
class
HelloWorld
: Defines a class namedHelloWorld
. Java programs are class-based.public
static
void
main(String[] args)
: The starting point of the program.System.out.println()
: A statement that prints to the console.{}
: Code blocks grouped together.;
: Every statement ends with a semicolon.
π§ Java is Case-Sensitive
These are not the same:
System.out.println(); // valid
system.out.println(); // invalid β βsystemβ should be capitalized
π§ Naming Conventions
Follow these standard conventions to keep code readable:
| Type | Convention | Example |
|-||--|
| Class | PascalCase | MyFirstClass
|
| Method/Variable| camelCase | printMessage()
|
| Constant | ALL_CAPS_WITH_UNDERSCORES | MAX_VALUE
|
β Code Formatting Tips
- Use indentation (typically 4 spaces or a tab).
- Keep braces on the same or next line (consistent with your IDE settings).
- Add comments using:
//
for single line/* */
for multi-line
// This is a single-line comment
/*
This is a
multi-line comment
*/
π‘ Example: Simple Java Program
public class Greeting {
public static void main(String[] args) {
String name = "Java";
System.out.println("Hello, " + name + "!");
}
}
π« Common Syntax Errors
- Missing semicolon
;
- Unmatched braces
{}
or parentheses()
- Wrong casing (e.g.,
String
vsstring
) - Incorrect method or class names
π Recap
Java code follows a consistent structure:
- Classes contain methods
- The
main()
method is the starting point - Every statement ends in
;
- Curly braces define code blocks