In Java, tokens are the smallest individual units that make up a program. The Java programming language has the following types of tokens:
- Keywords: These are reserved words that have a specific meaning in Java. Examples include
class
,if
,else
,for
,while
,return
, andpublic
. You cannot use keywords as identifiers (variable names, method names, etc.). - Identifiers: These are names given to classes, methods, variables, and other entities in Java. Identifiers must follow certain rules, such as starting with a letter, underscore, or dollar sign, and can contain letters, digits, underscores, and dollar signs.
- Literals: These represent constant values in the code. There are several types of literals in Java, including:
- Integer literals: Whole numbers without decimal points, such as
42
or-10
. - Floating-point literals: Numbers with decimal points, such as
3.14
or1.0e-5
. - Boolean literals:
true
andfalse
. - Character literals: Single characters enclosed in single quotes, such as
'A'
or'\n'
. - String literals: Sequences of characters enclosed in double quotes, such as
"Hello, World!"
.
- Operators: These symbols perform operations on operands. Examples of operators in Java include arithmetic operators (
+
,-
,*
,/
), assignment operator (=
), comparison operators (==
,!=
,<
,>
,<=
,>=
), logical operators (&&
,||
,!
), and more. - Separators: These symbols are used to separate parts of the program. Examples include parentheses (
(
and)
), braces ({
and}
), brackets ([
and]
), commas (,
), semicolons (;
), and periods (.
). - Comments: These are used to add explanatory notes or disable certain portions of the code. There are two types of comments in Java:
- Single-line comments: Start with
//
and extend to the end of the line. - Multi-line comments: Enclosed between
/*
and*/
and can span multiple lines.
It’s worth noting that whitespace (spaces, tabs, and line breaks) is not considered a token and is used for formatting and readability purposes.