Вы находитесь на странице: 1из 27

Chapter 2.

Language Fundamentals
Exam Objectives
Identify correctly constructed package declarations, import statements, class
declarations (of all forms, including inner classes), interface declarations, method
declarations (including the main method that is used to start execution of a class),
variable declarations, and identifiers.
o For defining and using packages, see Section 4.6.
o For class declarations, see Section 4.2.
o For nested classes, see Chapter 7.
o For interface declarations, see Section 6.4.
o For method declarations, see Section 4.3.
Identify classes that correctly implement an interface where that interface is either
java.lang.Runnable or a fully specified interface in the question.
o For interface implementation, see Section 6.4.
o For implementation of java.lang.Runnable, see Section 9.3.
State the correspondence between index values in the argument array passed to a
main method and command line arguments.
o See Section 3.23.
Identify all Java programming language eywords. !ote" #here will not be any
questions regarding esoteric distinctions between eywords and manifest
constants.
State the effect of using a variable or array element of any ind, when no explicit
assignment has been made to it.
o For array elements, see Section 4..
State the range of all primitive data types, and declare literal values for String
and all primitive types using all permitted formats, bases and representations.
o See also !ppendi" #.
Supplementary Objectives
State the wrapper classes for primitive data types.
2.1 Basic Language Elements
$ie any other programming language, the Java programming language is defined by grammar
rules that specify how syntactically legal constructs can be formed using the language elements,
and by a semantic definition that specifies the meaning of syntactically legal constructs.
Lexical !"ens
#he low%level language elements are called le"ical tokens (or &ust tokens for short) and are the
building blocs for more complex constructs. Identifiers, numbers, operators, and special
characters are all examples of toens that can be used to build high%level constructs lie
expressions, statements, methods, and classes.
#denti$iers
' name in a program is called an identifier. Identifiers can be used to denote classes, methods,
variables, and labels.
In Java an identifier is composed of a sequence of characters, where each character can be either a
letter, a digit, a connecting punctuation (such as underscore _), or any currency sym$ol (such as $,
, , or ). (owever, the first character in an identifier cannot be a digit. Since Java programs are
written in the )nicode character set (see p. *+), the definitions of letter and digit are interpreted
according to this character set.
Identifiers in Java are case sensitive, for example, price and Price are two different identifiers.
Examples of Legal Identifiers:
number, Number, sum_$, bingo, $$_1, m!l, gr"#
Examples of Illegal Identifiers:
$%c&ev', all(&an)s, gran)*sum
#he name $%c&ev' is not a legal identifier as it starts with a digit. #he character ( is not a legal
character in an identifier. It is also not a legal operator so that all(&an)s cannot not be interpreted
as a legal expression with two operands. #he character * is also not a legal character in an
identifier. (owever, it is a legal operator so gran)*sum could be interpreted as a legal expression
with two operands.
%ey&!rds
%ey&ords are reserved identifiers that are predefined in the language and cannot be used to
denote other entities. 'll the eywords are in lowercase, and incorrect usage results in compilation
errors.
,eywords currently defined in the language are listed in #able *.-. In addition, three identifiers are
reserved as predefined literals in the language" the null reference and the .oolean literals true
and +alse (see #able *.*). ,eywords currently reserved, but not in use, are listed in #able *.+. 'll
these reserved words cannot be used as identifiers. #he index contains references to relevant
sections where currently defined eywords are explained.
Table 2.1. Keywords in Java
abstract )e+ault implements protecte) t&ro,
assert )o import public t&ro,s
boolean )ouble instanceo+ return transient
break else int s&ort tr'
b'te e-ten)s inter+ace static voi)
case +inal long strict+p volatile
catc& +inall' native super ,&ile
c&ar +loat ne, s,itc&

class +or package s'nc&roni.e)

continue i+ private t&is

Table 2.2. Reserved Literals in Java
null true +alse
Table 2.. Reserved Keywords not !"rrently in #se
const goto
Literals
' literal denotes a constant value, that is, the value a literal represents remains unchanged in the
program. $iterals represent numerical (integer or floating%point), character, boolean or string
values. In addition, there is the literal null that represents the null reference.
Table 2.$. Examples of Literals
Integer
/ *0
/loating%point
1.1$ *1.1$ .2 .2
0haracter
3a3 343 33 353 3*3 363
.oolean
true +alse
String
7abba7 71.1$7 7+or7 7a piece o+ t&e action7
#nteger Literals
Integer data types are comprised of the following primitive data types" int, long, b'te, and s&ort
(see Section *.*).
#he default data type of an integer literal is always int, but it can be specified as long by
appending the suffix 8 (or l) to the integer value. 1ithout the suffix, the long literals /8 and l
will be interpreted as int literals. #here is no direct way to specify a s&ort or a b'te literal.
In addition to the decimal number system, integer literals can also be specified in octal ($ase %)
and hexadecimal ($ase 19) number systems. 2ctal and hexadecimal numbers are specified with
and - (or :) prefix respectively. 3xamples of decimal, octal and hexadecimal literals are shown in
#able *.4. !ote that the leading (5ero) digit is not the uppercase letter ;. #he hexadecimal digits
from a to + can also be specified with the corresponding uppercase forms (4 to <). !egative
integers (e.g. *=) can be specified by prefixing the minus sign (*) to the magnitude of the integer
regardless of number system (e.g., *11/ or *:24). !umber systems and number representation
are discussed in 'ppendix 6. Java does not support literals in binary notation.
Table 2.%. Examples of &e'imal( )'tal( and *exade'imal Literals
&e'imal )'tal *exade'imal
% 1 -%
18 1/8 :a8
19 / -1
/0 11 -1>
=8 11/8 -2a8
*= *11/ *:24
/1$0$%19$0 (i.e., *
+-
*1)
10000000000 -0+++++++
*/1$0$%19$% (i.e., %*
+-
)
*/ *-%
11/2%===9%$/9/$8 (i.e., *
47
)
$8 -$8
Fl!ating'p!int Literals
/loating%point data types come in two flavors" +loat or )ouble.
#he default data type of a floating%point literal is )ouble, but it can be explicitly designated by
appending the suffix ? (or )) to the value. ' floating%point literal can also be specified to be a
+loat by appending the suffix < (or +).
/loating%point literals can also be specified in scientific notation, where @ (or e) stands for
'"ponent. /or example, the )ouble literal 1=$.=@*/ in scientific notation is interpreted as
1=$.=A1
*/
(i.e., 1.=$=).
Examples of double Literals
. .) ?
.$= .$= .$=?
$=. $=. $=?
$.=@B1 $.=@B1? $.=e1) $=e*/ .$=@/
Examples of float Literals
.< +
.$=< .$=<
$=.< $=.< $=<
$.=@B1< $=e*/+ .$=@/<
!ote that the decimal point and the exponent are optional and that at least one digit must be
specified.
B!!lean Literals
#he primitive data type boolean represents the truth%values true or false that are denoted by the
reserved literals true or +alse, respectively.
Character Literals
' character literal is quoted in single%quotes (3). 'll character literals have the primitive data type
c&ar.
0haracters in Java are represented by the -8%bit )nicode character set, which subsumes the 9%bit
IS2%$atin%- and the :%bit 'S0II characters. In #able *.8, note that digits ( to =), upper%case
letters (4 to C), and lower%case letters (a to .) have contiguous )nicode values. 'ny )nicode
character can be specified as a four%digit hexadecimal number (i.e., -8 bits) with the prefix Du.
Table 2.+. Examples of #ni'ode ,al"es
!-ara'ter Literal !-ara'ter Literal "sing #ni'ode val"e !-ara'ter
3 3 3Du/3 Space
33 3Du13
313 3Du113 1
3=3 3Du1=3 =
343 3Du$13 4
Table 2.+. Examples of #ni'ode ,al"es
!-ara'ter Literal !-ara'ter Literal "sing #ni'ode val"e !-ara'ter
3>3 3Du$/3 >
3C3 3Du2a3 C
3a3 3Du913 a
3b3 3Du9/3 b
3.3 3Du0a3 .
3E3 3Du%$3 E
3!3 3Du%c3 !
3#3 3Dua03 #
Es'ape .e/"en'es
0ertain escape se(uences define special character values as shown in #able *.:. #hese escape
sequences can be single%quoted to define character literals. /or example, the character literals 3Dt3
and 3Du=3 are equivalent. (owever, the character literals ;Dua3 and ;Du)3 should not be
used to represent newline and carriage return in the source code. #hese values are interpreted as
line%terminator characters by the compiler, and will cause compile time errors. 2ne should use the
escape sequences 3Dn3 and 3Dr3, respectively, for correct interpretation of these characters in the
source code.
Table 2.0. Es'ape .e/"en'es
Es'ape .e/"en'e #ni'ode ,al"e !-ara'ter
Db Du%
.acspace (.S)
Table 2.0. Es'ape .e/"en'es
Es'ape .e/"en'e #ni'ode ,al"e !-ara'ter
Dt Du=
(ori5ontal tab ((# or #'.)
Dn Dua
$inefeed ($/) a..a., !ewline (!$)
D+ Duc
/orm feed (//)
Dr Du)
0arriage return (0<)
D3 Du/0
'postrophe%quote
D7 Du//
=uotation mar
DD Du2c
.acslash
1e can also use the escape sequence Dddd to specify a character literal by octal value, where each
digit d can be any octal digit (>0), as shown in #able *.9. #he number of digits must be three or
fewer, and the octal value cannot exceed D100, that is, only the first *48 characters can be
specified with this notation.
Table 2.1. Examples of Es'ape .e/"en'e \ddd
Es'ape .e/"en'e \ddd !-ara'ter Literal
3D1$13 3a3
3D$93 3F3
3D93 33
String Literals
' string literal is a sequence of characters, which must be quoted in quotation mars and which
must occur on a single line. 'll string literal are ob&ects of the class String (see Section -7.4, p.
?7:).
3scape sequences as well as )nicode values can appear in string literals"
7Gere comes a tab.Dt 4n) &ere comes anot&er oneDu=H I16
7J&at3s on t&e menuK7 I/6
7D7String literals are )ouble*Luote).D77 I16
78e+tHDnRig&tH7 I$6
In (-), the tab character is specified using the escape sequence and the )nicode value respectively.
In (*), the single apostrophe need not be escaped in strings, but it would be if specified as a
character literal(3D33). In (+), the double apostrophes in the string must be escaped. In (?), we
use the escape sequence Dn to insert a newline. @rinting these strings would give the following
result"
Gere comes a tab. 4n) &ere comes anot&er one H
J&at3s on t&e menuK
7String literals are )ouble*Luote).7
8e+tH
Rig&tH
2ne should also use the string literals 7Dn7 and 7Dr7, respectively, for correct interpretation of the
characters ADua7 and ADu)7 in the source code.
(hite Spaces
' &hite space is a sequence of spaces, tabs, form feeds, and line terminator characters in a Java
source file. $ine terminators can be newline, carriage return, or carriage return%newline sequence.
' Java program is a free%format sequence of characters that is tokeni)ed by the compiler, that is,
broen into a stream of toens for further analysis. Separators and operators help to distinguish
toens, but sometimes white space has to be inserted explicitly as separators. /or example, the
identifier classRoom will be interpreted as a single toen, unless white space is inserted to
distinguish the eyword class from the identifier Room.
1hite space aids not only in separating toens, but also in formatting the program so that it is easy
for humans to read. #he compiler ignores the white spaces once the toens are identified.
C!mments
' program can be documented by inserting comments at relevant places. #hese comments are for
documentation purposes and are ignored by the compiler.
Java provides three types of comments to document a program"
' single%line comment" MM ... to t&e en) o+ t&e line
' multiple%line comment" MA ... AM
' documentation (Javadoc) comment" MAA ... AM
.ingle2line !omment
'll characters after the comment%start sequence MM through to the end of the line constitute a
single*line comment.
MM N&is comment en)s at t&e en) o+ t&is line.
int ageO MM <rom comment*start seLuence to t&e en) o+ t&e line is a comment.
3"ltiple2line !omment
' multiple*line comment, as the name suggests, can span several lines. Such a comment starts
with MA and ends with AM.
MA 4 comment
on several
lines.
AM
#he comment%start sequences (MM, MA, MAA) are not treated differently from other characters when
occurring within comments, and are thus ignored. #his means trying to nest multiple%line
comments will result in compile time error"
MA <ormula +or alc&em'.
gol) P ,i.ar).makeQol)Istone6O
MA >ut it onl' ,orks on Sun)a's. AM
AM
#he second occurrence of the comment%start sequence MA is ignored. #he last occurrence of the
sequence AM in the code is now unmatched, resulting in a syntax error.
&o'"mentation !omment
' documentation comment is a special%purpose comment that when placed before class or class
member declarations can be extracted and used by the java)oc tool to generate (#B$
documentation for the program. Cocumentation comments are usually placed in front of classes,
interfaces, methods and field definitions. 6roups of special tags can be used inside a
documentation comment to provide more specific information. Such a comment starts with MAA and
ends with AM"
MAA
A N&is class implements a gi.mo.
A (aut&or R.4.S.
A (version /.
AM
/or details on the java)oc tool, see the documentation for the tools in the Java * SC,.
)evie& *uesti!ns
2.11hich of the following is not a legal identifierD
Select the one correct answer.
a. a/.
b. T)ipus
c. 2/pickup
d. _class
e. ca$&
f. totalU
2.21hich statement is trueD
Select the one correct answer.
a. ne, and )elete are eywords in the Java language.
b. tr', catc&, and t&ro,n are eywords in the Java language.
c. static, unsigne), and long are eywords in the Java language.
d. e-it, class, and ,&ile are eywords in the Java language.
e. return, goto, and )e+ault are eywords in the Java language.
f. +or, ,&ile, and ne-t are eywords in the Java language.
2.Is this a complete and legal commentD
MA MM AM
Select the one correct answer.
a. !o, the bloc comment (MA ... AM6 is not ended since the single%line comment (MM ...)
comments out the closing part.
b. It is a completely valid comment. #he MM part is ignored by the compiler.
c. #his combination of comments is illegal and the compiler will re&ect it.
2.2 +rimitive ,ata ypes
/igure *.- gives an overview of the primitive data types in Java.
4ig"re 2.1. 5rimitive &ata Types in Java
@rimitive data types in Java can be divided into three main categories"
+ntegral typesE represent signed integers (b'te, s&ort, int, long) and unsigned character
values (c&ar)
Floating*point types (+loat, )ouble)E represent fractional signed numbers
,oolean type (boolean)E represent logical values
@rimitive data values are not ob&ects. 3ach primitive data type defines the range of values in the
data type, and operations on these values are defined by special operators in the language (see
0hapter +).
3ach primitive data type also has a corresponding &rapper class that can be used to represent a
primitive value as an ob&ect. 1rapper classes are discussed in Section -7.+.
#nteger ypes
Table 2.6. Range of Integer ,al"es
&ata Type 7idt- 8bits9 3inim"m val"e 3I:;,<L#E 3axim"m val"e 3<=;,<L#E
b'te %
*/
:
I*1/%6 /
:
*1 IB1/06
s&ort 19
*/
-4
I*1/09%6 /
-4
*1 IB1/0906
int 1/
*/
+-
I*/1$0$%19$%6 /
+-
*1 IB/1$0$%19$06
Table 2.6. Range of Integer ,al"es
&ata Type 7idt- 8bits9 3inim"m val"e 3I:;,<L#E 3axim"m val"e 3<=;,<L#E
long 9$
*/
8+
I*=//110/19%2$002%%86 /
8+
*1 IB=//110/19%2$002%086
Integer data types are b'te, s&ort, int, and long (see #able *.F). #heir values are signed integers
represented by *;s complement (see Section 6.?, p. 4F9).
Character ype
Table 2.1>. Range of !-ara'ter ,al"es
&ata Type 7idt- 8bits9 3inim"m #ni'ode val"e 3axim"m #ni'ode val"e
c&ar 19 - IDu6 -++++ IDu++++6
0haracters are represented by the data type c&ar (see #able *.-7). #heir values are unsigned
integers that denote all the 844+8 (*
-8
) characters in the -8%bit )nicode character set. #his set
includes letters, digits, and special characters.
#he first -*9 characters of the )nicode set are the same as the -*9 characters of the :%bit 'S0II
character set, and the first *48 characters of the )nicode set correspond to the *48 characters of
the 9%bit IS2 $atin%- character set.
Fl!ating'p!int ypes
Table 2.11. Range of 4loating2point ,al"es
&ata
Type
7idt-
8bits9
3inim"m 5ositive ,al"e
3I:;,<L#E
3axim"m 5ositive ,al"e
3<=;,<L#E
+loat 1/ 1.$1/=%$9$1/$%10@*$2+ 1.$/%/1$0991%2/%%9eB1%+
)ouble 9$ $.=$929$2%$1/$92$$e*1/$ 1.0=09=111$%9/1120eB1%
/loating%point numbers are represented by the +loat and )ouble data types.
/loating%point numbers conform to the I333 :4?%-F94 binary floating%point standard. #able *.--
shows the range of values for positive floating%point numbers, but these apply equally to negative
floating%point numbers with the 3*3 sign as prefix. Gero can be either . or *..
Since the si5e for representation is finite, certain floating%point numbers can only be represented as
approximations. /or example, the value of the expression I1.M1.6 is represented as an
approximation due to the finite number of bits used.
B!!lean ype
Table 2.12. ?oolean ,al"es
&ata Type 7idt- Tr"e ,al"e Literal 4alse ,al"e Literal
boolean
not applicable
true +alse
#he data type boolean represents the two logical values denoted by the literals true and +alse
(see #able *.-*).
.oolean values are produced by all relational (see Section +.F), conditional (see Section +.-*) and
$oolean logical operators (see Section +.--), and are primarily used to govern the flow of control
during program execution.
#able *.-+ summari5es the pertinent facts about the primitive data types" their width or si5e, which
indicates the number of the bits required to store a primitive valueH their range (of legal values),
which is specified by the minimum and the maximum values permissibleH and the name of the
corresponding wrapper class.
Table 2.1. ."mmary of 5rimitive &ata Types
&ata
Type
7idt-
8bits9
3inim"m ,al"e( 3axim"m ,al"e 7rapper
!lass
boolean
not
applicable
true, +alse (no ordering implied)
>oolean
b'te %
%*
:
, *
:
%-
>'te
s&ort 19
%*
-4
, *
-4
%-
S&ort
Table 2.1. ."mmary of 5rimitive &ata Types
&ata
Type
7idt-
8bits9
3inim"m ,al"e( 3axim"m ,al"e 7rapper
!lass
c&ar 19
-, -++++
V&aracter
int 1/
%*
+-
, *
+-
%-
Wnteger
long 9$
%*
8+
, *
8+
%-
8ong
+loat 1/
I1.$1/=%$9$1/$%100e*$2+,
I1.$/%/1$0991%2/%%9eB1%+
<loat
)ouble 9$
J;b-$.=$929$2%$1/$92$$e*
1/$, J;b-1.0=09=111$%9/1120eB1%
?ouble
)evie& *uesti!ns
2.$1hich of the following do not denote a primitive data value in JavaD
Select the two correct answers.
a. 7t7
b. 3k3
c. 2.2<
d. 7&ello7
e. +alse
2.%1hich of the following primitive data types are not integer typesD
Select the three correct answers.
a. #ype boolean
b. #ype b'te
c. #ype +loat
d. #ype s&ort
e. #ype )ouble
2.+1hich integral type in Java has the exact range from %/1$0$%19$% I*/
+-
6 to /1$0$%19$0 I/
+-
*
16, inclusiveD
Select the one correct answer.
a. #ype b'te
b. #ype s&ort
c. #ype int
d. #ype long
e. #ype c&ar
2.- .ariable ,eclarati!ns
' -aria$le stores a value of a particular type. ' variable has a name, a type, and a value associated
with it. In Java, variables can only store values of primitive data types and references to ob&ects.
Kariables that store references to ob&ects are called reference -aria$les.
,eclaring and #nitiali/ing .ariables
Kariable declarations are used to specify the type and the name of variables. #his implicitly
determines their memory allocation and the values that can be stored in them. 1e show some
examples of declaring variables that can store primitive values"
c&ar a, b, cO MM a, b an) c are c&aracter variables.
)ouble areaO MM area is a +loating*point variable.
boolean +lagO MM +lag is a boolean variable.
#he first declaration above is equivalent to the following three declarations"
c&ar aO
c&ar bO
c&ar cO
' declaration can also include initiali5ation code to specify an appropriate initial value for the
variable"
int i P 1, MM i is an int variable ,it& initial value 1.
j P 11O MM j is an int variable ,it& initial value 11.
long big P /1$0$%19$%8O MM big is a long variable ,it& speci+ie) initial value.
Object )e$erence .ariables
'n o$.ect reference is a value that denotes an ob&ect in Java. Such reference values can be stored
in variables and used to manipulate the ob&ect denoted by the reference value.
' variable declaration that specifies a reference type (i.e., a class, an array, or an interface name)
declares an ob&ect reference variable. 'nalogous to the declaration of variables of primitive data
types, the simplest form of reference variable declaration only specifies the name and the reference
type. #he declaration determines what ob&ects a reference variable can denote. .efore we can use
a reference variable to manipulate an ob&ect, it must be declared and initiali5ed with the reference
value of the ob&ect.
Pi..a 'umm'Pi..aO MM Xariable 'umm'Pi..a can re+erence objects o+ class Pi..a.
Gamburger big;ne, MM Xariable big;ne can re+erence objects o+ class Gamburger,
small;neO MM an) so can variable small;ne.
It is important to note that the declarations above do not create any ob&ects of class Pi..a or
Gamburger. #he declarations only create variables that can store references to ob&ects of these
classes.
' declaration can also include an initiali5er to create an ob&ect whose reference can be assigned to
the reference variable"
Pi..a 'umm'Pi..a P ne, Pi..aI7GotFSpic'76O MM ?eclaration ,it& initiali.er.
#he reference variable 'umm'Pi..a can reference ob&ects of class Pi..a. #he eyword ne,,
together with the constructor call Pi..aI7GotFSpic'76, creates an ob&ect of class Pi..a. #he
reference to this ob&ect is assigned to the variable 'umm'Pi..a. #he newly created ob&ect of class
Pi..a can now be manipulated through the reference stored in this variable.
+nitiali)ers for initiali5ing fields in ob&ects, classes, and interfaces are discussed in Section 9.*.
<eference variables for arrays are discussed in Section ?.-.
Li$etime !$ .ariables
$ifetime of a variable, that is, the time a variable is accessible during execution, is determined by
the context in which it is declared. 1e distinguish between lifetime of variables in three contexts"
+nstance -aria$lesE members of a class and created for each ob&ect of the class. In other
words, every ob&ect of the class will have its own copies of these variables, which are local
to the ob&ect. #he values of these variables at any given time constitute the state of the
ob&ect. Instance variables exist as long as the ob&ect they belong to exists.
Static -aria$lesE also members of a class, but not created for any ob&ect of the class and,
therefore, belong only to the class (see Section ?.-7, p. -??). #hey are created when the
class is loaded at runtime, and exist as long as the class exists.
/ocal -aria$les (also called method automatic -aria$les)E declared in methods and in
blocs and created for each execution of the method or bloc. 'fter the execution of the
method or bloc completes, local (non%+inal) variables are no longer accessible.
2.0 #nitial .alues $!r .ariables
,e$ault .alues $!r Fields
Cefault values for fields of primitive data types and reference types are listed in #able *.-?. #he
value assigned depends on the type of the field.
Table 2.1$. &efa"lt ,al"es
&ata Type &efa"lt ,al"e
boolean +alse
c&ar 3Du3
Integer (b'te, s&ort, int, long) 8 for long, for others
/loating%point (+loat, )ouble) .< or .?
<eference types
null
If no initiali5ation is provided for a static variable either in the declaration or in a static initiali5er
bloc (see Section 9.*, p. ++8), it is initiali5ed with the default value of its type when the class is
loaded.
Similarly, if no initiali5ation is provided for an instance variable either in the declaration or in an
instance initiali5er bloc (see Section 9.*, p. ++9), it is initiali5ed with the default value of its type
when the class is instantiated.
#he fields of reference types are always initiali5ed with the null reference value, if no initiali5ation
is provided.
3xample *.- illustrates default initiali5ation of fields. !ote that static variables are initiali5ed when
the class is loaded the first time, and instance variables are initiali5ed accordingly in e-ery ob&ect
created from the class 8ig&t.
Example 2.1 &efa"lt ,al"es for 4ields
public class 8ig&t Y
MM Static variable
static int counterO MM ?e+ault value ,&en class is loa)e).
MM Wnstance variables
int no;+Jatts P 1O MM @-plicitl' set to 1.
boolean in)icatorO MM Wmplicitl' set to )e+ault value +alse.
String locationO MM Wmplicitl' set to )e+ault value null.
public static voi) mainIStringZ[ args6 Y
8ig&t bulb P ne, 8ig&tI6O
S'stem.out.printlnI7Static variable counter5 7 B 8ig&t.counter6O
S'stem.out.printlnI7Wnstance variable no;+Jatts5 7 B bulb.no;+Jatts6O
S'stem.out.printlnI7Wnstance variable in)icator5 7 B bulb.in)icator6O
S'stem.out.printlnI7Wnstance variable location5 7 B bulb.location6O
returnO
\
\
2utput from the program"
Static variable counter5
Wnstance variable no;+Jatts5 1
Wnstance variable in)icator5 +alse
Wnstance variable location5 null
#nitiali/ing L!cal .ariables !$ +rimitive ,ata ypes
$ocal variables are not initiali5ed when they are created at method invocation, that is, when the
execution of a method is started. #hey must be explicitly initiali5ed before being used. #he compiler
will report attempts to use uninitiali5ed local variables.
Example 2.2 4lagging #ninitiali@ed Lo'al ,ariables of 5rimitive &ata Types
public class NooSmartVlass Y
public static voi) mainIStringZ[ args6 Y
int ,eig&t P 1, t&ePriceO MM 8ocal variables
i+ I,eig&t ] 16 t&ePrice P 1O
i+ I,eig&t ^ 26 t&ePrice P 2O
i+ I,eig&t ^P 16 t&ePrice P ,eig&tA1O MM 4l,a's e-ecute).
S'stem.out.printlnI7N&e price is5 7 B t&ePrice6O MM I16
\
\
In 3xample *.*, the compiler complains that the local variable t&ePrice used in the println
statement at (-) may not be initiali5ed. (owever, it can be seen that at runtime the local variable
t&ePrice will get the value 1 in the last i+%statement, before it is used in the println
statement. #he compiler does not perform a rigorous analysis of the program in this regard. It only
compiles the body of a conditional statement if it can deduce the condition to be true. #he
program will compile correctly if the variable is initiali5ed in the declaration, or if an unconditional
assignment is made to the variable. <eplacing the declaration of the local variables in 3xample *.*
with the following declaration solves the problem"
int ,eig&t P 1, t&ePrice P O MM >ot& local variables initiali.e).
#nitiali/ing L!cal )e$erence .ariables
$ocal reference variables are bound by the same initiali5ation rules as local variables of primitive
data types.
Example 2. 4lagging #ninitiali@ed Lo'al Referen'e ,ariables
public class Xer'SmartVlass Y
public static voi) mainIStringZ[ args6 Y
String importantSessageO MM 8ocal re+erence variable
S'stem.out.printlnI7N&e message lengt& is5 7 B importantSessage.lengt&I66O
\
\
In 3xample *.+, the compiler complains that the local variable importantSessage used in the
println statement may not be initiali5ed. If the variable importantSessage is set to the value
null, the program will compile. (owever, at runtime, a NullPointer@-ception will be thrown
since the variable importantSessage will not denote any ob&ect. #he golden rule is to ensure that a
reference variable, whether local or not, is assigned a reference to an ob&ect before it is used, that
is, ensure that it does not have the value null. #he program compiles and runs if we replace the
declaration with the following declaration, which creates a string literal and assigns its reference to
the local reference variable importantSessage"
String importantSessage P 7Wnitiali.e be+ore useH7O
'rrays and their default values are discussed in Section ?.- on page -7-.
)evie& *uesti!ns
2.01hich of the following
lines are valid
declarationsD
Select the three
correct answers.
a. c&ar a P
3Du913O
b. c&ar 3a3 P
3a3O
c. c&ar Du91
P 3a3O
d. c&Du91r a
P 3a3O
e. c&3a3r a P
3a3O
2.16iven the following
code within a method,
which statement is
trueD
int a, bO
b P 2O
Select the one correct
answer.
a. $ocal variable
a is not
declared.
b. $ocal variable
b is not
declared.
c. $ocal variable
a is declared
but not
initiali5ed.
d. $ocal variable
b is declared
but not
initiali5ed.
e. $ocal variable
b is initiali5ed
but not
declared.
2.6In which of these
variable declarations
will the variable
remain uninitiali5ed
unless explicitly
initiali5edD
Select the one correct
answer.
a. Ceclaration of
an instance
variable of
type int.
b. Ceclaration of
a static
variable of
type +loat.
c. Ceclaration of
a local variable
of type +loat.
d. Ceclaration of
a static
variable of
type ;bject.
e. Ceclaration of
an instance
variable of
type intZ[.
2.1 2ava S!urce File Structure
#he structure of a seletal Java source file is depicted in /igure *.*. ' Java
source file can have the following elements that, if present, must be
specified in the following order"
-. 'n optional package declaration to specify a pacage name. @acages
are discussed in Section ?.8.
*. Gero or more import declarations. Since import declarations
introduce class and interface names in the source code, they must be
placed before any type declarations. #he import statement is
discussed in Section ?.8.
+. 'ny number of top*le-el class and interface declarations. Since these
declarations belong to the same pacage, they are said to be defined
at the top le-el, which is the pacage level.
#he classes and interfaces can be defined in any order. 0lass and
interface declarations are collectively nown as type declarations.
#echnically, a source file need not have any such definitions, but that
is hardly useful.
#he Java * SC, imposes the restriction that at the most one public
class definition per source file can be defined. If a public class is
defined, the file name must match this public class. If the public
class name is Ne,4pp, then the file name must be Ne,4pp.java.
0lasses are discussed in Section ?.*, and interfaces are discussed in
Section 8.?.
4ig"re 2.2. Java .o"r'e 4ile .tr"'t"re
!ote that except for the package and the import statements, all code is
encapsulated in classes and interfaces. !o such restriction applies to
comments and white space.
)evie& *uesti!ns
2.1>1hat will be the result of attempting to compile this classD
import java.util.AO
package com.acme.toolkitO
public class 4Vlass Y
public ;t&er anWnstanceO
\
class ;t&er Y
int valueO
\
Select the one correct answer.
a. #he class will fail to compile, since the class ;t&er has not yet been declared when
referenced in class 4Vlass.
b. #he class will fail to compile, since import statements must never be at the very top of
a file.
c. #he class will fail to compile, since the package declaration can never occur after an
import statement.
d. #he class will fail to compile, since the class ;t&er must be defined in a file called
;t&er.java.
e. #he class will fail to compile, since the class ;t&er must be declared public.
f. #he class will compile without errors.
2.11Is an empty file a valid source fileD
'nswer true or false.
2.3 he main() 4eth!d
#he mechanics of compiling and running Java applications using the Java * SC, are outlined in
Section -.-7. #he Java interpreter executes a method called main in the class specified on the
command line. 'ny class can have a mainI6 method, but only the mainI6 method of the class
specified to the Java interpreter is executed to start a Java application.
#he mainI6 method must have public accessibility so that the interpreter can call it (see Section
?.F, p. -+9). It is a static method belonging to the class, so that no ob&ect of the class is required
to start the execution (see Section ?.-7, p. -??). It does not return a value, that is, it is declared
voi) (see Section 4.?, p. -:8). It always has an array of String ob&ects as its only formal
parameter. #his array contains any arguments passed to the program on the command line (see
Section +.*+, p. F4). 'll this adds up to the following definition of the mainI6 method"
public static voi) mainIStringZ[ args6 Y
MM ...
\
#he above requirements do not exclude specification of additional modifiers (see Section ?.-7, p.
-??) or any t&ro,s clause (see Section 4.F, p. *7-). #he mainI6 method can also be overloaded
lie any other method (see p. --8). #he Java interpreter ensures that the mainI6 method, that
complies with the above definition is the starting point of the program execution.
)evie& *uesti!ns
2.121hich of these are valid declarations of the mainI6 method in order to start the execution of a
Java applicationD
Select the two correct answers.
a. static voi) mainIStringZ[ args6 Y MA ... AM \
b. public static int mainIStringZ[ args6 Y MA ... AM \
c. public static voi) mainIString args6 Y MA ... AM \
d. +inal public static voi) mainIStringZ[ arguments6 Y MA ... AM \
e. public int mainIStringsZ[ args, int argc6 Y MA ... AM \
f. static public voi) mainIString argsZ[6 Y MA ... AM \
2.11hich of the following are reserved eywordsD
Select the three correct answers.
a. public
b. static
c. voi)
d. main
e. String
f. args
Chapter Summary
#he following topics were discussed in this chapter"
basic language elements" identifiers, eywords, literals, white spaces, and comments
primitive data types" integral, floating%point, and .oolean
converting numbers between decimal, octal, and hexadecimal systems
lifetime of fields and local variables
declaration and initiali5ation of variables, including reference variables
usage of default values for fields
structure of a valid Java source file
declaration of the mainI6 method whose execution starts the application
+r!gramming Exercises
2.1#he following program has several errors. Bodify it so that it will compile and run without errors.
(See Section ?.8 on page -*F for compiling and running code from pacages.)
import java.util.AO
package com.acmeO
public class @-ercise1 Y
int counterO
voi) mainIStringZ[ args6 Y
@-ercise1 instance P ne, @-ercise1I6O
instance.goI6O
\
public voi) goI6 Y
int sumO
int i P O
,&ile Ii]16 Y
i+ Ii PP 6 sum P 1O
sum P sum B iO
iBBO
\
S'stem.out.printlnIsum6O
\
\
2.2#he following program has several errors. Bodify it so that it will compile and run without errors.
MM <ilename5 Nemperature.java
P_>8WV V84SS temperature Y
P_>8WV voi) mainIstring args6 Y
)ouble +a&ren&eit P 9/.2O
AM Vonvert MA
)ouble celsius P +/cI+a&ren&eit6O
S'stem.out.printlnI+a&ren&eit B 3< P 3 B celsius B 3V36O
\
)ouble +/cI+loat +a&r6 Y
R@N_RN I+a&r * 1/6 A 2 M =O
\
\

Вам также может понравиться