One of the important things to learn regarding java programming language is what is allowed and not allowed in choosing the name of a variable. Basically there are rules for choosing the name of a variable and there are conventions. In this post, we will be learning about the rules that govern variable naming in java language in addition to the conversions that is used by any java developer. We will include code examples to illustrate naming rules.
Naming Rules
1 - Variable name can start only with a letter, underscore (_) or dollar sign ($).
//This is allowed
int firstNum;
//This is allowed
int FirstNum;
//This is allowed
int _firstNum;
//This is allowed
int $firstNum;
//This is not allowed
int !firstNum;
2 - Variable name can contain numbers after the first letter.
//This is allowed
int burger1;
//This is not allowed
int 1burger;
//This is allowed
int burger2;
3 - Variable name cannot contain spaces or special characters.
//This is not allowed
int burger 1;
//This is not allowed
int burger-2;
//This is not allowed
int burger(3);
4 - Uppercase name differ from lower case.
//This one variable
int burger;
//This one is another one
int BURGER;
//Also this one is not same as above
int BURGer;
5 - Java keywords cannot be used for variable name (e.g. void).
//not allowed
int void;
6 - The length of the variable can be of any length.
Naming Conventions
Naming conventions are used by the developers to understand the meaning of a variable. For example, if you wrote a code and someone else reads that code, he will be able to understand your code easier if you use naming conventions. I my self follow the given conversions when I write Java code.
The following naming conventions are good to follow when you start writing your code:
- Do not use dollar sign or underscore in the name of your variables.
- Use meaningful names.
- Use uppercase letters for the constant variables(e.g. PI = 3.14).
- If the constant has two words, use underscore to separate words (e.g. MAX_SIZE = 4).
No comments:
Post a Comment
Feel free to write any thing in your mind here 😉