Nearby lessons

10 of 125

Java - Basic Syntax

📌 What You Will Learn
  • The small building blocks of Java: tokens
  • All 8 primitive data types with their ranges
  • Type casting — implicit and explicit
  • Control statements: if, switch, loops
  • Arrays — single, double and jagged
  • Variable length arguments (var-args)

Basic Syntax is a core concept of the Java language. This lesson explains The Structure of a Java Program, Tokens — The Smallest Building Blocks and More About Tokens — Lexeme and Token with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

The Structure of a Java Program

Every well-written Java file follows a fixed order of sections. Memorise this format:

SectionPurpose
Comment SectionDescribes the program: author, objective, project details.
Package SectionPuts the classes into a named package (must be the first statement).
Import SectionBrings in ready-made classes from other packages.
Classes/Interfaces SectionRepresents the real-world entities (Employee, Student, Account...).
Main Class SectionContains main() — the starting point of the application.
Example01
JCode Cell
1// 1) Comment Section - description about the program
2package packname; // 2) Package Section (optional, first statement)
3import java.io.*; // 3) Import Section (optional)
4 
5// 4) Classes / Interfaces Section
6class Employee {
7 // variables and methods
8}
9 
10// 5) Main Class Section - contains main()
11class Test {
12 public static void main(String[] args) {
13 // application logic
14 }
15}

Tokens — The Smallest Building Blocks

A Java program is made of many small pieces. These smallest meaningful pieces are called tokens. Just like an English sentence is made of words, a Java program is made of tokens.

There are five types of tokens in Java:

Token typeMeaningExample
IdentifiersNames given by the programmer to classes, variables, methodsa, name, Student, totalMarks
LiteralsConstant values written directly in the code10, 5.5, 'A', "Hello", true
KeywordsWords with fixed meaning, reserved by Javaclass, int, if, new, return
OperatorsSymbols that perform operations+, -, *, /, =, ==
SeparatorsSymbols that separate parts of code{, }, (, ), ;, ,
Example02
JCode Cell
1int a = 10 + 5; ==> tokens: int | a | = | 10 | + | 5 | ;

More About Tokens — Lexeme and Token

The smallest logical unit in a Java program is called a lexeme. A token is a group of lexemes that belong to the same category.

There are four types of tokens in Java: Identifiers, Literals, Keywords (Reserved Words) and Operators.

Identifier Rules — All the Details

RuleValid examplesInvalid examples
Must not start with a number; may start with a letter, _ or $int eno = 111;int 9eno = 999;
After the first letter, digits are allowedString emp9No = "E-9";
_ and $ are allowed anywhereemp_Addr, emp$Salemp-Addr, emp+No
No spaces inside a nameconcat(), getInputStream()for Name(), get Input Stream()
No duplicate names in the same scopei in class + i in method (different scopes)two i at class level
Predefined class names may be used as identifiers (with care)int Exception = 10;int System = 10; (then System class is shadowed)
Trainer's Note: The System gotcha from the classic material: int System = 10; compiles, but now the word System means your variable, so System.out.println fails! You must use the full name java.lang.System.out.println(...) instead. This is why it is wise not to use class names as variable names.

Literals — All the Details

A literal is a constant value written directly in code. Java has integer, floating-point, boolean, character and String literals. Since Java 7, you can also use underscores inside numbers to make them readable:

Example03
JCode Cell
1int a = b + c * d;
2 
3Lexemes : int, a, =, b, +, c, *, d, ; (9 small pieces)
4Tokens : int (data type) | a, b, c, d (identifiers)
5 =, +, * (operators) | ; (special symbol)

More About Tokens — Lexeme and Token

Java supports four number systems for integer literals:

Number systemPrefixDigitsExample
Binary (base 2)0b or 0B0, 1int b = 0b1010; (valid), 0b1012 (invalid)
Octal (base 8)0 (zero)0-7int o = 04567; (valid), 05678 (invalid)
Decimal (base 10)none0-9int d = 123; (default)
Hexadecimal (base 16)0x or 0X0-9, a-fint h = 0x89abcd; (valid), 0x9g (invalid)

The compiler recognises the system from the prefix and converts everything to decimal internally before processing.

Keywords — The Reserved Words

A keyword is a word with both recognition and functionality (like class, int). A reserved word is only recognised but has no function in Java — the two reserved words are goto and const. Keywords are grouped by purpose:

Example04
JCode Cell
1float f = 1_23_45_678.2345f; // compiler removes _ and uses 12345678.2345

More About Tokens — Lexeme and Token

Trainer's Note: true, false and null are not technically keywords, but they are reserved literals — you still cannot use them as names.
Example05
JCode Cell
1Data types & return : byte, short, int, long, float, double, char, boolean, void
2Access control : public, protected, private, static, final, abstract, native, volatile, transient, synchronized, strictfp
3Flow control : if, else, switch, case, default, for, while, do, break, continue, return
4Class / object : class, enum, extends, interface, implements, package, import, new, this, super
5Exceptions : throw, throws, try, catch, finally

Identifiers — Naming Rules

  • An identifier can contain letters, digits, underscore _ and dollar $.
  • It cannot start with a digit. 1name is wrong, name1 is correct.
  • It cannot be a keyword. You cannot name a variable class or int.
  • Java is case sensitive. total and Total are two different names.
  • There is no length limit on the name, but keep it sensible.
Trainer's Note: Good coding habit: variable names start with a small letter (like studentAge), class names start with a capital letter (like Student), and constants are all capitals (like MAX_LIMIT). This is called camelCase and it makes your code professional.
Example06
JCode Cell
1Valid: name, _total, $value, name123, studentName
2Invalid: 123name, class, my name, a-b

Keywords

Keywords are words that Java has already reserved. You cannot use them as variable or class names. There are 53 keywords in Java. Some common ones:

Trainer's Note: true, false and null are not keywords in the strict sense but they are reserved literals — you still cannot use them as names.
Example07
JCode Cell
1class, public, static, void, int, if, else, for, while, do, switch, case,
2break, continue, return, new, this, super, final, try, catch, throw, throws,
3interface, package, import, boolean, byte, char, short, long, float, double,
4true, false, null, synchronized, volatile, extends, implements, ...

Java Naming Conventions (Coding Habits)

Java is case sensitive — Name and name are different. Good developers follow these naming conventions so code is easy to read:

ItemConventionExamples
Class / interface / enum namesStart with a capital letter, then capital for each new wordString, StringBuffer, InputStreamReader
Variable namesStart with small letter, capital for each new wordstudentName, totalMarks, in, out
Method namesStart with small letter, capital for each new wordconcat(), getInputStream(), forName()
ConstantsAll capital letters with underscoresMAX_PRIORITY, MIN_VALUE
Package namesAll small lettersjava.util, com.example
Trainer's Note: These rules are mandatory for Java's own library and optional but strongly suggested for your own code. Following them makes your code look professional in college and job interviews.

File Naming Rules — With Examples

The rule has two parts, and these five examples from the classic material make it crystal clear:

  • If the file contains a public element (public class/interface/enum), the file must be named after it.
  • If there is no public element, you can save the file with any name — but it is best to use the class that has main().
File nameContentResult
abc.javaclass FirstApp { main() } (no public class)Compiles — but not suggested
FirstApp.javaclass FirstApp { main() } (no public class)Compiles — suggested
FirstApp.javapublic class A { } + class FirstApp { main() }Error — file must be A.java
A.javapublic class A { } + class FirstApp { main() }Compiles
A.javapublic class A { } + public class B { }Error — two public classes

The reason a file can have only one public class: the file would need more than one name, which is impossible on any operating system.

📝 Key Takeaways
  • Tokens are the smallest pieces of a program: identifiers, literals, keywords, operators, separators.
  • Java has 8 primitive types: byte, short, int, long, float, double, char, boolean.
  • Widening casting is automatic and safe; narrowing casting needs brackets and may lose data.
  • if / switch decide which path runs; for / while / do-while repeat code; break and continue control loops.
  • Arrays hold many same-type values; index starts at 0; size is fixed; for-each loop reads them simply.
  • Var-args (int... x) lets a method take any number of arguments.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1