Variables

   

Core Java™ 2: Volume I - Fundamentals
By Cay S. Horstmann, Gary Cornell
Table of Contents
Chapter 3.  Fundamental Programming Structures in Java


In Java, every variable has a type. You declare a variable by placing the type first, followed by the name of the variable. Here are some examples:

 double salary; int vacationDays; long earthPopulation; char yesChar; boolean done; 

Notice the semicolon at the end of each declaration. The semicolon is necessary because a declaration is a complete Java statement.

The rules for a variable name are as follows:

A variable name must begin with a letter, and must be a sequence of letters or digits. Note that the terms "letter" and "digit" are much broader in Java than in most languages. A letter is defined as 'A' 'Z', 'a' 'z', '_', or any Unicode character that denotes a letter in a language. For example, German users can use umlauts such as 'ä' in variable names; Greek speakers could use a p. Similarly, digits are '0' '9' and any Unicode characters that denote a digit in a language. Symbols like '+' or '©' cannot be used inside variable names, nor can spaces. All characters in the name of a variable are significant and case is also significant. The length of a variable name is essentially unlimited.

graphics/exclamatory_icon.gif

If you are really curious as to what Unicode characters are "letters" as far as Java is concerned, you can use the isJavaIdentifierStart and isJavaIdentifierPart methods in the Character class to check.

You also cannot use a Java reserved word for a variable name. (See Appendix I for a list of reserved words.)

You can have multiple declarations on a single line

 int i, j; // both are integers 

However, we don't recommend this style. If you define each variable separately, your programs are easier to read.

graphics/notes_icon.gif

As you saw, names are case-sensitive, for example hireday and hireDay are two separate names. In general, you should not have two names that only differ in their letter case. However, sometimes it is difficult to come up with a good name for a variable. Many programmers then give the variable the same name of the type, such as

 Box box; // ok--Box is the type and box is the variable name 

However, a better solution is to use an "a" prefix for the variable:

 Box aBox; 


       
    Top
     



    Core Java 2(c) Volume I - Fundamentals
    Building on Your AIX Investment: Moving Forward with IBM eServer pSeries in an On Demand World (MaxFacts Guidebook series)
    ISBN: 193164408X
    EAN: 2147483647
    Year: 2003
    Pages: 110
    Authors: Jim Hoskins

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net