Understanding Java Syntax and Program Structure
Course: Core Java Training
Topic: Understanding Java Syntax and Program Structure
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
JustAcademy Homepage: Visit JustAcademy
1. Introduction to Java Syntax and Program Structure
Java is a high-level, class-based, object-oriented programming language used to develop desktop applications, web applications, enterprise software, Android applications, and backend services. To write effective Java programs, developers must understand Java syntax and the standard structure of a program.
Java syntax refers to the rules that define how Java code must be written. These rules specify how to declare variables, create classes and methods, write statements, use operators, and organize expressions.
Java program structure refers to the way source code is organized into elements such as package declarations, import statements, classes, fields, constructors, methods, and executable statements.
Understanding these fundamentals helps beginners write readable programs, prevent compilation errors, and build a strong foundation for advanced Core Java concepts.
Learning Objectives
- Understand the basic rules of Java syntax.
- Learn the standard structure of a Java program.
- Understand classes, methods, variables, and statements.
- Learn the purpose of the
main() method.
- Understand Java keywords, identifiers, comments, and naming conventions.
- Learn how braces, semicolons, and indentation are used.
- Identify common syntax errors and correct them.
- Write, compile, and execute simple Java programs.
2. Basic Structure of a Java Program
A Java source file can contain package declarations, import declarations, class or interface definitions, fields, constructors, and methods. The exact structure depends on the application's requirements.
Example of a Basic Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
Save this program in a file named HelloWorld.java.
Explanation of the Program
| Code Element |
Explanation |
public |
A keyword that makes the declared class accessible wherever the applicable access rules permit. |
class |
A keyword used to declare a class. |
HelloWorld |
The class name. |
main() |
The conventional entry-point method used to launch this basic Java application. |
String[] args |
An array of strings that can receive command-line arguments. |
System.out.println() |
Prints text to standard output and moves to a new line. |
{ } |
Curly braces define a block of code, such as a class or method body. |
; |
A semicolon terminates most Java statements. |
3. Understanding Java Classes
A class is a blueprint for creating objects. It can define data using fields and behavior using methods. Java applications organize most of their program logic into classes and other types.
Example
public class Student {
String name;
int age;
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
In this example, Student is a class. The variables name and age are instance fields, while displayDetails() is a method.
Important Points About Classes
- A class is declared using the
class keyword.
- The class body is enclosed in curly braces.
- A class can contain fields, constructors, methods, and nested types.
- Objects can be created from classes using the
new keyword when appropriate.
- By convention, class names use PascalCase, such as
StudentDetails.
4. Understanding the main() Method
For a traditional Java application launched through the standard Java launcher, the main() method is the conventional starting point for application execution.
Standard Main Method
public static void main(String[] args) {
System.out.println("Program started");
}
Explanation of Each Keyword
| Keyword or Element |
Meaning |
public |
Allows the launcher to access the method under the standard entry-point convention. |
static |
Allows the method to be invoked without creating an instance of the class. |
void |
Indicates that the method does not return a value. |
main |
The method name recognized as the conventional application entry point. |
String[] args |
Receives command-line arguments as an array of strings. |
Example Using Command-Line Arguments
public class Greeting {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("Hello, " + args[0]);
} else {
System.out.println("Hello, Guest");
}
}
}
Compile the program:
javac Greeting.java
Run it with an argument:
java Greeting Manish
Expected output:
Hello, Manish
If no argument is supplied, the program prints Hello, Guest.
5. Java Statements and Semicolons
A statement is an instruction that performs an action. Most ordinary Java statements end with a semicolon. A missing semicolon is a common beginner mistake.
Examples of Statements
int age = 25;
String name = "Aarav";
System.out.println(name);
System.out.println(age);
Each line above is a separate statement.
Statements That Do Not End With a Semicolon in the Usual Way
Declarations of classes and methods, as well as control structures such as if, for, and while, use blocks or headers rather than ending the entire structure with a semicolon.
if (age >= 18) {
System.out.println("Eligible");
}
In this example, the if condition is followed by a block. The statement inside the block ends with a semicolon.
6. Curly Braces and Code Blocks
Curly braces, { and }, define blocks in Java. They are used to enclose the body of classes, methods, constructors, loops, and conditional statements.
Example
public class NumberCheck {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("Positive number");
}
}
}
The outer braces define the class body, the next pair defines the main() method, and the inner pair defines the if block.
Why Braces Matter
- They group related statements into blocks.
- They define the boundaries of classes and methods.
- They help control the scope of local variables.
- Missing or mismatched braces can cause compilation errors.
- Consistent indentation makes nested blocks easier to understand.
7. Java Keywords and Reserved Words
Keywords are words with predefined meanings in the Java language. They are used to define program structures, data types, access rules, and control flow. Reserved keywords cannot be used as ordinary identifiers.
Common Java Keywords
| Keyword |
Purpose |
Example |
class |
Declares a class |
class Employee { } |
public |
Declares public accessibility |
public class Demo { } |
private |
Restricts member access to the declaring class |
private int age; |
static |
Declares a class-level member |
static int count; |
void |
Declares a method that returns no value |
void display() |
int |
Declares an integer primitive variable |
int score = 90; |
if |
Executes a block conditionally |
if (score >= 50) |
else |
Provides an alternative conditional branch |
else { } |
return |
Returns control from a method and may return a value |
return total; |
new |
Creates an object or array |
new Student() |
Java is case-sensitive. For example, class is a keyword, but Class is a different identifier and does not have the same meaning.
8. Identifiers and Naming Rules
An identifier is a name assigned to a program element, such as a variable, method, class, or package.
Rules for Identifiers
- An identifier may contain letters, digits, underscores, and dollar signs.
- An identifier cannot begin with a digit.
- Java identifiers are case-sensitive.
- Reserved keywords cannot be used as ordinary identifiers.
- Spaces are not permitted inside an identifier.
- Names should be meaningful and easy to understand.
Valid and Invalid Identifiers
| Identifier |
Valid? |
Reason |
studentName |
Yes |
Starts with a letter and follows identifier rules. |
age2 |
Yes |
Digits are allowed after the first character. |
_count |
Yes, with a caveat |
Valid under current Java identifier rules, but underscore-only names are restricted and a lone underscore cannot be used as an identifier in modern Java. |
$price |
Yes |
The dollar sign is permitted, though it is usually avoided in ordinary application naming. |
2score |
No |
An identifier cannot begin with a digit. |
student name |
No |
Spaces are not permitted. |
class |
No |
It is a reserved keyword. |
Recommended Naming Conventions
| Program Element |
Convention |
Example |
| Class |
PascalCase |
StudentDetails |
| Method |
camelCase |
calculateTotal() |
| Variable |
camelCase |
studentAge |
| Constant |
Uppercase words separated by underscores |
MAX_LIMIT |
| Package |
Usually lowercase |
com.example.app |
9. Variables and Data Types
Variables store data that a program can use or modify. Every variable has a type that determines the kind of value it can hold and the operations permitted on that value.
Example
public class VariableExample {
public static void main(String[] args) {
int age = 22;
double salary = 35000.50;
char grade = 'A';
boolean isActive = true;
String name = "Priya";
System.out.println(name);
System.out.println(age);
System.out.println(salary);
System.out.println(grade);
System.out.println(isActive);
}
}
Common Data Types
| Type |
Category |
Example |
byte |
Primitive integer |
byte level = 5; |
short |
Primitive integer |
short year = 2026; |
int |
Primitive integer |
int count = 100; |
long |
Primitive integer |
long population = 8000000L; |
float |
Primitive floating-point |
float rate = 2.5f; |
double |
Primitive floating-point |
double price = 99.99; |
char |
Primitive character |
char initial = 'P'; |
boolean |
Primitive logical value |
boolean passed = true; |
String |
Reference type |
String city = "Mumbai"; |
Primitive types store values of their respective primitive type. A variable of a reference type, such as String, holds a reference to an object or may contain null.
10. Java Comments
Comments are notes written in source code for developers. They help explain the purpose of code and are ignored as executable instructions by the compiler, except for documentation comments that tools can process.
10.1 Single-Line Comments
// This is a single-line comment
int age = 20;
10.2 Multi-Line Comments
/*
This comment spans
multiple lines.
*/
int total = 100;
10.3 Documentation Comments
/**
* Calculates the sum of two integers.
* @param a first number
* @param b second number
* @return sum of both numbers
*/
public int add(int a, int b) {
return a + b;
}
Documentation comments begin with /** and can be processed by the Javadoc tool to generate API documentation.
11. Import Statements and Package Declarations
Packages organize related Java types. Import statements allow source code to refer to types using their simple names instead of writing fully qualified names repeatedly.
Example With an Import
import java.util.ArrayList;
public class ListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Aarav");
names.add("Priya");
System.out.println(names);
}
}
The import statement allows the program to refer to ArrayList without writing java.util.ArrayList every time.
Example With a Package Declaration
package com.example;
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java packages");
}
}
In a conventional source file, the package declaration appears before import declarations and top-level type declarations. Save this example as Welcome.java within the appropriate package directory under the source root.
12. Methods and Method Syntax
A method is a named block of code that performs a task. Methods help divide a program into smaller, reusable units.
General Method Structure
accessModifier returnType methodName(parameters) {
// Method body
}
Example
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
int result = calculator.add(10, 20);
System.out.println("Sum: " + result);
}
}
Output:
Sum: 30
Method Components
- Access modifier: Determines where the method can be accessed.
- Return type: Specifies the type of value returned, or
void if no value is returned.
- Method name: Identifies the method.
- Parameters: Receive values supplied by the caller.
- Method body: Contains statements that perform the task.
13. Operators and Expressions in Java
Operators perform operations on values or variables. An expression combines values, variables, method calls, and operators to produce a result.
| Operator Category |
Operators |
Example |
| Arithmetic |
+ - * / % |
int sum = 10 + 5; |
| Comparison |
== != > < >= <= |
age >= 18 |
| Logical |
&& || ! |
age >= 18 && hasId |
| Assignment |
= += -= *= /= |
count += 1; |
| Increment and decrement |
++ -- |
count++; |
| Conditional |
? : |
String result = score >= 50 ? "Pass" : "Fail"; |
Example
public class OperatorExample {
public static void main(String[] args) {
int a = 15;
int b = 5;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println(a / b);
System.out.println(a % b);
}
}
14. Control Flow Syntax
Control flow statements determine which instructions run and how often they run. Common examples include conditional statements and loops.
14.1 if-else Statement
int marks = 75;
if (marks >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
14.2 for Loop
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
14.3 while Loop
int i = 1;
while (i <= 3) {
System.out.println(i);
i++;
}
14.4 switch Statement
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Other day");
}
Use braces and indentation consistently so the intended conditions and loop bodies are clear. Remember that a missing break in a traditional switch statement may cause execution to continue into subsequent cases.
15. Java Is Case-Sensitive
Java distinguishes uppercase and lowercase letters. Identifiers that differ only by capitalization are treated as different names.
Example
public class CaseExample {
public static void main(String[] args) {
int age = 20;
int Age = 25;
System.out.println(age);
System.out.println(Age);
}
}
Output:
20
25
Although both variables are valid, using names that differ only by capitalization can make programs confusing. Prefer consistent naming conventions.
16. Whitespace and Indentation
Whitespace includes spaces, tabs, and line breaks. Java generally ignores whitespace between tokens where it is permitted, but whitespace inside string literals is part of the string value.
Readable Formatting
public class FormatExample {
public static void main(String[] args) {
int number = 10;
if (number > 5) {
System.out.println("Number is greater than five");
}
}
}
Good indentation makes nested blocks easier to follow. Poor formatting may not cause a compilation error, but it makes code harder to read, debug, and maintain.
17. Common Java Syntax Errors
| Error |
Incorrect Code |
Correct Code |
| Missing semicolon |
int age = 20 |
int age = 20; |
| Incorrect capitalization |
system.out.println("Hi"); |
System.out.println("Hi"); |
| Missing quotation mark |
String name = "Aarav; |
String name = "Aarav"; |
| Unmatched braces |
if (x > 0) { ... |
Close the block with a matching }. |
| Keyword used as an identifier |
int class = 5; |
int classCount = 5; |
| Public class/file mismatch |
Public class Demo in Example.java |
Save it as Demo.java. |
| Incorrect string quotes |
char grade = "A"; |
char grade = 'A'; |
Tips for Fixing Syntax Errors
- Read the complete compiler error message.
- Check the reported line and the lines immediately before it.
- Verify semicolons, parentheses, quotation marks, and braces.
- Check capitalization of class names, variables, and Java library references.
- Compile the program again after making corrections.
- Fix the first error first, because one syntax error can trigger several follow-up messages.
18. Best Practices for Writing Java Programs
- Use meaningful class, method, and variable names.
- Follow standard Java naming conventions.
- Keep methods focused on one clear task.
- Indent nested blocks consistently.
- Use comments to explain intent when the code is not self-explanatory.
- Avoid unnecessary comments that merely repeat the code.
- Use appropriate access modifiers to protect class data.
- Initialize variables appropriately and use types that suit the data.
- Compile and test programs frequently.
- Break large problems into smaller classes and methods.
- Use an IDE or editor that supports syntax highlighting and error detection.
- Follow a consistent formatting style across the project.
19. Practical Exercise: Create a Student Result Program
This exercise combines Java classes, variables, methods, conditional statements, and output statements.
Program
public class StudentResult {
public static void main(String[] args) {
String studentName = "Priya";
int marks = 82;
System.out.println("Student: " + studentName);
System.out.println("Marks: " + marks);
if (marks >= 50) {
System.out.println("Result: Pass");
} else {
System.out.println("Result: Fail");
}
}
}
Expected Output
Student: Priya
Marks: 82
Result: Pass
Instructions
- Save the code as
StudentResult.java.
- Compile it using
javac StudentResult.java.
- Run it using
java StudentResult.
- Change the student's name and marks.
- Test the program with marks below 50.
- Introduce a missing semicolon, compile again, and correct the error.
20. Practice Questions
- What is Java syntax, and why is it important?
- What are the main components of a basic Java program?
- What is the purpose of the
main() method?
- Why do most Java statements end with a semicolon?
- What is the difference between a keyword and an identifier?
- What naming conventions are recommended for classes and methods?
- What is the purpose of curly braces?
- How do single-line and multi-line comments differ?
- What is the difference between a variable and a method?
- How can you compile and run a Java program from the command line?
21. Interview Questions and Answers
Q1. What is Java syntax?
Java syntax is the set of rules that determines how Java source code must be written so the compiler can understand it.
Q2. What is the basic structure of a Java program?
A typical Java program contains a class declaration and methods. A simple application launched with the standard Java launcher commonly uses a public static void main(String[] args) method as its entry point.
Q3. Why is the main method static?
The traditional launcher can invoke the entry-point method without first creating an instance of the class, which is why the conventional main method is declared static.
Q4. What is a Java keyword?
A keyword is a reserved word with a predefined meaning in Java, such as class, public, static, or return.
Q5. What is an identifier?
An identifier is a name assigned to a program element, such as a class, variable, method, or package.
Q6. Why is Java case-sensitive?
Java treats uppercase and lowercase letters as different characters in identifiers. Therefore, name and Name refer to different identifiers.
Q7. What is the purpose of a semicolon?
A semicolon terminates most Java statements and helps the compiler identify the end of each statement.
Q8. What are comments in Java?
Comments are non-executable notes in source code. Java supports single-line comments, multi-line comments, and documentation comments.
Q9. What is the difference between a class and a method?
A class groups data and behavior into a type. A method defines a particular operation or behavior within a class or another permitted context.
Q10. What is a syntax error?
A syntax error occurs when code violates Java's language grammar, such as by using an invalid statement structure or omitting a required delimiter.
Q11. What is the difference between a primitive type and a reference type?
A primitive variable stores a value of a primitive type, such as int or boolean. A reference variable holds a reference to an object or may contain null.
Q12. What is the purpose of an import statement?
An import statement allows source code to refer to types using their simple names rather than repeatedly writing their fully qualified names.
22. Quick Revision Checklist
- Java syntax defines the rules for writing valid Java code.
- A class is declared using the
class keyword.
- Curly braces define class, method, and control-flow blocks.
- Most Java statements end with a semicolon.
- The conventional application entry point is
public static void main(String[] args).
- Keywords have predefined meanings and cannot be used as ordinary identifiers.
- Identifiers are case-sensitive and must follow Java naming rules.
- Variables store values or references, depending on their types.
- Methods organize program behavior into reusable units.
- Comments improve understanding and maintainability.
- Package and import declarations help organize and reference types.
- Consistent indentation and naming improve code readability.
- Compilation helps identify syntax and type errors before execution.
23. Conclusion
Understanding Java syntax and program structure is an essential first step in Core Java programming. By learning classes, methods, variables, keywords, identifiers, statements, comments, and control-flow structures, beginners can create programs that are valid, readable, and easier to maintain.
Regular coding practice is the best way to become comfortable with Java syntax. Start with simple programs, compile them frequently, understand compiler messages, and gradually move toward object-oriented programming, exception handling, collections, and other advanced Java topics.
Continue your learning journey with the Core Java Training course at JustAcademy. You can also register for a course demo or visit the JustAcademy homepage for more information.