-- JLS §7.3: Compilation Units --
CompilationUnit:
OrdinaryCompilationUnit
ModularCompilationUnit
OrdinaryCompilationUnit:
[PackageDeclaration] {ImportDeclaration} {TopLevelClassOrInterfaceDeclaration}
ModularCompilationUnit:
{ImportDeclaration} ModuleDeclaration
-- JLS §7.4: Package Declaration --
PackageDeclaration:
{PackageModifier} package PackageName ;
PackageName:
Identifier
PackageName . Identifier
-- JLS §7.5: Import Declarations --
ImportDeclaration:
SingleTypeImportDeclaration
TypeImportOnDemandDeclaration
SingleStaticImportDeclaration
StaticImportOnDemandDeclaration
SingleTypeImportDeclaration:
import TypeName ;
TypeImportOnDemandDeclaration:
import PackageOrTypeName . * ;
-- JLS §8.1: Class Declaration --
ClassDeclaration:
NormalClassDeclaration
EnumDeclaration
RecordDeclaration
NormalClassDeclaration:
{ClassModifier} class TypeIdentifier [TypeParameters]
[ClassExtends] [ClassImplements] [ClassPermits] ClassBody
ClassModifier:
Annotation
public | protected | private
abstract | static | final | sealed | non-sealed | strictfp
-- JLS §3.8: Identifiers --
Identifier:
IdentifierChars but not a Keyword or BooleanLiteral or NullLiteral
IdentifierChars:
JavaLetter {JavaLetterOrDigit}
JavaLetter:
any Unicode character that is a "Java letter"
JavaLetterOrDigit:
any Unicode character that is a "Java letter-or-digit"
-- JLS §3.9: Keywords --
Keyword:
ReservedKeyword | ContextualKeyword
ReservedKeyword: one of
abstract continue for new switch
assert default if package synchronized
boolean do goto private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
_
-- JLS §3.7: Comments --
Comment:
TraditionalComment
EndOfLineComment
TraditionalComment:
/* CommentTail
CommentTail:
* CommentTailStar
NotStar CommentTail
EndOfLineComment:
// {InputCharacter}
-- JLS §3.4: Line Terminators --
LineTerminator:
the ASCII LF character, also known as "newline"
the ASCII CR character, also known as "return"
the ASCII CR character followed by the ASCII LF character
-- JLS §3.6: White Space --
WhiteSpace:
the ASCII SP character, also known as "space"
the ASCII HT character, also known as "horizontal tab"
the ASCII FF character, also known as "form feed"
LineTerminator
-- JLS §8.4: Method Declarations --
MethodDeclaration:
{MethodModifier} MethodHeader MethodBody
MethodHeader:
Result MethodDeclarator [Throws]
TypeParameters {Annotation} Result MethodDeclarator [Throws]
MethodDeclarator:
Identifier ( [FormalParameterList] ) [Dims]
MethodModifier:
Annotation
public | protected | private
abstract | static | final | synchronized | native | strictfp
-- JLS §3.10: Literals --
Literal:
IntegerLiteral
FloatingPointLiteral
BooleanLiteral
CharacterLiteral
StringLiteral
TextBlock
NullLiteral
Java programs are translated in phases: 1. Unicode escape sequences (\uXXXX) are translated first. 2. Input is divided into lines using line terminators. 3. Lines are divided into tokens (lexical analysis). 4. Tokens are parsed (syntax analysis).
// Java 17+ (JEP 306): all code is effectively strictfp// strictfp modifier is obsolete but not an errorstrictfpclassCalculator{}// compiles with warning
// Example 1: Minimal Java Program// File: HelloWorld.javapackagecom.example.basics;publicclassHelloWorld{publicstaticvoidmain(String[]args){System.out.println("Hello, World!");}}
// Example 2: Package, Imports, Multiple Classes// File: Greeter.javapackagecom.example.basics;importjava.util.List;importjava.util.ArrayList;import staticjava.lang.Math.PI;publicclassGreeter{privateStringname;publicGreeter(Stringname){this.name=name;}publicStringgreet(){return"Hello, "+name+"!";}publicstaticvoidmain(String[]args){Greeterg=newGreeter("Java 21");System.out.println(g.greet());System.out.println("PI = "+PI);List<String>items=newArrayList<>();items.add("alpha");items.add("beta");for(Stringitem:items){System.out.println(item);}}}// Package-private helper class in same fileclassInternalHelper{staticStringformat(Strings){return"["+s+"]";}}
// Example 3: Comments, Identifiers, Unicode// File: SyntaxDemo.javapublicclassSyntaxDemo{// Single-line comment/* Multi-line comment *//** * JavaDoc comment * @param args command line arguments */publicstaticvoidmain(String[]args){// Unicode escape in identifierintcaf\u00E9=42;// declares: int café = 42;System.out.println(caf\u00E9);// prints: 42// var type inference (Java 10+)varmessage="Inferred as String";System.out.println(message);// Text block (Java 15+)Stringjson=""" { "key": "value" } """;System.out.println(json);}}
// Example 4: Sealed Class Hierarchy (Java 17+)// File: Shape.javapublicsealedclassShapepermitsCircle,Rectangle{abstractdoublearea();}finalclassCircleextendsShape{privatefinaldoubleradius;Circle(doubleradius){this.radius=radius;}@Overridedoublearea(){returnMath.PI*radius*radius;}}finalclassRectangleextendsShape{privatefinaldoublewidth,height;Rectangle(doublewidth,doubleheight){this.width=width;this.height=height;}@Overridedoublearea(){returnwidth*height;}}
// Example 5: Record Declaration (Java 16+)// File: Point.javapublicrecordPoint(doublex,doubley){// Compact constructorpublicPoint{if(Double.isNaN(x)||Double.isNaN(y)){thrownewIllegalArgumentException("Coordinates cannot be NaN");}}publicdoubledistanceTo(Pointother){doubledx=this.x-other.x;doubledy=this.y-other.y;returnMath.sqrt(dx*dx+dy*dy);}publicstaticvoidmain(String[]args){Pointp1=newPoint(0.0,0.0);Pointp2=newPoint(3.0,4.0);System.out.println("Distance: "+p1.distanceTo(p2));// 5.0}}