In Java a variable identifier must follow the following rules:
- Must start with a letter, a ‘$’ or an ‘_’
- Cannot start with a number
- After the first characters can appear letters, numbers, underscores or ‘$’
The following snippet gives an edge case of variable naming:
public class JavaCertification { public static void main(String[] args) { int _ = 20; // '_' is a valid identifier System.out.println(_); } }
This program compiles and produces the following result:
20
So, ‘_’ is a valid name for an identifier and it doesn’t produce a compilation error. Despite that it is better never to call a variable in this way :)