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.
// 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 2026Breaking 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 useScannerdirectly instead ofjava.util.Scanner. - βΆ
3. Class Declaration β Mandatory. Every Java program must have at least one class. The
publicclass name must exactly match the filename. Example: classJavaIntromust be in a file namedJavaIntro.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.
Java is strictly case-sensitive. 'String' and 'string' are different. 'System' and 'system' are different. Always match the exact case.
The public class name must exactly match the .java filename. Class 'HelloWorld' must be in 'HelloWorld.java' β not 'helloworld.java' or 'Hello.java'.
Every standalone Java application must have 'public static void main(String[] args)'. This is the JVM's entry point β it must be exact.
Every Java statement ends with a semicolon (;). Missing a semicolon is the most common beginner mistake and causes a compile error.
Curly braces {} define code blocks β class bodies, method bodies, if/else blocks, loops. Every opening brace { must have a matching closing brace }.
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:
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
100Java 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.
- βΆ
β οΈ Note:
true,false, andnullare technically literals, not keywords β but they are also reserved and cannot be used as identifiers. - βΆ
β οΈ Note:
gotoandconstare 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, andAGEare three different identifiers. - βΆ
There is no maximum length limit, but keep them meaningful and concise.
π Naming Conventions (Best Practices)
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 ( // )
// 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 ( /* ... */ )
/*
* 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
/**
* 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;
}- βΆ
π‘ Tip: Run
javadoc ClassName.javain 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).
ποΈ 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.
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: trueJava 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
// 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 changeTypes of Variables in 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: 1var β 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.
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- βΆ
β οΈ
varonly works for local variables where the type can be inferred at compile time. You cannot usevarfor 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
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: 30Input β 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.
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.75Java 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
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.02. 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.
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 LOSTComplete 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.
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
Easy2. What is the output of: System.out.println("Java" + 1 + 2);
Medium3. What is the default value of an int instance variable and a boolean instance variable?
Easy4. Write the correct method signature for the Java main method and explain what each keyword means.
Easy5. What is the output and why? double d = 9.99; int i = (int) d; System.out.println(i);
Medium6. How many classes can a single .java file contain? How many can be public?
Medium7. What is the difference between System.out.print() and System.out.println()?
Easy8. Can you use 'var' for an instance variable in Java? Why or why not?
HardSummary β 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:
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 β