+84 1649 660 740

Wednesday 27 August 2014

Variables 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 example:

double salary;
int vacationDays;
long earthPopulation;
boolean done;
Notice the semicolon at the end of each declaration. The semicolon is necessary because a declaration is a complete Java statement.

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 is most languages. A letter is defined as 'A'  -  'Z', 'a' - 'z', '_', '$', or any Unicode character the denotes a letter in a language. For example, German users can use umlauts such as 'ä' in variable names; Greek speakers could use a π. Similarly, digit 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.

* Note: 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.

* Note: Even though $ is a valid Java letter, you should not use it in your own code. It is intended for names that are generated by the Java compiler and other tools.

You also cannot use a Java reserved word for a variable name.

You can have multiple declarations on a single line:

 int i, j; //both are integers
However, we don'recommend this style. If you declare each variable separately, your programs are easier to read.

* Note: 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 as the type, for example:

 Box box; //"Box" is the type and "box" is the variable name
Other programmers perfer to use an "a" prefix for the variable:
 Box aBox;

0 comments:

Post a Comment