- Previous
- Next
Java program has a structure which is made of several elements. These elements are tokens, white-spaces, literals, comments, separators, and identifiers.
Read next article to know the list of keywords in Java.
Tokens
Tokens are the smallest element in a Java source code. The Java compiler break source into lines of code whenever it encounters terminator such as (;) semicolon. The compiler goes through the line and mark end of each token, then ignores all whitespaces, until a non-whitespace character is encountered. A token mismatch will cause a syntax error. The goal is to make a token list.
For example,
int number = 2000 ;
The above is the same as
int number = 2000;
We have the following tokens.
int
number
=
2000
;
Whitespaces
A Java whitespace is a newline character, space, or tab space. Java is a free form programming language, means you can leave lot spaces between tokens. You can write your program any way you like without worrying about the whitespaces.
Identifiers
Identifiers are names of different program elements such as class, package, variables, etc. An identifier uses letters, numbers, a special character like a ($)dollar sign and (_)underscore. The identifiers must follow certain rules.
- An identifier must start with letter, dollar, or underscore.
- The identifier can be of any length (but, we restrict to 15)
- Reserved words known as keywords cannot be used as identifiers.
Comments
Comments are lines ignored by the Java compiler. Two types of comments allowed in Java.
- Single line comments
- Multi-line comments
For example,
// This is a single line comment - ignored by compiler
int x = 2000;
The multi-line comment span multiple lines without any special indentation rules.
For example,
/*
This is multi-line comment used to describe program information at the beginning
of the program source code.
*/
Note that each comment must not be nested.
Separators
Separators are program elements that separate items like class, objects, a block of code, a line of code, function arguments. The most common separator is a semi-colon. If you remember from previous example codes, each statement ends with a semi-colon in Java.
Here is a list of separators in Java,
Separator | Symbol | Description |
Braces | { } | Contains a block of code. |
Parentheses | ( ) | Keep method arguments |
Brackets | [ ] | Define the size of an array |
Semi-colon | ; | Line terminator |
Comma | , | Separates argument list |
Dot | . | Separates packages, object methods |
Literals
A literal is a constant of a specific type. Here is a list of literal types in Java.
Literal Type | Example |
Integer | 568 |
Floating-point | 45.90 |
Boolean | True / False |
Character | ‘M’ |
String | “Sports” |