JAVA - Zero to Hero / Java Fundamentals

Java Syntax

πŸ“₯ 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 named MyClass.java

  • public static void main(String[] args): The main method is the starting point of execution

  • System.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 β‰  system

  • Main β‰  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:

  1. Some characters have special meanings (like quotes, new lines, or tabs).

  2. We can't directly insert some characters like newline, tab, or backslash itself in a string.

  3. They allow formatting strings in a readable way.

Escape Sequence

Meaning

Example Output

\\n

New Line

Hello\\nWorld β†’ 2 lines

\\t

Tab space

Hello\\tWorld

\\"

Double Quote

\\"Hello\\" β†’ "Hello"

\\\\

Backslash

C:\\\\Java

Example:

System.out.println("She said, \\"Java is fun!\\"");