Skip to content

Java Basic Syntax

Welcome to the fundamentals of Java programming! A Java program is essentially a collection of objects that interact by calling each other’s methods. Before diving deep, let’s understand the basic building blocks and syntax rules.

  • Object: An instance of a class, having state (data/fields) and behavior (methods). Example: A specific Dog object might have states like color="Brown", name="Buddy" and behaviors like bark(), fetch().
  • Class: A blueprint or template for creating objects. It defines the common properties (fields) and actions (methods) that all objects of that type will have. Example: The Dog class defines that all dogs have a name and can bark.
  • Method: A block of code within a class that performs a specific action or behavior. Methods manipulate data and execute logic.
  • Instance Variables (Fields): Variables declared within a class but outside any method. Each object (instance) of the class gets its own copy of these variables, defining its unique state.

Let’s start with the classic “Hello, World!” example. This simple program demonstrates the basic structure.

/**
* This is a simple Java program.
* It demonstrates the basic structure and prints "Hello, World!".
*/
public class HelloWorld {
// The main method is the entry point of the application.
public static void main(String[] args) {
// Print the text "Hello, World!" to the console.
System.out.println("Hello, World!");
}
} // End of HelloWorld class
  • public class HelloWorld: Declares a class named HelloWorld. The public keyword means this class is accessible from anywhere.
  • public static void main(String[] args): This is the main method. Every Java application needs one.
    • public: Accessible from anywhere.
    • static: Means the method belongs to the HelloWorld class itself, not to any specific object instance. It can be run without creating an object of the class.
    • void: Indicates that this method does not return any value.
    • main: This specific name tells the Java Virtual Machine (JVM) where to start execution.
    • String[] args: Declares a parameter named args, which is an array of String objects. This array holds any command-line arguments passed to the program when it runs.
  • System.out.println("Hello, World!");: This line does the work.
    • System: A built-in Java class from the java.lang package.
    • out: A static field within the System class, representing the standard output stream (usually the console).
    • println(): A method of the out object that prints the provided text (the argument) to the console, followed by a newline.
  • // and /** ... */: These are comments. The compiler ignores them. They are used to explain the code.
  1. Save: Save the code in a text file named exactly HelloWorld.java. The filename must match the public class name, including capitalization.
  2. Compile: Open a terminal or command prompt, navigate to the directory where you saved the file, and type:
  3. javac HelloWorld.java
  4. This command invokes the Java compiler (javac). If there are no errors, it will create a bytecode file named HelloWorld.class in the same directory.
  5. Run: In the same terminal, type:
  6. java HelloWorld
  7. This command starts the Java Virtual Machine (JVM) and tells it to run the HelloWorld class (specifically, its main method). Do not include the .class extension here.

Expected Output:

Hello, World!

Keep these fundamental rules in mind:

  • Case Sensitivity: Java is case-sensitive. myVariable and myvariable are different identifiers.
  • Class Names: By convention, class names start with an uppercase letter and use CamelCase (e.g., MyFirstClass, String, ArrayList).
  • Method Names: By convention, method names start with a lowercase letter and use camelCase (e.g., calculateTotal(), getUserName()).
  • File Names: The name of the .java file must exactly match the name of the public class declared within it.
  • main Method: Every Java application must contain a public static void main(String[] args) method as its starting point.
  • Statements: Each statement typically ends with a semicolon (;).
  • Code Blocks: Code blocks are defined by curly braces {}. They group statements together (e.g., within classes, methods, loops, conditional statements).
  • Whitespace: Java ignores extra whitespace (spaces, tabs, newlines) between tokens, but proper indentation makes code readable.

Identifiers are names given to Java elements like classes, methods, variables, packages, etc.

Rules for Identifiers:

  • Must start with a letter (a-z, A-Z), an underscore (_), or a dollar sign ($).
  • Subsequent characters can be letters, digits (0-9), underscores, or dollar signs.
  • Cannot be a Java keyword (reserved word like class, int, public, if, etc.).
  • Cannot be true, false, or null.
  • Are case-sensitive.
  • Can be of any length theoretically, but keep them meaningful and reasonably concise.

Examples:

  • Valid: age, userName, _balance, $amount, MAX_VALUE, calculateInterest
  • Invalid: 1stName (starts with digit), user name (contains space), class (keyword), max-value (contains hyphen)

Modifiers are keywords that you add to definitions (like classes, methods, variables) to change their meaning or accessibility.

  • Access Modifiers: Control visibility.
    • public: Accessible from anywhere.
    • private: Accessible only within the same class.
    • protected: Accessible within the same class, same package, and subclasses.
    • (Default/Package-Private): (No keyword) Accessible only within the same package.
  • Non-Access Modifiers: Provide other characteristics.
    • static: Belongs to the class, not an instance.
    • final: Value cannot be changed (variables), method cannot be overridden, class cannot be subclassed.
    • abstract: Class cannot be instantiated, method has no implementation (must be overridden).
    • synchronized, volatile: Related to multithreading (covered later).

We’ll explore these in more detail in later chapters.

Variables are containers for storing data values. In Java, there are three main types based on where they are declared:

  • Local Variables: Declared inside a method, constructor, or block. They exist only within that scope.
  • Instance Variables (Non-Static Fields): Declared inside a class but outside any method. Each object instance has its own copy.
  • Class Variables (Static Fields): Declared inside a class, outside any method, using the static keyword. There is only one copy shared by all instances of the class.

These are covered in detail in the ‘Java Variable Types’ chapter.

Arrays are objects that store a fixed-size sequence of elements of the same type. We’ll cover how to declare, create, and initialize arrays in a dedicated chapter.

Introduced in Java 5, an enum is a special type that defines a set of named constants. Enums restrict a variable to hold only one of these predefined constant values, improving type safety and code clarity.

// Define an enum for T-shirt sizes
enum Size {
SMALL, MEDIUM, LARGE, EXTRA_LARGE
}
public class TshirtOrder {
Size shirtSize; // Variable can only hold one of the Size constants
public static void main(String[] args) {
TshirtOrder order = new TshirtOrder();
order.shirtSize = Size.MEDIUM; // Assigning an enum constant
System.out.println("Selected size: " + order.shirtSize);
// Enums are great in switch statements
switch (order.shirtSize) {
case SMALL:
System.out.println("Ordering a small shirt.");
break;
case MEDIUM:
System.out.println("Ordering a medium shirt.");
break;
// ... other cases
default:
System.out.println("Unknown size selected.");
}
}
}

Output:

Selected size: MEDIUM
Ordering a medium shirt.

Keywords are reserved words with predefined meanings in Java. You cannot use them as identifiers (names for variables, classes, methods, etc.).

abstractassertbooleanbreak
bytecasecatchchar
classconst*continuedefault
dodoubleelseenum
extendsfinalfinallyfloat
forgoto*ifimplements
importinstanceofintinterface
longnativenewpackage
privateprotectedpublicreturn
shortstaticstrictfpsuper
switchsynchronizedthisthrow
throwstransienttryvoid
volatilewhile_ (underscore, restricted since Java 9)

Note: const and goto are reserved but not currently used. true, false, and null are literals, not keywords, but cannot be used as identifiers. var (since Java 10) is a reserved type name, not strictly a keyword.

Comments are used to explain code and are ignored by the compiler. Java supports three types:

  • Single-line comment: Starts with // and continues to the end of the line.
  • Multi-line comment: Starts with /* and ends with */. Can span multiple lines.
  • Javadoc comment: Starts with /** and ends with */. Similar to multi-line but used specifically for generating API documentation using the javadoc tool.
// This is a single-line comment.
int count = 0; // Initialize count
/*
This is a multi-line comment.
It can span several lines.
*/
/**
* This is a Javadoc comment for the calculate method.
* It explains what the method does.
* @param x The first operand.
* @param y The second operand.
* @return The sum of x and y.
*/
public int calculate(int x, int y) {
return x + y;
}

Now that you have a grasp of the basic syntax and structure, the next chapter, ‘Java Object & Classes’, will delve deeper into the core concepts of object-oriented programming in Java, explaining how to define your own classes and create objects from them.