Java is an object-oriented programming language, but there's more to Java than programming with objects. This tutorial is the first of several introducing non-object-oriented features and syntax that are fundamental to the Java language. You'll learn how to use comments, identifiers, types, literals, and variables in your Java programs. You'll also learn why and how to document your code, and you'll see how Java's support for Unicode affects source code and compilation.
Comments: Three ways to document your Java code
Suppose you're working in the IT department for a large company. Your boss instructs you to write a program consisting of a few thousand lines of source code. After a few weeks, you finish the program and deploy it. A few months later, users begin to notice that the program occasionally crashes. They complain to your boss, who orders you to fix it. The problem is, you've worked on other projects since creating this one, and you can't remember why you wrote the code the way that you did.
This is a common scenario, and stressful. You can avoid this stress by documenting your source code with meaningful descriptions. Though frequently overlooked, documenting code is one of the most important tasks in software development. Writing well-documented code is a sign of professionalism, and it will save you and other developers a lot of time.
In Java, you can use the comment feature to embed documentation in your source code. A comment is a delimited block of text that's meaningful to humans but not to the compiler. When you compile the source code, the Java compiler ignores all comments and doesn't generate bytecodes for them. Java supports single-line, multiline, and Javadoc comments.
Single-line comments
A single-line comment spans a single line. It begins with //
and continues to the end of the current line. The compiler ignores all characters from //
through the end of that line. The following example presents a single-line comment:
System.out.println((98.6 - 32) * 5 / 9); // Output Celsius equivalent of 98.6 degrees Fahrenheit.
A single-line comment is useful for specifying a short, meaningful description of the intent behind a given line of code.
Starting with Java 9, you can use jshell
to try out single-line and other kinds of comments. Here's an example:
jshell> // single-line comment
jshell>
Multiline comments
A multiline comment spans multiple lines. It begins with /*
and ends with */
. All characters from /*
through */
are ignored by the compiler. The following example presents a multiline comment:
/*
An amount of $2,200.00 is deposited in a bank paying an annual
interest rate of 2%, which is compounded quarterly. What is
the balance after 10 years?
Compound Interest Formula:
A = P(1+r/n)nt
A = amount of money accumulated after n years, including interest
P = principal amount (the initial amount you deposit)
r = annual rate of interest (expressed as a decimal fraction)
n = number of times the interest is compounded per year
t = number of years for which the principal has been deposited
*/
double principal = 2200;
double rate = 2 / 100.0;
double t = 10;
double n = 4;
System.out.println(principal * Math.pow(1 + rate / n, n * t));
As you can see, a multiline comment is useful for documenting multiple lines of code. Alternatively, you could use multiple single-line comments for this purpose:
// Create a ColorVSTextComponent object that represents a component
// capable of displaying lines of text in different colors and which
// provides a vertical scrolling capability. The width and height of
// the displayed component are set to 180 pixels and 100 pixels,
// respectively.
ColorVSTextComponent cvstc = new ColorVSTextComponent(180, 100);
You can also use multiline comments to comment out blocks of code that you don't want compiled, but still want to keep for future use:
/*
if (!version.startsWith("1.3") && !version.startsWith("1.4"))
{
System.out.println("JRE " + version + " not supported.");
return;
}
*/
If you nest multiline comments the compiler will report an error. For example, the compiler outputs an error message when it encounters /* This /* nested multiline comment (on a single line) */ is illegal */
. Don't nest multiline comments.
Multiline comments with jshell
You'll notice something interesting when entering a multiline (or Javadoc) comment in jshell
. This tool presents a ...>
continuation prompt each time you press Enter while the comment hasn't been finished:
jshell> /*
...> Multiline comment
...> */
jshell>
Javadoc comments
A Javadoc comment is a special multiline comment. It begins with /**
and ends with */
. All characters from /**
through */
are ignored by the compiler. The following example presents a Javadoc comment:
/**
* Application entry point
*
* @param args array of command-line arguments passed to this method
*/
public static void main(String[] args)
{
// TODO code application logic here
}
This example's Javadoc comment describes the main()
method. Sandwiched between /**
and */
is a description of the method and the @param
Javadoc tag (an @
-prefixed instruction to the javadoc
tool).
Consider these commonly used Javadoc tags:
@author
identifies the source code's author.@deprecated
identifies a source code entity (e.g., method) that should no longer be used.@param
identifies one of a method's parameters.@see
provides a see-also reference.@since
identifies the software release where the entity first originated.@return
identifies the kind of value that the method returns.@throws
documents an exception thrown from a method.
Although they're ignored by the compiler, Javadoc comments are processed by javadoc
, which compiles them into HTML-based documentation. For example, the following command generates documentation for a hypothetical Checkers
class:
javadoc Checkers
The generated documentation includes an index file (index.html
) that describes the documentation's start page. For example, Figure 1 shows the start page from the Java SE 12 runtime library API documentation.
Figure 1. Java SE 12 runtime library API documentation was generated by javadoc
Identifiers: Naming classes, methods, and more in your Java code
In any programming language, developers must be able to name entities in order to reference them in code. Java provides the identifiers feature for this purpose. An identifier is simply a name for a source code entity.
An identifier consists of letters (A-Z, a-z, or equivalent uppercase/lowercase letters in any alphabet); digits (0-9 or equivalent digits in any numeral system); punctuation characters (such as the underscore); and currency symbols (such as the dollar sign). An identifier name must begin with a letter, a currency symbol, or a punctuation character. Furthermore, it cannot wrap from one line to the next.
Below are some examples of valid identifiers:
i
count2
loanAmount$
last_name
$balance
π
(Greek letter Pi -- 3.14159)
Many character sequences are not valid identifiers. Consider the following examples:
5points
, because it starts with a digityour@email_address
, because it contains an@
symbollast name
, because it includes a space
Reserved words
Almost any valid identifier can be chosen to name a class, method, or other source code entity. However, Java reserves some identifiers for special purposes; these are known as reserved words. Java reserves the following identifiers:
The compiler outputs an error message when it detects any of these reserved words being used outside of its usage contexts; for example, as the name of a class or method. Java also reserves but doesn't use const
and goto
.
Reserved word changes in Java 9 and Java 10
Every Java update brings changes and improvements to the language. Recent updates have included changes to Java's reserved words.
Beginning with Java SE 9, the underscore (_
) is reserved and is regarded to be a keyword. It's an error to use a single underscore to name anything. (It's okay to use multiple underscores for naming, but you probably shouldn't.)
Java SE 9 also introduced modules, along with 10 restricted keywords:
open
module
requires
transitive
exports
opens
to
uses
provides
with
The Java compiler regards these identifiers to be keywords only in the context of a module-info.java
file. Outside of this file, they are ordinary identifiers that can be used to name arbitrary items. (You'll learn more about modules later in this series.)
Java SE 10 introduced var
as the type of a local variable declaration and a lambda formal parameter. The compiler treats var
as an identifier with special meaning, but it isn't considered to be a reserved word. You can't use var
to name a class, but you can use it to name a method (although you probably shouldn't). We'll talk more about var
later.
Types: Classifying values in your Java code
Java applications process characters, integers, floating-point numbers, strings, and other kinds of values. All values of the same kind share certain characteristics. For example, integers don't have fractions and strings are sequences of characters with the concept of length.
Java provides the type feature for classifying values. A type is a set of values, their representation in memory, and a set of operations for manipulating these values, often transforming them into other values. For example, the integer type describes a set of numbers without fractional parts, a two's-complement representation (I'll explain two's-complement shortly), and operations such as addition and subtraction that produce new integers.
Java supports primitive types, reference types, and array types.
Primitive types
A primitive type is a type that's defined by the language and whose values are not objects. Java supports a handful of primitive types:
- Boolean
- Character
- Byte integer
- Short integer
- Integer
- Long integer
- Floating-point
- Double precision floating-point
You'll use primitive types frequently in your Java programs, so let's take a minute to consider each of them.
Boolean
The Boolean type describes true/false values. The JVM specification indicates that Boolean values stored in an array (discussed later) are represented as 8-bit (binary digit) integer values in memory. Furthermore, when they appear in expressions, these values are represented as 32-bit integers. Java supplies AND, OR, and NOT operations for manipulating Boolean values. Also, its boolean
reserved word identifies the Boolean type in source code.