Java Building Blocks: Introduction

Data types, literal values, variables, operators, and basic statements.

Overview

While the Java language has evolved considerably over the past 25+ years, the low-level syntax has remained largely unchanged, and much of that (though not all) can be understood without having to know much about the high-level constructs of classes and interfaces. This low-level syntax defines expressions and statements (simple and compound), which are organized into methods.

Contents

This module introduces the first elements of the low-level syntax—data types, literals, variables, operators, and basic statements—through a number of examples. These examples demonstrate simple declarations and expressions which can be successfully compiled, as well as some that can’t. The reader is encouraged to try these examples (and others they might think of) using JShell, which allows a programmer to evaluate expressions and execute statements interactively. We can even write methods and classes in JShell; the examples here don’t include any class creation,1 but do include methods.

Requirements

The examples here use JShell, which is included in the JDK2 starting with version 9. Please note, however, that JShell has been improved significantly since its initial inclusion in the JDK. We recommend using the JShell included with Java 11 or higher. (For examples that use compound statements or methods, JShell 13 or higher improves ease-of-use greatly, but the examples don’t require those versions.)

For most purposes, JShell can be viewed as a combination of a Java compiler and execution environment, where statements are compiled and then immediately executed. This includes higher-level definition statements, such as those defining methods, classes, and interfaces. However, JShell isn’t an IDE, and is not at all ideal for development of classes and interfaces.

Windows setup

For some of the examples that display Unicode characters, the following commands must be executed in Windows command prompt shell or Windows PowerShell prior to launching JShell from the same shell:

Windows command prompt

chcp 65001
set JAVA_TOOL_OPTIONS=-Dfile.encoding=utf8

Windows PowerShell

chcp 65001
$Env:JAVA_TOOL_OPTIONS = "-Dfile.encoding=utf8"
  1. For an introduction to the syntax and use of classes, see “Classes in Java”

  2. The Java Development Kit (JDK) includes the tools needed to compile and package Java applications and libraries, along with the Java Runtime Environment (JRE) used to run Java applications. More information can be found in JRE & JDK