JavaBasic Syntax

Java Basic Syntax

What is Java?

Java is a high-level, object-oriented programming language developed by Sun Microsystems. It’s platform-independent, secure, and widely used for building web, mobile, and desktop applications.

Java Program Structure

A Java program is essentially a collection of classes and objects that interact through methods. Let’s break down these core concepts:

  • Class — A blueprint for creating objects. It defines properties and behaviors.

  • Object — An instance of a class. It has a state (variables) and behavior (methods).

  • Method — A block of code that performs a specific task.

  • Instance Variable — A variable defined inside a class but outside any method. Each object has its own copy.

First Java Program

MyFirstJavaProgram.java

Java
public class MyFirstJavaProgram {
    /* This is my first Java program.
     * It will print 'Hello World' as output.
     */
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}
How to Run This Program
  1. Open Notepad and paste the code above.

  2. Save the file as MyFirstJavaProgram.java.

  3. Open Command Prompt and navigate to the file location.

  4. Compile: javac MyFirstJavaProgram.java

  5. Run: java MyFirstJavaProgram

Hello World
Java Syntax Rules

Rule

Description

Case Sensitivity

Java is case-sensitive. Hello ≠ hello.

Class Names

Start with uppercase. Example: StudentData.

Method Names

Start with lowercase. Example: printDetails().

File Name

Must match the public class name. Example: MyFirstJavaProgram.java.

main() Method

Every Java application starts from main() method.

Java Identifiers

Identifiers are names used for classes, methods, variables, etc.

  • Must begin with a letter (A–Z or a–z), underscore _, or dollar sign $.

  • Cannot begin with a digit.

  • Cannot use Java reserved keywords.

Tip
Examples: age, _value, $salary. Invalid: 123abc, -data
Java Modifiers

Modifiers define access levels and behavior.

  • Access Modifiers: public, private, protected, default

  • Non-access Modifiers: final, abstract, static, strictfp

Java Variables

Three types of variables:

  • Local Variables — Declared inside methods.

  • Instance Variables — Non-static, unique to each object.

  • Class Variables — Static, shared across all instances.

Java Arrays

Arrays store multiple values of the same type.

Java
int[] numbers = {1, 2, 3, 4};
Java Enums

Enums restrict a variable to predefined constants.

Java
enum Size { SMALL, MEDIUM, LARGE }

Size s = Size.MEDIUM;
System.out.println("Size: " + s);
Size: MEDIUM
Java Comments

Single-line:

Java
// This is a comment

Multi-line:

Java
/* This is
   a multi-line comment */
Reserved Keywords in Java

Java has 50+ reserved keywords. Examples include: class, public, static, void, if, else, switch, try, catch, finally, return, new, this, super, enum, interface, extends, implements.