π₯ Basic Structure of a Java Program
Every Java program follows a specific structure:
public class MyClass {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}π§ Breakdown:
public class MyClass: Defines the class. The file must be namedMyClass.javapublic static void main(String[] args): The main method is the starting point of executionSystem.out.println(...): Prints output with a newline
π File Name Must Match Class Name
If you define:
public class HelloWorld { }then the file must be named:
HelloWorld.javaβ hello.java will cause an error!
π Semicolons and Braces
All statements end with a semicolon (
;)Curly braces
{}are used to define code blocks (class body, method body, loop body)
Example:
public class Demo {
public static void main(String[] args) {
System.out.println("Correct syntax!");
}
}π€ Method Declaration Syntax
Java method syntax follows this order:
[access_modifier] [static] return_type method_name([parameters]) {
// method body
}Example:
public static void greet() {
System.out.println("Welcome!");
}π Case Sensitivity
Java is case-sensitive:
SystemβsystemMainβmain
Always use the correct case or you'll get a compilation error.
β£ Whitespace and Formatting
Java ignores extra spaces and line breaks, but you should follow proper indentation.
Standard indentation is 4 spaces per block level.
Good:
public class Demo {
public static void main(String[] args) {
System.out.println("Neat and clean!");
}
}π§Ύ Escape Characters in Java
What is an Escape Sequence in Java (or any programming language)?
An escape sequence is a special character combination used in string literals to represent characters that cannot be typed directly or would otherwise be misinterpreted by the compiler.
They start with a backslash (\\), followed by one or more characters.
Why Do We Need Escape Sequences?
We use escape sequences because:
Some characters have special meanings (like quotes, new lines, or tabs).
We can't directly insert some characters like newline, tab, or backslash itself in a string.
They allow formatting strings in a readable way.
Escape Sequence | Meaning | Example Output |
|---|---|---|
| New Line |
|
| Tab space |
|
| Double Quote |
|
| Backslash |
|
Example:
System.out.println("She said, \\"Java is fun!\\"");