Java Syntax and Basic Structure

Chapter 3: Java Syntax and Basic Structure

Java Syntax and Basic Structure

3.1 Structure of a Java Program

Every Java program follows a specific structure that ensures it runs correctly. It includes:

  • Class definition
  • main() method (entry point)
  • Statements inside curly braces { }
public class MyProgram {
    public static void main(String[] args) {
        System.out.println("Java is powerful!");
    }
}

3.2 Components of a Java Program

  • Class Name
  • Methods
  • Statements & Expressions

3.3 Java Syntax Rules

  • Java is case-sensitive: Mainmain
  • File name must match the public class name
  • The main method must be exactly: public static void main(String[] args)

3.4 Java Comments

Comments make your code easy to understand:

  • Single-line: // This is a single-line comment
  • Multi-line:
    /* This is a
       multi-line comment */
    
  • Documentation comment:
    /**
     * This class prints Hello World.
     */
    

3.5 Printing Output in Java

We use System.out.println() or System.out.print():

System.out.println("Welcome!");
System.out.print("Hello ");
System.out.print("Java");

Output:

Welcome!
Hello Java

println prints and moves to a new line, while print stays on the same line.

3.6 The main() Method Breakdown

public static void main(String[] args)

This is the entry point for any Java application.

3.7 Writing Clean Java Code

  • Use meaningful class and variable names
  • Follow proper indentation and spacing
  • Write comments to explain your logic

💻 Practice Programs

  1. Print your school or college name.
  2. Modify HelloWorld to print your name and city.
  3. Add single-line and multi-line comments in your code.
  4. Create a class Intro that prints 3 lines of output.

❓ FAQs on Java Syntax & Structure

Q1: What is the basic structure of a Java program?

A: It includes:

  • Class definition
  • Main method
  • Statements inside the method

Q2: What is the role of the main() method?

A: It’s the entry point where Java program execution begins. Signature:

public static void main(String[] args)

Q3: What are Java statements and blocks?

A: Statements are executable instructions. A block is a group of statements enclosed in curly braces { }.

Q4: Are semicolons important in Java?

A: Yes. Each Java statement must end with a semicolon ;.

Q5: What is case sensitivity in Java?

A: Java treats identifiers with different letter cases as different entities.

Q6: How are comments written in Java?

A:

  • Single-line: // comment
  • Multi-line:
    /* comment */
    

📌 Related Java Learning Links

Comments

Popular posts from this blog

Java Classes in Depth – Complete Guide with Definitions, Syntax & Examples

Introduction to Java

Learn Java Free: Complete 14-Chapter Course (Beginner to Advanced)