Lably
Skip to content

Java syntax

Rules defining correctly structured Java programs

  • 90 min read
  • 8 chapters

Learn it on Lably

The syntax is mostly derived from C and C++. Unlike C++, Java has no global functions or variables, but has data members which are also regarded as global variables. All code belongs to classes and all values are objects. The only exception is the primitive data types, which are not considered to be objects for performance reasons (though can be automatically converted to objects and vice versa via autoboxing). Some features like operator overloading or unsigned integer data types are omitted to simplify the language and avoid possible programming mistakes.

The Java syntax has been gradually extended in the course of numerous major JDK releases, and now supports abilities such as generic programming and anonymous functions (function literals, called lambda expressions in Java). Since 2017, a new JDK version is released twice a year.

Basics

The Java "Hello, World!" program program is as follows:

<span id="mwJw"></span><span class="kd" id="mwKA">public</span><span class="w" id="mwKQ"> </span><span class="kd" id="mwKg">class</span> <span class="nc" id="mwKw">HelloWorld</span><span class="w" id="mwLA"> </span><span class="p" id="mwLQ">{</span> <span class="w" id="mwLg"> </span><span class="kd" id="mwLw">public</span><span class="w" id="mwMA"> </span><span class="kd" id="mwMQ">static</span><span class="w" id="mwMg"> </span><span class="kt" id="mwMw">void</span><span class="w" id="mwNA"> </span><span class="nf" id="mwNQ">main</span><span class="p" id="mwNg">(</span><span class="n" id="mwNw">String</span><span class="o" id="mwOA">[]</span><span class="w" id="mwOQ"> </span><span class="n" id="mwOg">args</span><span class="p" id="mwOw">)</span><span class="w" id="mwPA"> </span><span class="p" id="mwPQ">{</span> <span class="w" id="mwPg"> </span><span class="n" id="mwPw">System</span><span class="p" id="mwQA">.</span><span class="na" id="mwQQ">out</span><span class="p" id="mwQg">.</span><span class="na" id="mwQw">println</span><span class="p" id="mwRA">(</span><span class="s" id="mwRQ">"Hello World!"</span><span class="p" id="mwRg">);</span> <span class="w" id="mwRw"> </span><span class="p" id="mwSA">}</span> <span class="p" id="mwSQ">}</span>

Since Java 25, a simplified Hello World program without an explicit class may be written:

<span id="mwTQ"></span><span class="kt" id="mwTg">void</span><span class="w" id="mwTw"> </span><span class="nf" id="mwUA">main</span><span class="p" id="mwUQ">()</span><span class="w" id="mwUg"> </span><span class="p" id="mwUw">{</span> <span class="w" id="mwVA"> </span><span class="n" id="mwVQ">IO</span><span class="p" id="mwVg">.</span><span class="na" id="mwVw">println</span><span class="p" id="mwWA">(</span><span class="s" id="mwWQ">"Hello World!"</span><span class="p" id="mwWg">);</span> <span class="p" id="mwWw">}</span>

Identifier

An identifier is the name of an element in the code. There are certain standard naming conventions to follow when selecting names for elements. Identifiers in Java are case-sensitive.

An identifier can contain:

  • Any Unicode character that is a letter (including numeric letters like Roman numerals) or digit.
  • Currency sign (such as ¥).
  • Connecting punctuation character (such as _).

An identifier cannot:

  • Start with a digit.
  • Be equal to a reserved keyword, null literal or Boolean literal.

Keywords

Keywords

The following words are keywords and cannot be used as identifiers under any circumstances, of which there are 47.

  • abstract
  • assert
  • boolean
  • break
  • byte
  • case
  • catch
  • char
  • class
  • continue
  • default
  • do
  • double
  • else
  • enum
  • extends
  • final
  • finally
  • float
  • for
  • if
  • implements
  • import
  • instanceof
  • int
  • interface
  • long
  • native
  • new
  • package
  • private
  • protected
  • public
  • return
  • short
  • static
  • super
  • switch
  • synchronized
  • this
  • throw
  • throws
  • transient
  • try
  • void
  • volatile
  • while

Reserved identifiers

The following words are contextual keywords and are only restricted in certain contexts, of which there are 16.

  • exports
  • module
  • non-sealed
  • open
  • opens
  • permits
  • provides
  • record
  • requires
  • sealed
  • to
  • transitive
  • var
  • when
  • with
  • yield

Reserved words for literal values

The following words refer to literal values used by the language, of which there are 3.

  • true
  • false
  • null

Unused

The following words are reserved as keywords, but currently have no use or purpose, of which there are 4.

  • _
  • const
  • goto
  • strictfp

Literals

Integer literals are of int type by default unless long type is specified by appending L or l suffix to the literal, e.g. 367L. Since Java SE 7, it is possible to include underscores between the digits of a number to increase readability; for example, a number 145608987 can be written as 145_608_987.

Variables

Variables are identifiers associated with values. They are declared by writing the variable's type and name, and are optionally initialized in the same statement by assigning a value.

<span id="mwAUk"></span><span class="kt" id="mwAUo">int</span><span class="w" id="mwAUs"> </span><span class="n" id="mwAUw">count</span><span class="p" id="mwAU0">;</span><span class="w" id="mwAU4"> </span><span class="c1" id="mwAU8">// Declaring an uninitialized variable called 'count', of type 'int'</span> <span class="n" id="mwAVA">count</span><span class="w" id="mwAVE"> </span><span class="o" id="mwAVI">=</span><span class="w" id="mwAVM"> </span><span class="mi" id="mwAVQ">35</span><span class="p" id="mwAVU">;</span><span class="w" id="mwAVY"> </span><span class="c1" id="mwAVc">//Initializing the variable</span> <span class="kt" id="mwAVg">int</span><span class="w" id="mwAVk"> </span><span class="n" id="mwAVo">count</span><span class="w" id="mwAVs"> </span><span class="o" id="mwAVw">=</span><span class="w" id="mwAV0"> </span><span class="mi" id="mwAV4">35</span><span class="p" id="mwAV8">;</span><span class="w" id="mwAWA"> </span><span class="c1" id="mwAWE">// Declaring and initializing the variable at the same time</span>

Multiple variables of the same type can be declared and initialized in one statement using comma as a delimiter.

<span id="mwAWU"></span><span class="kt" id="mwAWY">int</span><span class="w" id="mwAWc"> </span><span class="n" id="mwAWg">a</span><span class="p" id="mwAWk">,</span><span class="w" id="mwAWo"> </span><span class="n" id="mwAWs">b</span><span class="p" id="mwAWw">;</span><span class="w" id="mwAW0"> </span><span class="c1" id="mwAW4">// Declaring multiple variables of the same type</span> <span class="kt" id="mwAW8">int</span><span class="w" id="mwAXA"> </span><span class="n" id="mwAXE">a</span><span class="w" id="mwAXI"> </span><span class="o" id="mwAXM">=</span><span class="w" id="mwAXQ"> </span><span class="mi" id="mwAXU">2</span><span class="p" id="mwAXY">,</span><span class="w" id="mwAXc"> </span><span class="n" id="mwAXg">b</span><span class="w" id="mwAXk"> </span><span class="o" id="mwAXo">=</span><span class="w" id="mwAXs"> </span><span class="mi" id="mwAXw">3</span><span class="p" id="mwAX0">;</span><span class="w" id="mwAX4"> </span><span class="c1" id="mwAX8">// Declaring and initializing multiple variables of the same type</span>

Type inference

Since Java 10, it has become possible to infer types for the variables automatically by using var.

<span id="mwAYg"></span><span class="kn" id="mwAYk">import</span><span class="w" id="mwAYo"> </span><span class="nn" id="mwAYs">java.io.FileOutputStream</span><span class="p" id="mwAYw">;</span> <span class="c1" id="mwAY0">// stream will have the FileOutputStream type as inferred from its initializer</span> <span class="kd" id="mwAY4">var</span><span class="w" id="mwAY8"> </span><span class="n" id="mwAZA">stream</span><span class="w" id="mwAZE"> </span><span class="o" id="mwAZI">=</span><span class="w" id="mwAZM"> </span><span class="k" id="mwAZQ">new</span><span class="w" id="mwAZU"> </span><span class="n" id="mwAZY">FileOutputStream</span><span class="p" id="mwAZc">(</span><span class="s" id="mwAZg">"file.txt"</span><span class="p" id="mwAZk">);</span> <span class="c1" id="mwAZo">// An equivalent declaration with an explicit type</span> <span class="n" id="mwAZs">FileOutputStream</span><span class="w" id="mwAZw"> </span><span class="n" id="mwAZ0">stream</span><span class="w" id="mwAZ4"> </span><span class="o" id="mwAZ8">=</span><span class="w" id="mwAaA"> </span><span class="k" id="mwAaE">new</span><span class="w" id="mwAaI"> </span><span class="n" id="mwAaM">FileOutputStream</span><span class="p" id="mwAaQ">(</span><span class="s" id="mwAaU">"file.txt"</span><span class="p" id="mwAaY">);</span>

Code blocks

The separators { and } signify a code block and a new scope. Class members and the body of a method are examples of what can live inside these braces in various contexts.

Inside of method bodies, braces may be used to create new scopes, as follows:

<span id="mwAbE"></span><span class="kt" id="mwAbI">void</span><span class="w" id="mwAbM"> </span><span class="nf" id="mwAbQ">doSomething</span><span class="p" id="mwAbU">()</span><span class="w" id="mwAbY"> </span><span class="p" id="mwAbc">{</span> <span class="w" id="mwAbg"> </span><span class="kt" id="mwAbk">int</span><span class="w" id="mwAbo"> </span><span class="n" id="mwAbs">a</span><span class="p" id="mwAbw">;</span> <span class="w" id="mwAb0"> </span><span class="p" id="mwAb4">{</span> <span class="w" id="mwAb8"> </span><span class="kt" id="mwAcA">int</span><span class="w" id="mwAcE"> </span><span class="n" id="mwAcI">b</span><span class="p" id="mwAcM">;</span> <span class="w" id="mwAcQ"> </span><span class="n" id="mwAcU">a</span><span class="w" id="mwAcY"> </span><span class="o" id="mwAcc">=</span><span class="w" id="mwAcg"> </span><span class="mi" id="mwAck">1</span><span class="p" id="mwAco">;</span> <span class="w" id="mwAcs"> </span><span class="p" id="mwAcw">}</span> <span class="w" id="mwAc0"> </span><span class="n" id="mwAc4">a</span><span class="w" id="mwAc8"> </span><span class="o" id="mwAdA">=</span><span class="w" id="mwAdE"> </span><span class="mi" id="mwAdI">2</span><span class="p" id="mwAdM">;</span> <span class="w" id="mwAdQ"> </span><span class="n" id="mwAdU">b</span><span class="w" id="mwAdY"> </span><span class="o" id="mwAdc">=</span><span class="w" id="mwAdg"> </span><span class="mi" id="mwAdk">3</span><span class="p" id="mwAdo">;</span><span class="w" id="mwAds"> </span><span class="c1" id="mwAdw">// Illegal because the variable b is declared in an inner scope..</span> <span class="p" id="mwAd0">}</span>

Comments

Java has three kinds of comments: traditional comments, end-of-line comments and documentation comments.

Traditional comments, also known as block comments, start with /* and end with */, they may span across multiple lines. This type of comment was derived from C and C++.

<span id="mwAek"></span><span class="cm" id="mwAeo">/* This is a multi-line comment.</span> <span class="cm" id="mwAes">It may occupy more than one line. */</span>

End-of-line comments start with // and extend to the end of the current line. This comment type is also present in C++ and in modern C.

<span id="mwAfA"></span><span class="c1" id="mwAfE">// This is an end-of-line comment</span>

Documentation comments in the source files are processed by the Javadoc tool to generate documentation. This type of comment is identical to traditional comments, except it starts with /** and follows conventions defined by the Javadoc tool. Technically, these comments are a special kind of traditional comment and they are not specifically defined in the language specification.

<span id="mwAfc"></span><span class="cm" id="mwAfg">/**</span> <span class="cm" id="mwAfk"> * This is a documentation comment.</span> <span class="cm" id="mwAfo"> * </span> <span class="cm" id="mwAfs"> * @author John Doe</span> <span class="cm" id="mwAfw"> */</span>

Universal types

Classes in the package java.lang (but not its subpackages) are implicitly imported into every program, as long as no explicitly-imported types have the same names. Important ones include:

java.lang.System

java.lang.System is one of the most fundamental classes in Java. It is a utility class for interacting with the system, containing standard input, output, and error streams, system properties and environment variables, time, and more.

java.lang.Object

java.lang.Object is Java's top type. It is implicitly the superclass of all classes that do not declare any parent class (thus all classes in Java inherit from Object). All values can be converted to this type, although for primitive values this involves autoboxing.

java.lang.Record

All records implicitly extend java.lang.Record. Thus, a record, while treated as a class, cannot extend any other class.

java.lang.Enum<E>

All enumerated types (enums) in Java implicitly extend java.lang.Enum<E>. Thus, an enum, while treated as a class, cannot extend any other class. The type parameter E is constrained as Enum<E extends Enum<E>>.

java.lang.Class<T>

java.lang.Class<T> is a class that represents a class or interface in the application at runtime. It cannot be constructed via direct instantiation, but is rather created by the JVM when a class is derived from the bytes of a .class file. A class literal can be obtained through X.class on such a class X. For instance, String.class returns Class<String>. An unknown class being modeled can be represented as Class<?> (where ? denotes a wildcard).

While X.class appears to be accessing a field named "class", there is actually no such field named "class"; it is in fact performing the instruction ldc, which pushes a constant from the class's runtime constant pool into the operand stack.

java.lang.String

java.lang.String is Java's basic string type. It is immutable. It does not implement Iterable<Character>, so it cannot be iterated over in a for-each loop, but can be converted to char[]. Some methods treat each UTF-16 code unit as a char, but methods to convert to an int[] that is effectively UTF-32 are also available. String implements java.lang.CharSequence, so chars in the String can be accessed by the method charAt().

java.lang.Throwable

java.lang.Throwable is the supertype of everything that can be thrown or caught with Java's throw and catch statements. Its direct known subclasses are java.lang.Error (for serious unrecoverable errors) and java.lang.Exception (for exceptions that may naturally occur in the execution of a program).

java.lang.Error

java.lang.Error is the supertype of all error classes and extends Throwable. It is used to indicate conditions that a reasonable application should not catch.

java.lang.Exception

java.lang.Exception is the supertype of all exception classes and extends Throwable. It is used to indicate conditions that a reasonable application may have reason to catch.

java.lang.Math

java.lang.Math is a utility class containing mathematical functions and mathematical constants (such as Math.sin(), Math.pow(), and Math.PI).

java.lang.IO

java.lang.IO is a class introduced in Java 25 (previously residing in java.io as java.io.IO). It allows simpler access to the standard input and output streams over System.in and System.out.

Primitives

Each primitive type has an associated wrapper class (see primitive types).

Sign in to keep reading

7 more chapters are free with a Lably account.

More in Computer Applications