Identifiers and Rules for Naming
Every seat on a train has a label such as S4-32, and every account at a bank has a number. Labels let you point at one thing out of many. In a program, the labels are identifiers: the names you give to classes, variables, methods and packages. Java has a few strict rules about what a name may contain. Break one and the program doesn't compile.
What Counts as an Identifier
Any name you choose is an identifier. In this program, the identifiers are Fare, main, args, perPerson, passengers and total:
public class Fare {
public static void main(String[] args) {
int perPerson = 450;
int passengers = 3;
int total = perPerson * passengers;
System.out.println("Total: Rs. " + total);
}
}Total: Rs. 1350How it works
- Lines 3 to 5 create three variables.
perPerson,passengersandtotalare identifiers you picked. public,class,static,voidandintare keywords, not identifiers.StringandSystemare identifiers too, but someone else chose them: they're names of classes in Java's standard library.
Try it yourself: rename perPerson to farePerPerson everywhere it appears. Does the output change?
The Five Rules
- A name may contain letters, digits,
_(underscore) and$(dollar sign). - It must not start with a digit.
seat2is fine;2ndSeatis not. - It must not contain spaces or other symbols such as
-,#,@or.. - It must not be a keyword such as
classorint, or the literalstrue,falseandnull. - A single
_on its own isn't a name you can use later. Since Java 22 it means an unnamed variable: one you must declare but never read.
There's no length limit, and "letters" includes letters from other scripts, so café and even मूल्य are valid. Most teams stick to English letters so that everyone can type every name.
What the Compiler Says
Breaking a rule usually doesn't produce a friendly "bad name" message. These are the real errors from Java 25:
Ident1.java:3: error: not a statement
int 2ndPlace = 2;
^
Ident2.java:3: error: ';' expected
int my-score = 90;
^In the second one, the compiler reads my - score as "my minus score", so it expects the statement to end after my. When an error points at the middle of a name, check that name against the five rules.
Common Mistakes
Starting a name with a number. 1stClass, 3dModel and 24hours all fail. Use firstClass, model3d, hours24.
Using a hyphen. user-name is subtraction to Java. Use userName.
Changing case halfway. Declaring int Total and later writing total causes cannot find symbol.
Practice
- Easy: Which are valid identifiers?
price,_price,$price,price$,2price,price-2,price_2,Price,int. - Harder: Write a program with valid names for these: number of seats in a coach, name of a passenger, platform number, ticket price in rupees. Print all four.
Key Takeaways
Was this tutorial helpful?