Java Reference
In-Depth Information
presented earlier in the “Bytecode” section
of this chapter. Figure 2-9 shows the output
after executing this program in Java.
classes
In Java, all code is grouped into classes. A
class is thus a code container. The definition
of the class starts with an access modifier
( public in this case), which specifies which
classes have access to it (you will learn about
this later more extensively). This is followed
by the keyword class and the name of the
class ( BMICalculator ). Every class defini-
tion is enclosed within brackets {} . It has both variables ( weight , height , and BMI ) and methods
( BMICalculator, calculateBMI, and main ). The main method is a special method since it is the
entry point of program execution. In other words, when the class BMICalculator is run by the Java
Runtime Environment, it will start by executing the main method. Note that not every Java class
should have a main method.
figure 2-9  
identifiers.
An identiier is a name of a language element. This can be a class, variable, or method. In the
BMI example, the following are identifiers: BMICalculator , weight , height , BMI , main , and
calculateBMI . Use these naming conventions when defining identifiers:
In theory, an identifier can have an unlimited length, although practically it needs to be less
than 64k of Unicode characters and digits, but it cannot begin with a digit. Although tech-
nically it is possible to start an identifier with a currency sign ( $ ) or punctuation character
(such as _ ), it is highly discouraged since it will decrease the readability of the code.
An identifier cannot be equal to a reserved keyword, null literal, or boolean literal.
Just like C, Java is case sensitive. So the identifiers bmi , Bmi , and BMI are all different according
to Java. Hence, it is important to carefully check your spelling and capitalization. When creating
identifiers, make sure to use full words instead of abbreviations as much as possible, unless the
abbreviations can be unambiguously interpreted. This will facilitate the understanding and future
maintenance of the code. In the BMI example, it's more intuitive to work with height , weight ,
and BMI , rather than h , w , and b . Imagine if you added new functionality to the calculator that
accepted the measurement of a person's waist. It would be even more difficult to keep track of
what w meant.
Java Keywords
Table 2-4 lists the 50 keywords of Java. All these keywords have a special reserved meaning in Java
and thus cannot be used as identifiers. The BMI example uses the following keywords: public ,
class , static , void , and double .
 
Search WWH ::




Custom Search