β˜• Java

Java Introduction β€” Program Structure & Syntax

A complete beginner's guide to Java syntax, program structure, tokens, identifiers, keywords, comments, data types, and variables β€” with working code examples.

πŸ“…

Last Updated

March 2026

⏱️

Read Time

15 min

🎯

Level

Beginner

Java Introduction β€” Overview

In the previous chapter, we learned what Java is, its history, features, and the JDK/JRE/JVM architecture. Now it is time to actually start writing Java code. This chapter covers the foundational concepts every Java developer must know before writing their first real program.

Before writing any Java program, you need to understand the building blocks of Java code β€” how a Java file is structured, what syntax rules Java follows, what tokens and identifiers are, and how Java handles different types of data. These fundamentals apply to every single Java program you will ever write.

  • β–Ά

    What you will learn: Java program structure, syntax rules, tokens, keywords, identifiers, comments, data types, variables, and how to take user input.

Structure of a Java Program

Every Java program follows a strict structure. Unlike Python or JavaScript, Java is highly structured β€” and that structure is what makes Java programs reliable and maintainable. Let us look at a complete Java program and break it down piece by piece.

β˜• JavaJavaIntro.java
// 1. Package Declaration (optional)
package com.techsustainify.intro;

// 2. Import Statements (optional)
import java.util.Scanner;

// 3. Class Declaration (mandatory)
public class JavaIntro {

    // 4. Instance Variables (optional)
    String courseName = "Java Tutorial";

    // 5. Main Method β€” Entry Point (mandatory for standalone app)
    public static void main(String[] args) {

        // 6. Local Variables & Statements
        int year = 2026;
        System.out.println("Welcome to Java " + year);
    }
}

Output

Welcome to Java 2026

Breaking Down the Java Program Structure

  • β–Ά

    1. Package Declaration β€” Optional but recommended. Groups related classes together. Example: package com.company.project;. Must be the first statement in the file (before imports).

  • β–Ά

    2. Import Statements β€” Optional. Brings in classes from other packages so you can use them without writing the full path. Example: import java.util.Scanner; lets you use Scanner directly instead of java.util.Scanner.

  • β–Ά

    3. Class Declaration β€” Mandatory. Every Java program must have at least one class. The public class name must exactly match the filename. Example: class JavaIntro must be in a file named JavaIntro.java.

  • β–Ά

    4. Instance Variables β€” Optional. Variables declared inside the class but outside any method. They represent the state/properties of the class.

  • β–Ά

    5. main() Method β€” Mandatory for standalone applications. This is where JVM starts executing your program. Exact signature: public static void main(String[] args).

  • β–Ά

    6. Statements & Expressions β€” The actual code logic β€” variable declarations, method calls, control flow, etc. Every statement ends with a semicolon ;.

Java Syntax Rules β€” What You Must Know

Java has strict syntax rules. Violating any of these causes a compilation error β€” your program will not compile until you fix the error. Learning these rules early saves hours of debugging.

πŸ”€
Case Sensitive

Java is strictly case-sensitive. 'String' and 'string' are different. 'System' and 'system' are different. Always match the exact case.

πŸ“„
File Name = Class Name

The public class name must exactly match the .java filename. Class 'HelloWorld' must be in 'HelloWorld.java' β€” not 'helloworld.java' or 'Hello.java'.

🎯
main() is Mandatory

Every standalone Java application must have 'public static void main(String[] args)'. This is the JVM's entry point β€” it must be exact.

;
Semicolon Required

Every Java statement ends with a semicolon (;). Missing a semicolon is the most common beginner mistake and causes a compile error.

{}
Curly Braces for Blocks

Curly braces {} define code blocks β€” class bodies, method bodies, if/else blocks, loops. Every opening brace { must have a matching closing brace }.

πŸ“¦
One Public Class Per File

A .java file can contain multiple classes, but only ONE class can be public. The public class must match the filename.

Good practice: Always use an IDE like IntelliJ IDEA or Eclipse β€” they highlight syntax errors in real time so you catch mistakes as you type.

Java Tokens β€” The Smallest Units of Java Code

When the Java Compiler reads your source code, it first breaks it down into the smallest individual units called tokens. A token is the smallest meaningful element in a Java program. There are 5 types of tokens in Java:

Token TypeDescriptionExamples
KeywordsReserved words with predefined meaning in Java. Cannot be used as identifiers.int, class, public, static, void, if, else, for, while, return, new, true, false
IdentifiersNames given to variables, methods, classes, and packages by the programmer.main, args, System, HelloWorld, myVariable, calculateTotal
LiteralsFixed values directly written in code.42, 3.14, 'A', "Hello", true, false, null
OperatorsSymbols that perform operations on variables and values.+ - * / % == != > < && || ! = += -= ++ --
Separators / PunctuatorsSymbols used to separate code elements.; , . ( ) { } [ ]
β˜• JavaTokens Example
public class TokensDemo {
    public static void main(String[] args) {
        int marks = 95;              // int=keyword, marks=identifier, 95=literal
        boolean passed = true;        // boolean=keyword, passed=identifier, true=literal
        int total = marks + 5;        // +=operator, total & marks=identifiers
        System.out.println(total);    // .=separator, ()=separators
    }
}

Output

100

Java Keywords β€” Reserved Words

Keywords (also called reserved words) are words that have a special, predefined meaning in Java. You cannot use them as variable names, class names, or method names. Java has 67 reserved keywords as of Java 21.

CategoryKeywords
Data Typesbyte, short, int, long, float, double, char, boolean
Access Modifierspublic, private, protected
Class & Objectclass, interface, enum, extends, implements, new, this, super, instanceof
Control Flowif, else, switch, case, default, break, continue, return
Loopsfor, while, do
Exception Handlingtry, catch, finally, throw, throws
Modifiersstatic, final, abstract, synchronized, volatile, transient, native
Package & Importpackage, import
Othervoid, null, true, false, var (since Java 10), record (since Java 16), sealed (since Java 17)
  • β–Ά

    ⚠️ Note: true, false, and null are technically literals, not keywords β€” but they are also reserved and cannot be used as identifiers.

  • β–Ά

    ⚠️ Note: goto and const are reserved in Java but currently unused. They exist to prevent programmers from using them as identifiers.

Java Identifiers β€” Naming Rules & Conventions

An identifier is a name you give to a variable, method, class, or package. Java has strict rules about what makes a valid identifier, plus widely followed naming conventions that make code readable.

βœ… Rules for Valid Identifiers (Mandatory)

  • β–Ά

    Must start with a letter (A–Z or a–z), an underscore (_), or a dollar sign ($). Cannot start with a digit.

  • β–Ά

    After the first character, can contain letters, digits (0–9), underscores, and dollar signs.

  • β–Ά

    Cannot be a Java keyword (like int, class, public).

  • β–Ά

    Java identifiers are case-sensitive. age, Age, and AGE are three different identifiers.

  • β–Ά

    There is no maximum length limit, but keep them meaningful and concise.

IdentifierValid?Reason
myVariableβœ… ValidStarts with a letter, contains only letters
_countβœ… ValidUnderscore is allowed as the first character
$priceβœ… ValidDollar sign is allowed as the first character
total99βœ… ValidDigits allowed after the first character
2marks❌ InvalidCannot start with a digit
my-name❌ InvalidHyphen (-) is not allowed
class❌ InvalidReserved keyword β€” cannot be used as identifier
my variable❌ InvalidSpaces are not allowed in identifiers

πŸ“ Naming Conventions (Best Practices)

ElementConventionExample
VariablecamelCase β€” start lowercasestudentName, totalMarks, isLoggedIn
MethodcamelCase β€” start lowercase, verbcalculateTotal(), getUserName(), printData()
ClassPascalCase β€” start uppercaseHelloWorld, StudentManager, BankAccount
ConstantUPPER_SNAKE_CASE β€” all capsMAX_SIZE, PI_VALUE, DEFAULT_TIMEOUT
Packageall lowercase, dot-separatedcom.techsustainify.java, org.example.utils
InterfacePascalCase β€” adjective or nounRunnable, Serializable, Comparable

Java Comments β€” Types and Usage

Comments are lines in your code that the Java compiler completely ignores. They exist purely for human readers β€” to explain what the code does, why a decision was made, or to temporarily disable code during debugging. Writing good comments is a professional habit.

Java supports three types of comments:

1. Single-Line Comment ( // )

β˜• JavaSingle-Line Comment
// This is a single-line comment
int age = 21;  // age of the student

// The line below is temporarily disabled:
// System.out.println("Debug info");

2. Multi-Line Comment ( /* ... */ )

β˜• JavaMulti-Line Comment
/*
 * This method calculates the area of a rectangle.
 * Formula: Area = length Γ— breadth
 * Both parameters must be positive numbers.
 */
int area = length * breadth;

3. Documentation Comment ( /** ... */ ) β€” Javadoc

β˜• JavaJavadoc Comment
/**
 * Calculates the sum of two integers.
 *
 * @param a  the first integer
 * @param b  the second integer
 * @return   the sum of a and b
 * @author   Tech Sustainify
 * @version  1.0
 */
public int add(int a, int b) {
    return a + b;
}
Comment TypeSyntaxBest Used For
Single-Line// commentShort inline explanations, disabling a single line
Multi-Line/* comment */Explaining a block of code, temporarily disabling multiple lines
Javadoc/** comment */Official API documentation β€” classes, methods, parameters
  • β–Ά

    πŸ’‘ Tip: Run javadoc ClassName.java in the terminal to auto-generate HTML documentation from your Javadoc comments β€” the same way the official Java API docs are generated.

Java Data Types β€” Primitive & Non-Primitive

In Java, every variable has a data type that defines what kind of value it can hold and how much memory it occupies. Java is a strongly typed language β€” you must declare the type of every variable before using it. Java has two categories of data types:

πŸ”’ Primitive Data Types (8 Types)

Primitive types are the most basic data types built into Java. They store simple values directly in memory. Java has exactly 8 primitive data types β€” and their sizes are fixed regardless of the platform (this is part of Java's portability).

Data TypeSizeDefault ValueRangeExample
byte1 byte (8 bits)0-128 to 127byte b = 100;
short2 bytes (16 bits)0-32,768 to 32,767short s = 5000;
int4 bytes (32 bits)0-2,147,483,648 to 2,147,483,647int age = 21;
long8 bytes (64 bits)0L-9.2 Γ— 10¹⁸ to 9.2 Γ— 10¹⁸long population = 8000000000L;
float4 bytes (32 bits)0.0f~3.4 Γ— 10⁻³⁸ to 3.4 Γ— 10³⁸float price = 9.99f;
double8 bytes (64 bits)0.0d~1.7 Γ— 10⁻³⁰⁸ to 1.7 Γ— 10³⁰⁸double pi = 3.14159265;
char2 bytes (16 bits)'\u0000'0 to 65,535 (Unicode)char grade = 'A';
boolean1 bit (JVM-dependent)falsetrue or false onlyboolean passed = true;

πŸ›οΈ Non-Primitive Data Types (Reference Types)

Non-primitive (reference) types do not store the value directly β€” they store a reference (memory address) to where the data is stored in the heap. All non-primitive types are derived from the Object class.

TypeDescriptionExample
StringSequence of characters. Most commonly used type.String name = "Java";
ArrayFixed-size collection of same-type elements.int[] marks = {90, 85, 92};
ClassBlueprint for creating objects with state and behavior.Student s = new Student();
InterfaceAbstract type that defines a contract for classes.Runnable r = new Thread();
EnumSpecial type with a fixed set of named constants.Day d = Day.MONDAY;
β˜• JavaDataTypes.java
public class DataTypes {
    public static void main(String[] args) {

        // Primitive Types
        byte  b  = 120;
        short s  = 32000;
        int   i  = 2026;
        long  l  = 9876543210L;   // suffix 'L' for long
        float f  = 3.14f;          // suffix 'f' for float
        double d = 3.141592653;
        char  c  = 'J';
        boolean flag = true;

        // Non-Primitive Type
        String language = "Java";

        System.out.println("Language: " + language);
        System.out.println("Year: " + i);
        System.out.println("PI: " + d);
        System.out.println("Grade: " + c);
        System.out.println("Active: " + flag);
    }
}

Output

Language: Java Year: 2026 PI: 3.141592653 Grade: J Active: true

Java Variables β€” Declaration, Initialization & Scope

A variable is a named container in memory that stores a value. Every variable in Java has a name (identifier), a data type, and a value. You must declare a variable before using it.

Variable Declaration and Initialization

β˜• JavaVariable Syntax
// Syntax:  dataType variableName;
//          dataType variableName = value;

int age;              // Declaration only
age = 21;             // Initialization (assigning value later)

int marks = 95;       // Declaration + Initialization together
String name = "Rahul"; // String variable
final double PI = 3.14159;  // Constant β€” value cannot change

Types of Variables in Java

Variable TypeWhere DeclaredScope / LifetimeExample
Local VariableInside a method or blockOnly within that method/block β€” destroyed after method endsint x = 10; inside main()
Instance VariableInside class, outside methodsAs long as the object exists β€” each object has its own copyString name; inside a class
Static (Class) VariableInside class with 'static' keywordAs long as the class is loaded β€” shared across all objectsstatic int count = 0;
Parameter VariableIn method signatureOnly during method executionvoid show(int age) β€” age is a parameter
β˜• JavaVariableTypes.java
public class VariableTypes {

    // 2. Instance Variable
    String studentName = "Rahul";

    // 3. Static (Class) Variable
    static int totalStudents = 0;

    public static void main(String[] args) {

        // 1. Local Variable
        int marks = 95;
        totalStudents++;

        System.out.println("Marks: " + marks);
        System.out.println("Total Students: " + totalStudents);
    }
}

Output

Marks: 95 Total Students: 1

var β€” Type Inference (Java 10+)

Since Java 10, you can use var for local variables β€” the compiler automatically infers the type from the assigned value. This makes code shorter without sacrificing type safety.

β˜• Javavar Keyword (Java 10+)
var name   = "Java";     // inferred as String
var year   = 2026;        // inferred as int
var price  = 99.99;       // inferred as double
var letter = 'J';         // inferred as char

System.out.println(name + " " + year);  // Java 2026
  • β–Ά

    ⚠️ var only works for local variables where the type can be inferred at compile time. You cannot use var for instance variables, method parameters, or return types.

Java Input and Output β€” System.out and Scanner

Every useful program needs to display output to the user and receive input from the user. Java provides built-in mechanisms for both.

Output β€” System.out

MethodDescriptionExample
System.out.println()Prints text and moves to a new lineSystem.out.println("Hello"); β†’ Hello↡
System.out.print()Prints text WITHOUT moving to a new lineSystem.out.print("Hi "); β†’ Hi (cursor stays)
System.out.printf()Formatted output β€” like C's printf()System.out.printf("%.2f", 3.14159); β†’ 3.14
β˜• JavaOutput Demo
public class OutputDemo {
    public static void main(String[] args) {
        System.out.println("Line 1");
        System.out.print("Line ");
        System.out.println("2");
        System.out.printf("PI = %.4f%n", 3.141592653);
        System.out.println("Sum: " + (10 + 20));
    }
}

Output

Line 1 Line 2 PI = 3.1416 Sum: 30

Input β€” Scanner Class

To take input from the user (keyboard), Java uses the Scanner class from the java.util package. You must import it before using it.

β˜• JavaScanner Input Demo
import java.util.Scanner;   // Step 1: Import Scanner

public class InputDemo {
    public static void main(String[] args) {

        // Step 2: Create Scanner object
        Scanner sc = new Scanner(System.in);

        // Step 3: Prompt and read input
        System.out.print("Enter your name: ");
        String name = sc.nextLine();   // reads full line

        System.out.print("Enter your age: ");
        int age = sc.nextInt();         // reads integer

        System.out.print("Enter your GPA: ");
        double gpa = sc.nextDouble();   // reads double

        // Step 4: Display the result
        System.out.println("Name: " + name);
        System.out.println("Age: "  + age);
        System.out.println("GPA: "  + gpa);

        sc.close();  // Step 5: Always close the scanner
    }
}

Output

Enter your name: Rahul Enter your age: 21 Enter your GPA: 8.75 Name: Rahul Age: 21 GPA: 8.75
Scanner MethodReadsExample
nextInt()Integer value (int)int n = sc.nextInt();
nextLong()Long integer valuelong l = sc.nextLong();
nextFloat()Float decimal valuefloat f = sc.nextFloat();
nextDouble()Double decimal valuedouble d = sc.nextDouble();
next()Single word (stops at whitespace)String word = sc.next();
nextLine()Entire line including spacesString line = sc.nextLine();
nextBoolean()Boolean value (true/false)boolean b = sc.nextBoolean();

Java Type Casting β€” Widening & Narrowing

Type casting is the process of converting a value from one data type to another. Java supports two types of casting:

1. Widening Casting (Automatic / Implicit)

Converting a smaller data type to a larger one. Java does this automatically β€” no data is lost. Order: byte β†’ short β†’ int β†’ long β†’ float β†’ double

β˜• JavaWidening Casting
int    myInt    = 100;
long   myLong   = myInt;     // int automatically widens to long
float  myFloat  = myLong;    // long automatically widens to float
double myDouble = myFloat;   // float automatically widens to double

System.out.println(myInt);     // 100
System.out.println(myDouble);  // 100.0

2. Narrowing Casting (Manual / Explicit)

Converting a larger data type to a smaller one. Must be done manually by placing the target type in parentheses. Data loss may occur β€” use with caution.

β˜• JavaNarrowing Casting
double myDouble = 9.78;
int    myInt    = (int) myDouble;  // manually cast double to int

System.out.println(myDouble);  // 9.78
System.out.println(myInt);     // 9  ← decimal part is LOST

Complete Java Program β€” Putting It All Together

Let us write one complete program that uses everything we learned in this chapter β€” variables, data types, comments, input, output, and type casting β€” all in a single example.

β˜• JavaStudentReport.java
import java.util.Scanner;

/**
 * StudentReport.java
 * Demonstrates: variables, data types, input, output, and type casting
 */
public class StudentReport {

    // Static variable β€” shared across all instances
    static String schoolName = "Tech Sustainify Academy";

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        // ---- Input Section ----
        System.out.print("Enter student name  : ");
        String name = sc.nextLine();

        System.out.print("Enter marks (0-100) : ");
        double marks = sc.nextDouble();

        // ---- Processing ----
        int roundedMarks = (int) marks;   // Narrowing cast
        char grade;

        if      (marks >= 90) grade = 'A';
        else if (marks >= 75) grade = 'B';
        else if (marks >= 60) grade = 'C';
        else                  grade = 'F';

        boolean passed = marks >= 40;

        // ---- Output Section ----
        System.out.println("\n====== Student Report ======");
        System.out.println("School  : " + schoolName);
        System.out.println("Student : " + name);
        System.out.printf ("Marks   : %.1f (Rounded: %d)%n", marks, roundedMarks);
        System.out.println("Grade   : " + grade);
        System.out.println("Result  : " + (passed ? "PASS" : "FAIL"));
        System.out.println("============================");

        sc.close();
    }
}

Output

Enter student name : Rahul Sharma Enter marks (0-100) : 87.5 ====== Student Report ====== School : Tech Sustainify Academy Student : Rahul Sharma Marks : 87.5 (Rounded: 87) Grade : B Result : PASS ============================

Practice This Code β€” Live Editor

Java Intro β€” Interview Questions

These are commonly asked Java interview questions related to the basics covered in this chapter β€” syntax, data types, variables, and identifiers.

Practice Questions β€” Test Your Knowledge

Test your understanding of Java Intro concepts. Answer each question yourself before revealing the answer.

1. Which of the following are valid Java identifiers? _myVar, 3count, $price, my-value, public

Easy

2. What is the output of: System.out.println("Java" + 1 + 2);

Medium

3. What is the default value of an int instance variable and a boolean instance variable?

Easy

4. Write the correct method signature for the Java main method and explain what each keyword means.

Easy

5. What is the output and why? double d = 9.99; int i = (int) d; System.out.println(i);

Medium

6. How many classes can a single .java file contain? How many can be public?

Medium

7. What is the difference between System.out.print() and System.out.println()?

Easy

8. Can you use 'var' for an instance variable in Java? Why or why not?

Hard

Summary β€” What You Learned in Java Intro

You have covered the foundational building blocks of every Java program. Here is a quick recap of what was covered in this chapter:

TopicKey Takeaway
Java Program StructurePackage β†’ Imports β†’ Class β†’ Variables β†’ main() β†’ Statements
Syntax RulesCase-sensitive, filename = class name, semicolons required, braces must balance
TokensKeywords, Identifiers, Literals, Operators, Separators β€” smallest units the compiler reads
Keywords67 reserved words β€” cannot be used as identifiers (int, class, static, void...)
IdentifiersMust start with letter/_/$, no spaces, no hyphens, not a keyword
Comments// single-line, /* */ multi-line, /** */ Javadoc
Primitive Types8 types: byte, short, int, long, float, double, char, boolean
Non-Primitive TypesString, Arrays, Classes, Interfaces, Enums β€” store references
VariablesLocal (method scope), Instance (object scope), Static (class scope)
Type CastingWidening (auto, safe), Narrowing (manual, may lose data)
OutputSystem.out.println(), print(), printf()
InputScanner class β€” nextInt(), nextDouble(), nextLine(), etc.

The next step is understanding Java Operators β€” arithmetic, relational, logical, bitwise, and assignment operators β€” which are the mathematical and logical tools that power every Java program's logic. Continue to the next chapter: Java Operators β†’

Frequently Asked Questions (FAQ) β€” Java Introduction