Tuesday, July 23, 2013

Naming Your Variables

The name that you choose for a variable, or indeed the name that you choose for anything in Java, is called an identifier. An identifier can be any length, but it must start with a letter, an underscore (_), or a dollar sign ($). The rest of an identifier can include any characters except those used as operators in Java (such as +, –, or *), but you will be generally better off if you stick to letters, digits, and the underscore character.

Java is case-sensitive, so the names republican and Republican are not the same. You must not include blanks or tabs in the middle of a name, so Betty May is out but you could have BettyMay or even Betty_May. Note that you can’t have 6Pack as a name since you cannot start a name with a numeric digit. Of course, you could use sixPack as an alternative.

Subject to the restrictions I have mentioned, you can name a variable almost anything you like, except for two additional restraints - you can’t use keywords in Java as a name for something, and a name can’t be anything that could be interpreted as a constant value - as a literal, in other words. Keywords are words that are an essential part of the Java language. You saw some keywords in the previous chapter,and you will learn a few more in this chapter. If you’d like to know what they all are now, see the complete list in Appendix A. The restriction on constant values is there because, although it is obvious why a name can’t be 1234 or 37.5, constants can also be alphabetic, such as true and false, for example,which are literals of type boolean. Of course, the basic reason for these rules is that the compiler has to be able to distinguish between your variables and other things that can appear in a program. If you try to use a name for a variable that makes this impossible, then it’s not a legal name.

No comments:

Post a Comment

Thanks for Commenting......