What is a token in Java?

Token in Java is the smallest piece of code, identified by the compiler.

Tokens can be:

  • Identifiers myVariable myMethod MyClass
  • Keywords new class int
  • Literals "a string" 'c' 53.3
  • Operators > == +
  • Separators ; ,
  • Comments /* a comment */

What tokens are present here?

In this block of code:

int number1 = 2;
int number2 = 3;

// adding 2 + 3
int result = number1 + number2;
  • number1, number2, result are identifiers.
  • int is a keyword.
  • 2 and 3 are literals.
  • = and + are operators.
  • ; is a separator.
  • // adding 2 + 3 is a comment.