📄 chapter03.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<!--
This document was converted from RTF source:
By rtftohtml 4.19
See http://www.sunpack.com/RTF
Filename:Tjava14.rtf
Application Directory:c:\TOOLS\RTF2HTML\
Subject:
Author:Bruce Eckel
Operator:Bruce Eckel
Document Comments:
Version Comments:
Comments:
Keywords:
Translation Date:02/04/2000
Translation Time:23:24:41
Translation Platform:Win32
Number of Output files:27
This File:Chapter03.html
SplitDepth=1
SkipNavPanel=1
SkipLeadingToc=1
SkipTrailingToc=1
GenContents=1
GenFrames=1
GenIndex=1
-->
<HEAD lang="en"><META http-equiv="Content-Type" content="text/html">
<TITLE>3: Controlling program flow</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF"><DIV ALIGN="CENTER">
<a href="http://www.MindView.net">
<img src="mindview-head.gif" alt="MindView Inc." BORDER = "0"></a>
<CENTER>
<FONT FACE="Verdana" size = "-1">
[ <a href="README-HTML.txt">Viewing Hints</a> ]
[ <a href="http://www.mindview.net/TIJ2/index.html">2nd Edition</a> ]
[ <a href="http://www.mindview.net/MailingList.html">Free Newsletter</a> ] <br>
[ <a href="http://www.mindview.net/Training.html">Seminars</a> ]
[ <a href="http://www.mindview.net/javaCD2.html">Seminars on CD ROM</a> ]
[ <a href="http://www.mindview.net/CPPServices/#ConsultingServices">Consulting</a> ]
</FONT>
<H2><FONT FACE="Verdana">
Thinking in Java, 1st edition</FONT></H2>
<H3><FONT FACE="Verdana">©1998 by Bruce Eckel</FONT></H3>
<FONT FACE="Verdana" size = "-1">
[ <a href="Chapter02.html">Previous Chapter</a> ]
[ <a href="SimpleContents.html">Short TOC</a> ]
[ <a href="Contents.html">Table of Contents</a> ]
[ <a href="DocIndex.html">Index</a> ]
[ <a href="Chapter04.html">Next Chapter</a> ]
</FONT>
</CENTER>
</P></DIV><A NAME="Chapter_3"></A><A NAME="_Toc375545246"></A><A NAME="_Toc407441447"></A><A NAME="_Toc408018447"></A><A NAME="Heading98"></A><FONT FACE = "Verdana"><H1 ALIGN="LEFT">
3: Controlling program flow</H1></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Verdana" SIZE=4>Like a sentient creature,
a program must manipulate its world and make choices during execution.
</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">In Java you manipulate objects and
data using operators, and you make choices with execution control statements.
Java was inherited from C++, so most of these statements and operators will be
familiar to C and C++ programmers. Java has also added some improvements and
simplifications.</FONT><A NAME="_Toc375545247"></A><A NAME="_Toc408018448"></A><BR></P></DIV>
<A NAME="Heading99"></A><FONT FACE = "Verdana"><H2 ALIGN="LEFT">
Using Java operators<BR><A NAME="Index84"></A><A NAME="Index85"></A></H2></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">An operator takes one or more
arguments and produces a new value. The arguments are in a different form than
ordinary method calls, but the effect is the same. You should be reasonably
comfortable with the general concept of operators from your previous programming
experience. Addition (<B>+</B>), subtraction and unary minus (<B>-</B>),
multiplication (<B>*</B>), division (<B>/</B>) and assignment (<B>=</B>) all
work much the same in any programming language.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">All operators produce a value from
their operands. In addition, an operator can change the value of an operand.
This is called a <I>side effect<A NAME="Index86"></A></I>. The most common use
for operators that modify their operands is to generate the side effect, but you
should keep in mind that the value produced is available for your use just as in
operators without side effects.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Almost all operators work only with
primitives. The exceptions are <B>‘=</B>’, ‘<B>==</B>’
and ‘<B>!=</B>’, which work with all objects (and are a point of
confusion for objects). In addition, the <B>String </B>class supports
‘<B>+</B>’ and
‘<B>+=</B>’.</FONT><A NAME="_Toc375545248"></A><A NAME="_Toc408018449"></A><BR></P></DIV>
<A NAME="Heading100"></A><FONT FACE = "Verdana"><H3 ALIGN="LEFT">
Precedence<BR><A NAME="Index87"></A></H3></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Operator precedence defines how an
expression evaluates when several operators are present. Java has specific rules
that determine the order of evaluation. The easiest one to remember is that
multiplication and division happen before addition and subtraction. Programmers
often forget the other precedence rules, so you should use parentheses to make
the order of evaluation explicit. For example:</FONT><BR></P></DIV>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE>A = X + Y - 2/2 + Z;</PRE></FONT></BLOCKQUOTE>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">has a very different meaning from
the same statement with a particular grouping of parentheses:</FONT><BR></P></DIV>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE>A = X + (Y - 2)/(2 + Z);</PRE></FONT></BLOCKQUOTE><DIV ALIGN="LEFT"><P><A NAME="_Toc375545249"></A><A NAME="_Toc408018450"></A><BR></P></DIV>
<A NAME="Heading101"></A><FONT FACE = "Verdana"><H3 ALIGN="LEFT">
Assignment<A NAME="Index88"></A></H3></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Assignment is performed with the
operator =. It means “take the value of the right-hand side (often called
the <I>rvalue<A NAME="Index89"></A></I>) and copy it into the left-hand side
(often called the <I>lvalue<A NAME="Index90"></A></I>). An rvalue is any
constant, variable or expression that can produce a value, but an lvalue must be
a distinct, named variable. (That is, there must be a physical space to store a
value.) For instance, you can assign a constant value to a variable (<B>A =
4;</B>), but you cannot assign anything to constant value – it cannot be
an lvalue. (You can’t say <B>4 = A;.</B>)</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Assignment of primitives is quite
straightforward. Since the primitive holds the actual value and not a handle to
an object, when you assign primitives you copy the contents from one place to
another. For example, if you say <B>A = B</B> for primitives, then the contents
of <B>B</B> is copied into <B>A</B>. If you then go on to modify <B>A</B>,
<B>B</B> is naturally unaffected by this modification. This is what you’ve
come to expect as a programmer for most situations.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">When you
<A NAME="Index91"></A><A NAME="Index92"></A><A NAME="Index93"></A><A NAME="Index94"></A>assign
objects, however, things change. Whenever you manipulate an object, what
you’re manipulating is the handle, so when you assign “from one
object to another” you’re actually copying a handle from one place
to another. This means that if you say <B>C = D</B> for objects, you end up with
both <B>C</B> and <B>D</B> pointing to the object that, originally, only
<B>D</B> pointed to. The following example will demonstrate this.
</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">As an aside, the first thing you
see is a <A NAME="Index95"></A><B>package</B> statement for <B>package c03</B>,
indicating this book’s Chapter 3. The first code listing of each chapter
will contain a package statement like this to establish the chapter number for
the remaining code listings in that chapter. In Chapter 17, you’ll see
that as a result, all the listings in chapter 3 (except those that have
different package names) will be automatically placed in a subdirectory called
<B>c03</B>, Chapter 4’s listings will be in <B>c04</B> and so on. All this
will happen via the <B>CodePackager.java</B> program shown in Chapter 17, and in
Chapter 5 the concept of packages will be fully explained. What you need to
recognize at this point is that, for this book, lines of code of the form
<B>package c03</B> are used just to establish the chapter subdirectory for the
listings in the chapter.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">In order to run the program, you
must ensure that the
<A NAME="Index96"></A><A NAME="Index97"></A><A NAME="Index98"></A>classpath
contains the root directory where you installed the source code for this book.
(From this directory, you’ll see the subdirectories <B>c02</B>,
<B>c03</B>, <B>c04</B>, etc.)</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">For later versions of Java (1.1.4
and on), when your <B>main( ) </B>is inside a file with a <B>package
</B>statement, you must give the full package name before the program name in
order to run the program. In this case, the command line is:</FONT><BR></P></DIV>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE>java c03.Assignment</PRE></FONT></BLOCKQUOTE>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Keep this in mind any time
you’re running a program that’s in a
<B>package</B>.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Here’s the
example:</FONT><BR></P></DIV>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#009900>//: Assignment.java</font>
<font color=#009900>// Assignment with objects is a bit tricky</font>
<font color=#0000ff>package</font> c03;
<font color=#0000ff>class</font> Number {
<font color=#0000ff>int</font> i;
}
<font color=#0000ff>public</font> <font color=#0000ff>class</font> Assignment {
<font color=#0000ff>public</font> <font color=#0000ff>static</font> <font color=#0000ff>void</font> main(String[] args) {
Number n1 = <font color=#0000ff>new</font> Number();
Number n2 = <font color=#0000ff>new</font> Number();
n1.i = 9;
n2.i = 47;
System.out.println(<font color=#004488>"1: n1.i: "</font> + n1.i +
<font color=#004488>", n2.i: "</font> + n2.i);
n1 = n2;
System.out.println(<font color=#004488>"2: n1.i: "</font> + n1.i +
<font color=#004488>", n2.i: "</font> + n2.i);
n1.i = 27;
System.out.println(<font color=#004488>"3: n1.i: "</font> + n1.i +
<font color=#004488>", n2.i: "</font> + n2.i);
}
} <font color=#009900>///:~</font></PRE></FONT></BLOCKQUOTE>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The <B>Number</B> class is simple,
and two instances of it (<B>n1</B> and <B>n2</B>) are created within
<B>main( )</B>. The <B>i</B> value within each <B>Number</B> is given a
different value, and then <B>n2</B> is assigned to <B>n1</B>, and <B>n1</B> is
changed. In many programming languages you would expect <B>n1</B> and <B>n2</B>
to be independent at all times, but because you’ve assigned a handle
here’s the output you’ll see:</FONT><BR></P></DIV>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE>1: n1.i: 9, n2.i: 47
2: n1.i: 47, n2.i: 47
3: n1.i: 27, n2.i: 27</PRE></FONT></BLOCKQUOTE>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Changing the <B>n1</B> object
appears to change the <B>n2</B> object as well! This is because both <B>n1</B>
and <B>n2</B> contain the same handle, which is pointing to the same object.
(The original handle that was in <B>n1</B> that pointed to the object holding a
value of 9 was overwritten during the assignment and effectively lost; its
object will be cleaned up by the garbage collector.)</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">This phenomenon is often called
<A NAME="Index99"></A><A NAME="Index100"></A><I>aliasing</I> and it’s a
fundamental way that Java works with objects. But what if you don’t want
aliasing to occur in this case? You could forego the assignment and
say:</FONT><BR></P></DIV>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE>n1.i = n2.i;</PRE></FONT></BLOCKQUOTE>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">This retains the two separate
objects instead of tossing one and tying <B>n1 </B>and <B>n2</B> to the same
object, but you’ll soon realize that manipulating the fields within
objects is messy and goes against good object-oriented design principles. This
is a non-trivial topic, so it is left for Chapter 12, which is devoted to
aliasing. In the meantime, you should keep in mind that assignment for objects
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -