📄 ch5.htm
字号:
<P>Although the special characters in Table 5.1 are represented bytwo symbols, the first of which is always a backslash, you stilluse them as single characters. For example, to define a <TT>char</TT>variable as a backspace character, you might write something likethe following in your Java program:<BLOCKQUOTE><PRE>char backspace = '\b';</PRE></BLOCKQUOTE><P>When Java's compiler sees the backslash, it knows that it's aboutto encounter a special character of some type. The symbol followingthe backslash tells the compiler which special character to use.Because the backslash is used to signify a special character,when you want to specify the backslash character yourself, youmust use two backslashes, which keeps the compiler from gettingconfused. Other special characters that might confuse the compilerbecause they are used as part of the Java language are singleand double quotes. When you want to use these characters in yourprogram's data, you must also precede them with a backslash.<H3><A NAME="BooleanValues">Boolean Values</A></H3><P>Many times in a program, you need a way to determine if a specificcondition has been met. For example, you might need to know whethera part of your program executed properly. In such cases, you canuse Boolean values, which are represented in Java by the <TT>boolean</TT>data type. Boolean values are unique in that they can be onlyone of two possible values: true or false. You declare a <TT>boolean</TT>value like this:<BLOCKQUOTE><PRE>boolean identifier;</PRE></BLOCKQUOTE><P>or<BLOCKQUOTE><PRE>boolean identifier = value;</PRE></BLOCKQUOTE><P>In the second example, value must be <TT>true</TT> or <TT>false</TT>.In an actual program, you might write something like this:<BLOCKQUOTE><PRE>boolean file_okay = true;</PRE></BLOCKQUOTE><P>Boolean values are often used in <TT>if</TT> statements, whichenable you to do different things depending on the value of avariable. You'll learn about <TT>if</TT> statements in Chapter9, "The <TT>if</TT> and <TT>switch</TT> Statements."<P>Table 5.2 summarizes Java's various data types. Take some timenow to look over the table and make sure you understand how thedata types differ from each other. You might also want to thinkof ways you might use each data type in an actual program.<BR><P><CENTER><B>Table 5.2 Summary of Java's Data Types.</B></CENTER><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD WIDTH=109><I><B>Type</B></I></TD><TD WIDTH=378><I><B>Value</B></I></TD></TR><TR VALIGN=TOP><TD WIDTH=109>byte</TD><TD WIDTH=378>-128 to 127</TD></TR><TR VALIGN=TOP><TD WIDTH=109>short</TD><TD WIDTH=378>-32,768 to 32,767</TD></TR><TR VALIGN=TOP><TD WIDTH=109>int</TD><TD WIDTH=378>-2,147,483,648 to 2,147,483,647</TD></TR><TR VALIGN=TOP><TD WIDTH=109>long</TD><TD WIDTH=378>Huge</TD></TR><TR VALIGN=TOP><TD WIDTH=109>float</TD><TD WIDTH=378>-3.402823e38 to 3.402823e38</TD></TR><TR VALIGN=TOP><TD WIDTH=109>double</TD><TD WIDTH=378>-1.79769313486232e308 to 1.79769313486232e308</TD></TR><TR VALIGN=TOP><TD WIDTH=109>char</TD><TD WIDTH=378>Symbols used in text</TD></TR><TR VALIGN=TOP><TD WIDTH=109>boolean</TD><TD WIDTH=378>True or false</TD></TR></TABLE></CENTER><P><H2><A NAME="VariableScope"><FONT SIZE=5 COLOR=#Ff0000>Variable Scope</FONT></A></H2><P>When you write your Java programs, you can't just declare yourvariables willy-nilly all over the place. You first have to considerhow and where you need to use the variables. This is because variableshave an attribute known as scope, which determines where in yourprogram variables can be accessed. In Java, a variable's scopeis determined by the program block in which the variable firstappears. The variable is "visible" to the program onlyfrom the beginning of its program block to the end of the programblock. When a program's execution leaves a block, all the variablesin the block disappear, a phenomenon that programmers call "goingout of scope."<P>Now you're probably wondering, "What the devil is a programblock?" Generally, a program block is a section of programcode that starts with an opening curly brace ({) and ends witha closing curly brace (}). (Sometimes, the beginning and endingof a block are not explicitly defined, but you don't have to worryabout that just yet.) Specifically, program blocks include thingslike classes, functions, and loops, all of which you'll learnabout later in this book.<P>Of course, things aren't quite as simple as all that (you're dealingwith computers, after all). The truth is that you can have programblocks within other program blocks. When you have one block insideanother, the inner block is considered to be nested. Figure 5.1illustrates the concept of nested program blocks.<P><A HREF="f5-1.gif"><B> Figure 5.1 : </B><I>Program blocks can be nested inside other program blocks.</I></A><P><P>In the figure, Block 1 encloses both Block 2 and Block 3. Thatis, Block 2 and Block 3 are nested within Block 1, because theseblocks occur after Block 1's opening brace but before Block 1'sclosing brace. If you wanted, you could also create a Block 4and nest it within Block 2 or Block 3, and thus create even anotherlevel of nesting. As you'll see when you start writing full-lengthJava programming, all programs have a lot of nesting going on.<P>The ability to nest program blocks adds a wrinkle to the ideaof variable scope. Because a variable remains in scope from thebeginning of its block to the end of its block, such a variableis also in scope in any blocks that are nested in the variable'sblock. For example, looking back at Figure 5.1, a variable that'sdefined in Block 1 is accessible in not just Block 1, but alsoin Block 2 and Block 3. However, a variable defined inside Block2 is accessible only in Block 2, because such a variable goesinto scope at the start of Block 2 and goes out of scope at theend of Block 2. If you're a little confused, the following exampleought to clear things up.<H3><A NAME="ExampleDeterminingaVariablesScope">Example: Determining a Variable's Scope</A></H3><P>Suppose you've written the small Java program shown in Listing5.3. (Nevermind, at this point, that you don't know much aboutwriting Java programs. Such minor details will be remedied bythe time you complete this book.) The program shown in the listingfollows the same program structure as that shown in Figure 5.1.That is, there is one large main block that contains two nestedblocks. The main block begins with the opening brace on the secondline and ends with the closing brace at the end of the program.The first inner block begins with the opening brace after theline labeling <TT>Function1</TT> and ends with the closing bracethree lines below the opening brace. The second inner block isdefined similarly, with its own opening and closing braces.<HR><BLOCKQUOTE><B>Listing 5.3 LST5_3.TXT: Determining Variable Scope.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>public class Block1 extends Applet{ int value1 = 32; void Block2() { float value2 = 4.5f; value1 = 45; } void Block3() { value1 = 100; // The following line causes an error. value2 = 55.46f; }}</PRE></BLOCKQUOTE><HR><P>Now look at the variables being used in this program. The firstvariable defined in the program is <TT>value1</TT>, which is foundright after the main block's opening brace. This means that <TT>value1</TT>is accessible in all three blocks, as you can see by looking atthe <TT>Block2</TT> and <TT>Block3</TT> blocks, both of whichassign new values to <TT>value1</TT>.<P>The second variable in the program, <TT>value2</TT>, is definedinside the <TT>Block2</TT> block, where it's both declared andassigned the value 4.5f. In the <TT>Block3</TT> block, the programtries to assign a value to <TT>value2</TT>. If you tried to compilethis program, you'd see that this line creates an error message,as shown in Figure 5.2. In the figure, the compiler is insistingthat <TT>value2</TT> in the <TT>Block3</TT> block is undefined,which, of course, is true as far as the <TT>Block3</TT> blockis concerned. You'd get a similar message if you tried to access<TT>value2</TT> anywhere but within the scope of the <TT>Block2</TT>block.<P><A HREF="f5-2.gif"><B> Figure 5.2 : </B><I>When you try to access a variable that's out of scope, Java's compiler thinks that the variable is undefined.</I></A><P><P>You can use variable scope to simplify the access of variablesin a program. For example, you will usually declare variablesthat you need in many places, so that they are in scope in theentire class. That way, you can access the variables without havingto pass them as arguments to functions. (If you don't know aboutargument passing just yet, you will after you read <A HREF="ch12.htm" >Chapter 12</A>,"Functions.") On the other hand, you'll have lots ofvariables that you use only inside one particular program block.You can keep your program uncluttered by being sure to declarethese types of variables only in the blocks in which they're used.You'll learn more about setting up variables with the proper scopeas you write Java programs later in this book.<H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>All computers must manipulate data in order to produce output.Java, like all programming languages, features many data typesthat you can use for constants and variables in your programs.These data types enable you to store everything from simple integerslike 23 and -10 to strings and complex floating-point numbers.There's a lot to know about variables, so your head may be spinninga bit at this point. Rest assured, however, that once you startwriting programs and using variables, all the theoretical stuffwill make sense.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>What is a constant?<LI>What is a variable?<LI>How do constants and variables make writing programs easier?<LI>Name the eight data types used in Java.<LI>What is variable scope?</OL><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#Ff0000>Review Exercises</FONT></A></H2><OL><LI>Suppose you need to write a Java program that calculates anemployee's paycheck for a given number of hours of work. Writedeclarations for the variables you'll need.<LI>Using the variables you declared in exercise 1, write theprogram lines needed to perform the paycheck calculations.<LI>Using Figure 5.1 as a guide, create a new figure that addsa program block to the class such that any variables declaredin the new block cannot be accessed in any other program block.<LI>Using the modified figure, add yet another program block,this time adding an additional level of block nesting.</OL><HR><HR WIDTH="100%"></P></CENTER><!-- reference library footer #1--></CENTER><IMG SRC="/images/rule.gif" WIDTH="460" HEIGHT="5" VSPACE="5"ALT="Ruler image"><br><FONT SIZE="-1">Contact <a href="mailto:reference@developer.com">reference@developer.com</a> with questions or comments.<br><a href="/legal/">Copyright 1998</a> <a href="http://www.earthweb.com" target="_top">EarthWeb Inc.</a>, All rights reserved.<BR>PLEASE READ THE <a href="/reference/usage.html">ACCEPTABLE USAGE STATEMENT</a>.<BR>Copyright 1998 Macmillan Computer Publishing. All rights reserved.</FONT></BLOCKQUOTE><!--outer table--><TD VALIGN="TOP"><!--right side ads --><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD1.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD1.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD2.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD2.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P></td></tr></table></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -