<?xml version="1.0" encoding="utf-8"?><?xml-stylesheet type='text/xsl' href='http://x-spirit.spaces.live.com/mmm2008-07-24_12.50/rsspretty.aspx?rssquery=en-US;http%3a%2f%2fx-spirit.spaces.live.com%2fcategory%2fCore%2bJava%e5%ad%a6%e4%b9%a0%e7%ac%94%e8%ae%b0%2ffeed.rss' version='1.0'?><rss version="2.0" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:msn="http://schemas.microsoft.com/msn/spaces/2005/rss" xmlns:live="http://schemas.microsoft.com/live/spaces/2006/rss" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:cf="http://www.microsoft.com/schemas/rss/core/2005" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>X-Spirit: Core Java学习笔记</title><description /><link>http://X-Spirit.spaces.live.com/?_c11_BlogPart_BlogPart=blogview&amp;_c=BlogPart&amp;partqs=catCore%2bJava%25E5%25AD%25A6%25E4%25B9%25A0%25E7%25AC%2594%25E8%25AE%25B0</link><language>en-US</language><pubDate>Thu, 25 Sep 2008 12:45:29 GMT</pubDate><lastBuildDate>Thu, 25 Sep 2008 12:45:29 GMT</lastBuildDate><generator>Microsoft Spaces v1.1</generator><docs>http://www.rssboard.org/rss-specification</docs><ttl>60</ttl><cf:parentRSS>http://X-Spirit.spaces.live.com/blog/feed.rss</cf:parentRSS><live:type>blogcategory</live:type><live:identity><live:id>-3743893519549122624</live:id><live:alias>X-Spirit</live:alias></live:identity><cf:listinfo><cf:group ns="http://schemas.microsoft.com/live/spaces/2006/rss" element="typelabel" label="Type" /><cf:group ns="http://schemas.microsoft.com/live/spaces/2006/rss" element="tag" label="Tag" /><cf:group element="category" label="Category" /><cf:sort element="pubDate" label="Date" data-type="date" default="true" /><cf:sort element="title" label="Title" data-type="string" /><cf:sort ns="http://purl.org/rss/1.0/modules/slash/" element="comments" label="Comments" data-type="number" /></cf:listinfo><item><title>3.7 Input and Output 输入与输出</title><link>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!335.entry</link><description>&lt;p&gt;  &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;To make our example programs more interesting, we want to accept input and properly format the program output. Of course, modern programs use a GUI for collecting user input. However, programming such an interface requires more tools and techniques than we have at our disposal at this time. Because the first order of business is to become more familiar with the Java programming language, we make do with the humble console for input and output for now. GUI programming is covered in &lt;a&gt;Chapters 7&lt;/a&gt; through &lt;a&gt;9&lt;/a&gt;. &lt;p&gt;要是我们的程序更有意思，我们需要在程序中接收输入，并适当的格式化输出。当然，先进的程序采用GUI（图形用户界面）来收集用户输入。但是编写这样一个界面需要更多的工具和技术，这已经超出了我们现在的目标。因为我们当前的目标是更熟悉Java编程语言，我们还是采用粗陋的控制台作为输入输出。GUI编程将在7~9章介绍。 &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;Reading Input &lt;/b&gt;&lt;b&gt;读取输入&lt;/b&gt;&lt;b&gt;&lt;/b&gt; &lt;p&gt;You saw that it is easy to print output to the &amp;quot;standard output stream&amp;quot; (that is, the console window) just by calling System.out.println. Oddly enough, before JDK 5.0, there was no convenient way to read input from the console window. Fortunately, that situation has finally been rectified.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;你可以看到，向标准输出流（也就是控制台窗口）输出内容非常简单，只需要调用System.out.println即可。非常奇怪的是，JDK5.0以前，还没有什么便捷的办法可以从控制台窗口读取输入。幸运的是，这种情况最终得以矫正。 &lt;p&gt;To read console input, you first construct a Scanner that is attached to the &amp;quot;standard input stream&amp;quot; System.in. &lt;p&gt;要读取控制台输入，你首先构造一个附属于标准输入流System.in的Scanner。 &lt;p&gt;Scanner in = new Scanner(System.in); &lt;p&gt;Now you use the various methods of the Scanner class to read input. For example, the nextLine method reads a line of input. &lt;p&gt;现在你可以使用Scanner类的各种方法来读取输入。例如，nextLine方法可以读取一行输入。 &lt;p&gt;System.out.print(&amp;quot;What is your name? &amp;quot;); &lt;p&gt;String name = in.nextLine(); &lt;p&gt;Here, we use the nextLine method because the input might contain spaces. To read a single word (delimited by whitespace), call &lt;p&gt;这里，我们使用nextLine方法因为输入可能包含空格。要读取单个单词（以空格分隔），调用： &lt;p&gt;String firstName = in.next(); &lt;p&gt;To read an integer, use the nextInt method. &lt;p&gt;要读取一个整数，使用nextInt方法。 &lt;p&gt;System.out.print(&amp;quot;How old are you? &amp;quot;); &lt;p&gt;int age = in.nextInt(); &lt;p&gt;Similarly, the nextdouble method reads the next floating-point number. &lt;p&gt;类似的，nextdouble方法读取下一个浮点数字。 &lt;p&gt;The program in &lt;a&gt;Example 3-2&lt;/a&gt; asks for the user's name and age and then prints a message like &lt;p&gt;Hello, Cay. Next year, you'll be 46 &lt;p&gt;Finally, add the line &lt;p&gt;import java.util.*; &lt;p&gt;at the beginning of the program. The Scanner class is defined in the java.util package. Whenever you use a class that is not defined in the basic java.lang package, you need to use an import directive. We look at packages and import directives in more detail in &lt;a&gt;Chapter 4&lt;/a&gt;. &lt;p&gt;例3-2要求用户输入姓名和年龄，并输出消息”Hello, cay. Next year, you’ll be 46” &lt;p&gt;最后在程序的开头加上import java.util.*; &lt;p&gt;Scanner类是定义在java.util包里的。只要你使用了一个没有定义在基本的java.lang包中的类，你都需要一个import 命令。我们将在第四章中更详细的讨论包和import。 &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;Example 3-2. InputTest.java&lt;/b&gt; &lt;p&gt;&lt;a&gt;&lt;/a&gt;1. import java.util.*; &lt;p&gt;2. &lt;p&gt;3. public class InputTest &lt;p&gt;4. { &lt;p&gt;5. public static void main(String[] args) &lt;p&gt;6. { &lt;p&gt;7. Scanner in = new Scanner(System.in); &lt;p&gt;8. &lt;p&gt;9. // get first input &lt;p&gt;10. System.out.print(&amp;quot;What is your name? &amp;quot;); &lt;p&gt;11. String name = in.nextLine(); &lt;p&gt;12. &lt;p&gt;13. // get second input &lt;p&gt;14. System.out.print(&amp;quot;How old are you? &amp;quot;); &lt;p&gt;15. int age = in.nextInt(); &lt;p&gt;16. &lt;p&gt;17. // display output on console &lt;p&gt;18. System.out.println(&amp;quot;Hello, &amp;quot; + name + &amp;quot;. Next year, you'll be &amp;quot; + (age + 1)); &lt;p&gt;19. } &lt;p&gt;20. } &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;NOTE&lt;/b&gt; &lt;p&gt;  &lt;p&gt;If you do not have JDK 5.0 or above, you have to work harder to read user input. The simplest method is to use an input dialog (see &lt;a&gt;Figure 3-6&lt;/a&gt;).&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;如果你没有JDK 5.0或以上版本，你必须在读取用户输入上多费些力气。最简单的方法就是使用一个输入框（见图3-6） &lt;p&gt;String input = JOptionPane.showInputDialog(promptString) &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;Figure 3-6. An input dialog&lt;/b&gt; &lt;p&gt;&lt;img height=122 alt="G:\temp\Core Java 7th\Core Java I 7th\images\03fig06.jpg" src="http://blufiles.storage.msn.com/y1p4iJf0JBb69lWbvgSzBucsi2x64_7Yk9UDaQX2qDK2KZY3AWFMVTu_LW3FwrtbtCA_Q6wiup3nFE" width=300 border=0&gt; &lt;p&gt;The return value is the string that the user typed. &lt;p&gt;返回值就是用户输入的字符串。 &lt;p&gt;For example, here is how you can query the name of the user of your program: &lt;p&gt;例如，下面的代码展示了我们如何在程序中要求输入用户的名字。 &lt;p&gt;String name = JOptionPane.showInputDialog(&amp;quot;What is your name?&amp;quot;);&lt;a&gt;&lt;/a&gt; &lt;p&gt;Reading numbers requires an additional step. The JOptionPane.showInputDialog method returns a string, not a number. You use the Integer.parseInt or Double.parseDouble method to convert the string to its numeric value. For example, &lt;p&gt;读取数字型输入需要再多一步。JOptionPane.showInputDialog方法返回一个字符串，而不是一个数字。你需要使用Integer.parseInt或者Double.parseDouble方法来将其数字值转换为字符串。例如 &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;String input = JOptionPane.showInputDialog(&amp;quot;How old are you?&amp;quot;); int age = Integer.parseInt(input); &lt;p&gt;If the user types 45, then the string variable input is set to the string &amp;quot;45&amp;quot;. The Integer.parseInt method converts the string to its numeric value, the number 45. &lt;p&gt;如果用户输入45，则字符串变量被赋值为”45”。Integer.parseInt方法将字符串转换为相应的数字值，也就是数字45。 &lt;p&gt;The JOptionPane class is defined in the javax.swing package, so you need to add the statement &lt;p&gt;JOptionPane类是定义在javax.swing包中，所以你需要添加语句 &lt;p&gt;import javax.swing.*; &lt;p&gt;Finally, whenever your program calls JOptionPane.showInputDialog, you need to end it with a call to System.exit(0). The reason is a bit technical. Showing a dialog box starts a new thread of control. When the main method exits, the new thread does not automatically terminate. To end all threads, you call the System.exit method. (For more information on threads, see &lt;a&gt;Chapter 1&lt;/a&gt; of Volume 2.) The following program is the equivalent to &lt;a&gt;Example 3-2&lt;/a&gt; prior to JDK 5.0. &lt;p&gt;最后，无论何时程序调用JOptionPane.showInputDialog，你需要采用System.exit(0)来结束之。这是一个有点技术性的原因。显示一个对话框需要启动一个新的控制线程。当main方法退出时，新启动的线程并没有终结。要结束所有线程，你需要调用System.exit方法（想进一步了解线程，参见卷2第一章）下面的程序等同于JDK5.0以前的例3-2 &lt;p&gt;import javax.swing.*; &lt;p&gt;public class InputTest &lt;p&gt;{ &lt;p&gt;public static void main(String[] args) &lt;p&gt;{ &lt;p&gt;String name = JOptionPane.showInputDialog(&amp;quot;What is your name?&amp;quot;); &lt;p&gt;String input = JOptionPane.showInputDialog(&amp;quot;How old are you?&amp;quot;); &lt;p&gt;int age = Integer.parseInt(input); &lt;p&gt;System.out.println(&amp;quot;Hello, &amp;quot; + name + &amp;quot;. Next year, you'll be &amp;quot; + (age + 1)); &lt;p&gt;System.exit(0); &lt;p&gt;} &lt;p&gt;} &lt;p&gt;  &lt;p&gt;&lt;b&gt;java.util.Scanner 5.0&lt;/b&gt;&lt;a&gt;&lt;/a&gt; &lt;ul&gt; &lt;li&gt;Scanner(InputStream in)&lt;/ul&gt; &lt;p&gt;constructs a Scanner object from the given input stream. &lt;ul&gt; &lt;li&gt;String nextLine()&lt;/ul&gt; &lt;p&gt;reads the next line of input. &lt;ul&gt; &lt;li&gt;String next()&lt;/ul&gt; &lt;p&gt;reads the next word of input (delimited by whitespace). &lt;ul&gt; &lt;li&gt;int nextInt() &lt;li&gt;double nextDouble()&lt;/ul&gt; &lt;p&gt;read and convert the next character sequence that represents an integer or floating-point number. &lt;ul&gt; &lt;li&gt;boolean hasNext()&lt;/ul&gt; &lt;p&gt;tests whether there is another word in the input.检测后面是否还有一个单词 &lt;ul&gt; &lt;li&gt;boolean hasNextInt() &lt;li&gt;boolean hasNextDouble()&lt;/ul&gt; &lt;p&gt;test whether the next character sequence represents an integer or floating-point number.检测下一个字符序列是否代表一个整数或一个浮点数。 &lt;p&gt;  &lt;p&gt;&lt;b&gt;javax.swing.JOptionPane 1.2&lt;/b&gt; &lt;ul&gt; &lt;li&gt;static String showInputDialog(Object message)&lt;/ul&gt; &lt;p&gt;displays a dialog box with a message prompt, an input field, and &amp;quot;OK&amp;quot; and &amp;quot;Cancel&amp;quot; buttons. The method returns the string that the user typed.&lt;br&gt;显示一个带有消息提示的对话框，一个输入框，还有”OK”和”Cancel”按钮。该方法返回用户键入的字符串。 &lt;p&gt;  &lt;p&gt;&lt;b&gt;java.lang.System 1.0&lt;/b&gt; &lt;ul&gt; &lt;li&gt;static void exit(int status)&lt;/ul&gt; &lt;p&gt;terminates the virtual machine and passes the status code to the operating system. By convention, a non-zero status code indicates an error.&lt;br&gt;终止虚拟机并向操作系统传递状态码。约定非零状态码表示一种错误。 &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;Formatting Output &lt;/b&gt;&lt;b&gt;格式化输出&lt;/b&gt;&lt;b&gt;&lt;/b&gt; &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;You can print a number x to the console with the statement System.out.print(x). That command will print x with the maximum number of non-zero digits for that type. For example, &lt;p&gt;你可以用System.out.print(x)语句将一个数字x输出到控制台。这个命令将以该类型最大非零位数打印x。例如： &lt;p&gt;double x = 10000.0 / 3.0; &lt;p&gt;System.out.print(x); &lt;p&gt;prints打印出 &lt;p&gt;3333.3333333333335 &lt;p&gt;That is a problem if you want to display, for example, dollars and cents.但是当你想显示美元和美分的时候这就成了问题。 &lt;p&gt;Before JDK 5.0, formatting numbers was a bit of a hassle. Fortunately, JDK 5.0 brought back the venerable printf method from the C library. For example, the call&lt;a&gt;&lt;/a&gt; &lt;p&gt;JDK5.0前，对数字的格式化产生了争论。幸运的是，JDK5.0将古老的printf方法从C库中带回来了。例如： &lt;p&gt;System.out.printf(&amp;quot;%8.2f&amp;quot;, x); &lt;p&gt;prints x with a &lt;i&gt;field width&lt;/i&gt; of 8 characters and a &lt;i&gt;precision&lt;/i&gt; of 2 characters. That is, the printout contains a leading space and the seven characters &lt;p&gt;以8个字符的字段宽度和2个字符的精度打印出x。也就是说，输出包含前导空白和七个字符 &lt;p&gt;3333.33 &lt;p&gt;You can supply multiple parameters to printf, for example:你可以在printf中使用多个参数。 &lt;p&gt;System.out.printf(&amp;quot;Hello, %s. Next year, you'll be %d&amp;quot;, name, age); &lt;p&gt;Each of the &lt;i&gt;format specifiers&lt;/i&gt; that start with a % character is replaced with the corresponding argument. The &lt;i&gt;conversion character&lt;/i&gt; that ends a format specifier indicates the type of the value to be formatted: f is a floating-point number, s a string, and d a decimal integer. &lt;a&gt;Table 3-5&lt;/a&gt; shows all conversion characters. &lt;p&gt;每个格式区分符以%开始，并被相应的变量取代。结束格式区分符的转换字符指明了要格式化的值的类型：f是指一个浮点数字，s是指一个字符串，d是指一个十进制整数。表3-5列出了所有的转换字符。 &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;Table 3-5. Conversions for &lt;/b&gt;&lt;b&gt;printf&lt;/b&gt;&lt;b&gt;&lt;/b&gt; &lt;p&gt;&lt;b&gt;Conversion Character&lt;/b&gt; &lt;p&gt;&lt;b&gt;Type&lt;/b&gt; &lt;p&gt;&lt;b&gt;Example&lt;/b&gt; &lt;p&gt;d &lt;p&gt;Decimal integer十进制整数 &lt;p&gt;159 &lt;p&gt;x &lt;p&gt;Hexadecimal integer&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;十六进制整数 &lt;p&gt;9f &lt;p&gt;o &lt;p&gt;Octal integer八进制整数 &lt;p&gt;237 &lt;p&gt;f &lt;p&gt;Fixed-point floating-point定点浮点数 &lt;p&gt;15.9 &lt;p&gt;e &lt;p&gt;Exponential floating-point指数型浮点数 &lt;p&gt;1.59e+01 &lt;p&gt;g &lt;p&gt;General floating-point (the shorter of e and f) &lt;p&gt;a &lt;p&gt;Hexadecimal floating point十六进制浮点 &lt;p&gt;0x1.fccdp3 &lt;p&gt;s &lt;p&gt;String &lt;p&gt;Hello &lt;p&gt;c &lt;p&gt;Character &lt;p&gt;H &lt;p&gt;b &lt;p&gt;Boolean &lt;p&gt;TRue &lt;p&gt;h &lt;p&gt;Hash code哈希码 &lt;p&gt;42628b2 &lt;p&gt;t&lt;i&gt;x&lt;/i&gt; &lt;p&gt;Date and time &lt;p&gt;See &lt;a&gt;Table 3-7&lt;/a&gt; &lt;p&gt;% &lt;p&gt;The percent symbol百分号 &lt;p&gt;% &lt;p&gt;n &lt;p&gt;The platform-dependent line separator换行符 &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;Table 3-7. Date and Time Conversion Characters&lt;/b&gt; &lt;p&gt;&lt;b&gt;Conversion Character&lt;/b&gt; &lt;p&gt;&lt;b&gt;Type&lt;/b&gt; &lt;p&gt;&lt;b&gt;Example&lt;/b&gt; &lt;p&gt;C &lt;p&gt;Complete date and time &lt;p&gt;Mon Feb 09 18:05:19 PST 2004 &lt;p&gt;F &lt;p&gt;ISO 8601 date&lt;a&gt;&lt;/a&gt; &lt;p&gt;2004-02-09 &lt;p&gt;D &lt;p&gt;U.S. formatted date (month/day/year) &lt;p&gt;02/09/2004 &lt;p&gt;T &lt;p&gt;24-hour time &lt;p&gt;18:05:19 &lt;p&gt;r &lt;p&gt;12-hour time &lt;p&gt;06:05:19 pm &lt;p&gt;R &lt;p&gt;24-hour time, no seconds&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;18:05 &lt;p&gt;Y &lt;p&gt;Four-digit year (with leading zeroes) &lt;p&gt;2004 &lt;p&gt;y &lt;p&gt;Last two digits of the year (with leading zeroes) &lt;p&gt;04 &lt;p&gt;C &lt;p&gt;First two digits of the year (with leading zeroes) &lt;p&gt;20 &lt;p&gt;B &lt;p&gt;Full month name &lt;p&gt;February &lt;p&gt;b or h &lt;p&gt;Abbreviated month name&lt;a&gt;&lt;/a&gt;月份名称缩写 &lt;p&gt;Feb &lt;p&gt;m &lt;p&gt;Two-digit month (with leading zeroes) &lt;p&gt;02 &lt;p&gt;d &lt;p&gt;Two-digit day (with leading zeroes)&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;09 &lt;p&gt;e &lt;p&gt;Two-digit day (without leading zeroes) &lt;p&gt;9 &lt;p&gt;A &lt;p&gt;Full weekday name &lt;p&gt;Monday &lt;p&gt;a &lt;p&gt;Abbreviated weekday name &lt;p&gt;Mon &lt;p&gt;j &lt;p&gt;Three-digit day of year (with leading zeroes), between 001 and 366 &lt;p&gt;069 &lt;p&gt;H &lt;p&gt;Two-digit hour (with leading zeroes), between 00 and 23 &lt;p&gt;18 &lt;p&gt;k &lt;p&gt;Two-digit hour (without leading zeroes), between 0 and 23 &lt;p&gt;18 &lt;p&gt;I &lt;p&gt;Two-digit hour (with leading zeroes), between 01 and 12 &lt;p&gt;06 &lt;p&gt;l &lt;p&gt;Two-digit hour (without leading zeroes), between 1 and 12 &lt;p&gt;6 &lt;p&gt;M &lt;p&gt;Two-digit minutes (with leading zeroes) &lt;p&gt;05 &lt;p&gt;S &lt;p&gt;Two-digit seconds (with leading zeroes) &lt;p&gt;19 &lt;p&gt;L &lt;p&gt;Three-digit milliseconds (with leading zeroes)三位毫秒数 &lt;p&gt;047 &lt;p&gt;N &lt;p&gt;Nine-digit nanoseconds (with leading zeroes)九位纳秒数 &lt;p&gt;047000000 &lt;p&gt;P &lt;p&gt;Uppercase morning or afternoon marker大写上下午标记 &lt;p&gt;PM &lt;p&gt;p &lt;p&gt;Lowercase morning or afternoon marker小写上下午标记 &lt;p&gt;pm &lt;p&gt;z &lt;p&gt;RFC 822 numeric offset from GMT格林尼治时间偏移量 &lt;p&gt;-0800 &lt;p&gt;Z &lt;p&gt;Time zone时区 &lt;p&gt;PST &lt;p&gt;s &lt;p&gt;Seconds since 1970-01-01 00:00:00 GMT &lt;p&gt;1078884319 &lt;p&gt;E &lt;p&gt;Milliseconds since 1970-01-01 00:00:00 GMT&lt;a&gt;&lt;/a&gt; &lt;p&gt;1078884319047 &lt;p&gt;In addition, you can specify &lt;i&gt;flags&lt;/i&gt; that control the appearance of the formatted output. &lt;a&gt;Table 3-6&lt;/a&gt; shows all flags. For example, the comma flag adds group separators. That is,&lt;a&gt;&lt;/a&gt; &lt;p&gt;另外，你可以指定标记来控制格式化输出的行为。例如逗号标记可以添加组分隔符。也就是 &lt;p&gt;System.out.printf(&amp;quot;%,.2f&amp;quot;, 10000.0 / 3.0); &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;Table 3-6. Flags for &lt;/b&gt;&lt;b&gt;printf&lt;/b&gt;&lt;b&gt;&lt;/b&gt; &lt;p&gt;&lt;b&gt;Flag&lt;/b&gt; &lt;p&gt;&lt;b&gt;Purpose&lt;/b&gt; &lt;p&gt;&lt;b&gt;Example&lt;/b&gt; &lt;p&gt;+ &lt;p&gt;Prints sign for positive and negative numbers输出数字的正负号 &lt;p&gt;+3333.33 &lt;p&gt;space &lt;p&gt;Adds a space before positive numbers在整数前加一个空格 &lt;p&gt;| 3333.33| &lt;p&gt;0 &lt;p&gt;Adds leading zeroes加入前导的0 &lt;p&gt;003333.33 &lt;p&gt;- &lt;p&gt;Left-justifies field左对齐字段 &lt;p&gt;|3333.33 | &lt;p&gt;( &lt;p&gt;Encloses negative number in parentheses用圆括号括起负数 &lt;p&gt;(3333.33) &lt;p&gt;, &lt;p&gt;Adds group separators添加组分隔符 &lt;p&gt;3,333.33 &lt;p&gt;# (for f format) &lt;p&gt;Always includes a decimal point总是包含小数点 &lt;p&gt;3,333. &lt;p&gt;# (for x or o format) &lt;p&gt;Adds 0x or 0 prefix添加0x或者0前缀 &lt;p&gt;0xcafe &lt;p&gt;^ &lt;p&gt;Converts to upper case转换为大写 &lt;p&gt;0XCAFE &lt;p&gt;$ &lt;p&gt;Specifies the index of the argument to be formatted; for example, %1$d %1$x prints the first argument in decimal and hexadecimal指定要格式化的参数的索引，例如%1$d %1$x以十进制和十六进制形式输出第一个参数 &lt;p&gt;159 9F &lt;p&gt;&amp;lt; &lt;p&gt;Formats the same value as the previous specification; for example, %d %&amp;lt;x prints the same number in decimal and hexadecimal格式化前面指定的相同的值，例如%d %&amp;lt;x 以十进制和十六进制的形式输出同一个数字。 &lt;p&gt;159 9F &lt;p&gt;prints打印出 &lt;p&gt;3,333.33 &lt;p&gt;You can use multiple flags, for example, &amp;quot;%,(.2f&amp;quot;, to use group separators and enclose negative numbers in parentheses. &lt;p&gt;你可以使用多个标记，例如&amp;quot;%,(.2f&amp;quot;,使用组分隔符并用圆括号括住负数。 &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;NOTE&lt;/b&gt; &lt;p&gt;  &lt;p&gt;You can use the s conversion to format arbitrary objects. If an arbitrary object implements the Formattable interface, the object's formatTo method is invoked. Otherwise, the toString method is invoked to turn the object into a string. We discuss the toString method in &lt;a&gt;Chapter 5&lt;/a&gt; and interfaces in &lt;a&gt;Chapter 6&lt;/a&gt;. &lt;p&gt;你可以使用s转换来格式化任意对象。如果任意对象实现了Formattable接口，则对象的formatTo方法被调用。否则调用toString方法来将一个对象转变为一个字符串。我们将在第五章和第六章中分别讨论toString方法和接口 &lt;p&gt;You can use the static String.format method to create a formatted string without printing it: &lt;p&gt;你可使用静态方法String.format来创建格式化的字符串，而并不将其输出。 &lt;p&gt;String message = String.format(&amp;quot;Hello, %s. Next year, you'll be %d&amp;quot;, name, age); &lt;p&gt;Although we do not describe the Date type in detail until &lt;a&gt;Chapter 4&lt;/a&gt;, we do, in the interest of completeness, briefly discuss the date and time formatting options of the printf method. You use two a two-letter format, starting with t and ending in one of the letters of &lt;a&gt;Table 3-7&lt;/a&gt;. For example, &lt;p&gt;尽管我们到第4章才讲述Date类型，但是完全是出于兴趣，简要介绍一下printf方法的时间和日期格式选项。你可以使用一个两字母的格式，以t开始，以表3-7中的字母结束。例如 &lt;p&gt;System.out.printf(&amp;quot;%tc&amp;quot;, new Date()); &lt;p&gt;prints the current date and time in the format &lt;p&gt;以如下格式输出日期和时间。 &lt;p&gt;Mon Feb 09 18:05:19 PST 2004 &lt;p&gt;As you can see in &lt;a&gt;Table 3-7&lt;/a&gt;, some of the formats yield only a part of a given date, for example, just the day or just the month. It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the &lt;i&gt;index&lt;/i&gt; of the argument to be formatted. The index must immediately follow the %, and it must be terminated by a $. For example, &lt;p&gt;如你在表3-7中所见，一些格式仅输出指定时间的一部分，例如，仅仅是日或者月。如果你要多次提供时间，并要格式化每个部分，这看起来很傻。一个格式化字串可以指定要格式化的参数的索引。索引值紧跟百分号%，并以$结束。例如 &lt;p&gt;System.out.printf(&amp;quot;%1$s %2$tB %2$te, %2$tY&amp;quot;, &amp;quot;Due date:&amp;quot;, new Date()); &lt;p&gt;prints输出 &lt;p&gt;Due date: February 9, 2004 &lt;p&gt;Alternatively, you can use the &amp;lt; flag. It indicates that the same argument as in the preceding format specification should be used again. That is, the statement &lt;p&gt;或者你可以选择使用&amp;lt;标记。它表明将再次使用前一个格式所规范的参数。也就是如下语句 &lt;p&gt;System.out.printf(&amp;quot;%s %tB %&amp;lt;te, %&amp;lt;tY&amp;quot;, &amp;quot;Due date:&amp;quot;, new Date()); &lt;p&gt;yields the same output as the preceding statement. &lt;p&gt;将和上一条语句产生相同的输出。 &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;CAUTION&lt;/b&gt; &lt;p&gt;  &lt;p&gt;Argument index values start with 1, not with 0: %1$... formats the first argument. This avoids confusion with the 0 flag. &lt;p&gt;参数索引值以1开始，而不是0. &lt;p&gt;You have now seen all features of the printf method. &lt;a&gt;Figure 3-7&lt;/a&gt; shows a syntax diagram for format specifiers. &lt;p&gt;下图是格式化说明符的语法： &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;Figure 3-7. Format specifier syntax&lt;/b&gt; &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;[View full size image]&lt;/a&gt; &lt;p&gt;&lt;img height=100 alt="G:\temp\Core Java 7th\Core Java I 7th\images\03fig07.gif" src="http://blufiles.storage.msn.com/y1p4iJf0JBb69ko4mfmy10tLrzC0seKyaDi4sVi7comL_S1EZ7MOFvEsdshwcHRkjQ8JDBLX8qzka8" width=500 border=0&gt; &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;NOTE&lt;/b&gt; &lt;p&gt;  &lt;p&gt;A number of the formatting rules are &lt;i&gt;locale specific&lt;/i&gt;. For example, in Germany, the decimal separator is a period, not a comma, and Monday is formatted as Montag. You will see in Volume 2 how to control the international behavior of your applications.&lt;a&gt;&lt;/a&gt; &lt;p&gt;一些格式化规范是地区性的。例如，在德国，十进制分隔符是一个句点，而不是一个逗号，而Monday被格式化为Montag。你将在卷2中看到如何在你的程序中处理国际化问题。 &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;TIP&lt;/b&gt; &lt;p&gt;  &lt;p&gt;If you use a version of Java prior to JDK 5.0, use the NumberFormat and DateFormat classes instead of printf.&lt;a&gt;&lt;/a&gt; &lt;p&gt;如果你使用的是JDK5.0以前版本，请使用NumberFormat和DateFormat来代替printf&lt;img src="http://c.services.spaces.live.com/CollectionWebService/c.gif?cid=-3743893519549122624&amp;page=RSS%3a+3.7+Input+and+Output+%e8%be%93%e5%85%a5%e4%b8%8e%e8%be%93%e5%87%ba&amp;referrer=" width="1px" height="1px" border="0" alt=""&gt;&lt;img style="position:absolute" alt="" width="0px" height="0px" src="http://c.live.com/c.gif?NC=31263&amp;amp;NA=1149&amp;amp;PI=73329&amp;amp;RF=&amp;amp;DI=3919&amp;amp;PS=85545&amp;amp;TP=x-spirit.spaces.live.com&amp;amp;GT1=X-Spirit"&gt;</description><comments>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!335.entry#comment</comments><guid isPermaLink="true">http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!335.entry</guid><pubDate>Tue, 18 Sep 2007 11:35:10 GMT</pubDate><slash:comments>1</slash:comments><msn:type>blogentry</msn:type><live:type>blogentry</live:type><live:typelabel>Blog entry</live:typelabel><wfw:commentRss>http://X-Spirit.spaces.live.com/blog/cns!CC0B04AE126337C0!335/comments/feed.rss</wfw:commentRss><wfw:comment>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!335.entry#comment</wfw:comment><dcterms:modified>2007-09-21T23:02:01Z</dcterms:modified></item><item><title>3.6 Strings字符串</title><link>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!330.entry</link><description>&lt;p&gt;   &lt;p&gt;Conceptually, Java strings are sequences of Unicode characters. For example, the string &amp;quot;Java\u2122&amp;quot; consists of the five Unicode characters J, a, v, a, and ™. Java does not have a built-in string type. Instead, the standard Java library contains a predefined class called, naturally enough, String. Each quoted string is an instance of the String class:&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;概念上讲，Java字符串就是Unicode字符序列。例如，字符串&amp;quot;Java\u2122&amp;quot;由5个Unicode字符J，a，v，a和™组成。Java没有内建的string类型。但是，标准Java库提供了一个类，很自然的，叫做String。每个被引起来的字符串就是一个String实例：  &lt;p&gt;String e = &amp;quot;&amp;quot;; // an empty string  &lt;p&gt;String greeting = &amp;quot;Hello&amp;quot;;  &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;Code Points and Code Units &lt;/b&gt;&lt;b&gt;代码点和代码单元&lt;/b&gt;&lt;b&gt;&lt;/b&gt;  &lt;p&gt;Java strings are implemented as sequences of char values. As we discussed on page &lt;a&gt;41&lt;/a&gt;, &lt;a&gt;the char data type&lt;/a&gt; is a code unit for representing Unicode code points in the UTF-16 encoding. The most commonly used Unicode characters can be represented with a single code unit. The supplementary characters require a pair of code units.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;Java字符串是以char值序列的方式实现的。如我们在41页中提到的，char数据类型是一个表示UTF-16编码中各个Unicode代码点的代码单元。最常用的Unicode字符可以用一个单独的代码单元表示。增补字符需要一对代码单元。  &lt;p&gt;The length method yields the number of code units required for a given string in the UTF-16 encoding. For example:  &lt;p&gt;length方法返回指定的UTF-16编码字符串所需代码单元的数量，例如：  &lt;p&gt;String greeting = &amp;quot;Hello&amp;quot;;  &lt;p&gt;int n = greeting.length(); // is 5.  &lt;p&gt;To get the true length, that is, the number of code points, call  &lt;p&gt;要得到真实的长度，即代码点的数量，调用：  &lt;p&gt;int cpCount = greeting.codePointCount(0, greeting.length());  &lt;p&gt;The call s.charAt(n) returns the code unit at position n, where n is between 0 and s.length() – 1. For example,  &lt;p&gt;s.charAt(n) 返回位置n对应的代码单元，这里n介于0和s.length()-1之间。例如：  &lt;p&gt;char first = greeting.charAt(0); // first is 'H'  &lt;p&gt;char last = greeting.charAt(4); // last is 'o'  &lt;p&gt;To get at the ith code point, use the statements  &lt;p&gt;要获得第i个代码点，使用语句：  &lt;p&gt;int index = greeting.offsetByCodePoints(0, i);  &lt;p&gt;int cp = greeting.codePointAt(index);  &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;NOTE&lt;/b&gt;  &lt;p&gt;   &lt;p&gt;Java counts the code units in strings in a peculiar fashion: the first code unit in a string has position 0. This convention originated in C, where there was a technical reason for counting positions starting at 0. That reason has long gone away and only the nuisance remains. However, so many programmers are used to this convention that the Java designers decided to keep it.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;Java以一种特殊的方式计算字符串中的代码单元：字符串中的第一个代码单元的位置是0。这个约定源于C，在C中位置从0开始计数是有技术原因的。这个技术原因现在早已不存在了，但是却留下了这个令人讨厌的方式。但是由于很多程序员习惯了这个约定，所以Java的设计者们决定保留它。  &lt;p&gt;Why are we making a fuss about code units? Consider the sentence  &lt;p&gt;我们为什么要在代码单元上小题大做？看一下这个句子  &lt;p&gt;is the set of integers  &lt;p&gt;The character requires two code units in the UTF-16 encoding. Calling  &lt;p&gt;在UTF-16编码中，字符需要两个代码单元，调用  &lt;p&gt;char ch = sentence.charAt(1)  &lt;p&gt;doesn't return a space but the second code unit of . To avoid this problem, you should not use the char type. It is too low-level.  &lt;p&gt;并不返回一个空格，而是其第二个代码单元。要避免这个问题，你不应当使用char类型。这个类型太低级。  &lt;p&gt;If your code traverses a string, and you want to look at each code point in turn, use these statements:  &lt;p&gt;如果你的代码遍历一个字符串，并且你想逐个查看每个代码单元，请使用下面的语句：  &lt;p&gt;int cp = sentence.codePointAt(i);  &lt;p&gt;if (Character.isSupplementaryCodePoint(cp)) i += 2;  &lt;p&gt;else i++;  &lt;p&gt;Fortunately, the codePointAt method can tell whether a code unit is the first or second half of a supplementary character, and it returns the right result either way. That is, you can move backwards with the following statements:  &lt;p&gt;幸运的是，codePointAt方法可以告诉我们何处是一个辅助字符的前一半或者后一半，并且对于任一一种都可以返回正确的结果。也就是说，你也可以用下面的语句进行逆向遍历  &lt;p&gt;i--;  &lt;p&gt;int cp = sentence.codePointAt(i);  &lt;p&gt;if (Character.isSupplementaryCodePoint(cp)) i--;  &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;Substrings &lt;/b&gt;&lt;b&gt;子串&lt;/b&gt;&lt;b&gt;&lt;/b&gt;  &lt;p&gt;You extract a substring from a larger string with the substring method of the String class. For example,&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;用substring方法可以从一个大的字符串中提取字串。例如  &lt;p&gt;String greeting = &amp;quot;Hello&amp;quot;;  &lt;p&gt;String s = greeting.substring(0, 3);  &lt;p&gt;creates a string consisting of the characters &amp;quot;Hel&amp;quot;.  &lt;p&gt;得到一个由字符”Hel”组成的字串。  &lt;p&gt;The second parameter of substring is the first code unit that you &lt;i&gt;do not&lt;/i&gt; want to copy. In our case, we want to copy the code units in positions 0, 1, and 2 (from position 0 to position 2 inclusive). As substring counts it, this means from position 0 inclusive to position 3 &lt;i&gt;exclusive.&lt;/i&gt;  &lt;p&gt;substring的第二个参数是你第一个不想复制的代码单元。在我们的例子中，我们想复制的是位置0、1、2（从位置0到位置2，包含端点）。也就是从位置0（包含）到位置3（不包含）。  &lt;p&gt;There is one advantage to the way substring works: Computing the number of code units in the substring is easy. The string s.substring(a, b) always has b - a code units. For example, the substring &amp;quot;Hel&amp;quot; has 3 – 0 = 3 code units.  &lt;p&gt;substring的这种工作方式有一个优点：计算字串中的代码单元数量是简单的。字符串s.substring(a,b)的代码单元数总是等于b-a。从例子即可看出。  &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;String Editing &lt;/b&gt;&lt;b&gt;字符串编辑&lt;/b&gt;&lt;b&gt;&lt;/b&gt;  &lt;p&gt;The String class gives no methods that let you &lt;i&gt;change&lt;/i&gt; a character in an existing string. If you want to turn greeting into &amp;quot;Help!&amp;quot;, you cannot directly change the last positions of greeting into 'p' and '!'. If you are a C programmer, this will make you feel pretty helpless. How are you going to modify the string? In Java, it is quite easy: concatenate the substring that you want to keep with the characters that you want to replace.  &lt;p&gt;Java中的String类型虽然不提供字符串编辑的方法，但是，你可以采用将某个字符串的字串和其他字串相连接的方式。例如你希望将”Hello”修改为”Help!”，你可以这样做  &lt;p&gt;greeting = greeting.substring(0, 3) + &amp;quot;p!&amp;quot;;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;This declaration changes the current value of the greeting variable to &amp;quot;Help!&amp;quot;.  &lt;p&gt;Because you cannot change the individual characters in a Java string, the documentation refers to the objects of the String class as being &lt;i&gt;immutable.&lt;/i&gt; Just as the number 3 is always 3, the string &amp;quot;Hello&amp;quot; will always contain the code unit sequence describing the characters H, e, l, l, o. You cannot change these values. You can, as you just saw however, change the contents of the string &lt;i&gt;variable&lt;/i&gt; greeting and make it refer to a different string, just as you can make a numeric variable currently holding the value 3 hold the value 4.&lt;a&gt;&lt;/a&gt;  &lt;p&gt;在Java中，你不能改变Java字串中的某个值，但是，你可以改变变量的内容，即使得字符串变量指向其他字符串。  &lt;p&gt;Isn't that a lot less efficient? It would seem simpler to change the code units than to build up a whole new string from scratch. Well, yes and no. Indeed, it isn't efficient to generate a new string that holds the concatenation of &amp;quot;Hel&amp;quot; and &amp;quot;p!&amp;quot;. But immutable strings have one great advantage: the compiler can arrange that strings are &lt;i&gt;shared.&lt;/i&gt;  &lt;p&gt;虽然生成新的字符组合效率会降低，但是不可变的字符串有一大优点：编译器可以将字符串共享。  &lt;p&gt;To understand how this works, think of the various strings as sitting in a common pool. String variables then point to locations in the pool. If you copy a string variable, both the original and the copy share the same characters. Overall, the designers of Java decided that the efficiency of sharing outweighs the inefficiency of string editing by extracting substrings and concatenating.  &lt;p&gt;要理解这个工作过程，假设各种字符串处在一个共享池中。字符串变量指向池中的某一个位置。如果你复制一个字符串，原字串和拷贝共享同一个字符序列。总之，Java设计者认为共享的有效性远大于提取字串在连接的字符串编辑的有效性。  &lt;p&gt;Look at your own programs; we suspect that most of the time, you don't change strings—you just compare them. Of course, in some cases, direct manipulation of strings is more efficient. (One example is assembling strings from individual characters that come from a file or the keyboard.) For these situations, Java provides a separate StringBuilder class that we describe in &lt;a&gt;Chapter 12&lt;/a&gt;. If you are not concerned with the efficiency of string handling, you can ignore StringBuilder and just use String.  &lt;p&gt;看看我们的程序，大多数时候，我们并不改变字串，而是进行比较。当然，有时候直接对字符串进行操作更为有效。（一个例子就是编译来自于一个文件或者键盘的独立字符序列。）对此种情况而言，Java提供独立的StringBuilder类。我们在12章中讨论。如果你对字符串处理的效率不感兴趣，你可以跳过StringBuilder，仅仅使用String就可以了。  &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;C++ NOTE&lt;/b&gt;  &lt;p&gt;   &lt;p&gt;C programmers generally are bewildered when they see Java strings for the first time because they think of strings as arrays of characters:  &lt;p&gt;C程序员第一次看到Java字符串的时候会感到疑惑，因为他们会认为字符串其实就是字符数组：  &lt;p&gt;char greeting[] = &amp;quot;Hello&amp;quot;;  &lt;p&gt;That is the wrong analogy: a Java string is roughly analogous to a char* pointer,&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;这是一个错误的类比：Java字符串组略的类同于一个char*指针。  &lt;p&gt;char* greeting = &amp;quot;Hello&amp;quot;;  &lt;p&gt;When you replace greeting with another string, the Java code does roughly the following:  &lt;p&gt;当你用另一个字符串代替greeting的时候，Java代码粗略的进行如下工作：  &lt;p&gt;char* temp = malloc(6);  &lt;p&gt;strncpy(temp, greeting, 3);  &lt;p&gt;strncpy(temp + 3, &amp;quot;p!&amp;quot;, 3);  &lt;p&gt;greeting = temp;  &lt;p&gt;Sure, now greeting points to the string &amp;quot;Help!&amp;quot;. And even the most hardened C programmer must admit that the Java syntax is more pleasant than a sequence of strncpy calls. But what if we make another assignment to greeting?  &lt;p&gt;当然，现在greeting指向字符串”Help!”。即使是最铁杆的C程序员也必须承认Java语句比使用一组strncpy函数要令人愉快。但如果我们要给greeting另作指派又会如何呢？  &lt;p&gt;greeting = &amp;quot;Howdy&amp;quot;;  &lt;p&gt;Don't we have a memory leak? After all, the original string was allocated on the heap. Fortunately, Java does automatic garbage collection. If a block of memory is no longer needed, it will eventually be recycled.  &lt;p&gt;这难道不会产生内存泄漏？毕竟，原字串是分配在堆上的。幸运的是，Java具有垃圾自动回收机制。如果某部分内存不再需要，它将最终被回收。  &lt;p&gt;If you are a C++ programmer and use the string class defined by ANSI C++, you will be much more comfortable with the Java String type. C++ string objects also perform automatic allocation and deallocation of memory. The memory management is performed explicitly by constructors, assignment operators, and destructors. However, C++ strings are mutable—you can modify individual characters in a string.  &lt;p&gt;如果你是C++程序员，并且使用由ANSI C++定义的string类，你将感到和Java中的String类型一样的舒服。C++中的string对象也能自动分配和释放内存。内存管理由构造函数、赋值运算符和析构函数清晰的执行。但是C++字符串是可变的，你可以修改字串中的独立字符。  &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;Concatenation &lt;/b&gt;&lt;b&gt;连接&lt;/b&gt;&lt;b&gt;&lt;/b&gt;  &lt;p&gt;Java, like most programming languages, allows you to use the + sign to join (concatenate) two strings.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;和大多数编程语言一样，Java也可以使用+号将两个字符串相连接。  &lt;p&gt;String expletive = &amp;quot;Expletive&amp;quot;;  &lt;p&gt;String PG13 = &amp;quot;deleted&amp;quot;;  &lt;p&gt;String message = expletive + PG13;  &lt;p&gt;The above code sets the variable message to the string &amp;quot;Expletivedeleted&amp;quot;. (Note the lack of a space between the words: the + sign joins two strings in the order received, &lt;i&gt;exactly&lt;/i&gt; as they are given.)  &lt;p&gt;以上的代码将变量message设置为字符串”Expletivedeleted”。（之所以两个单词之间会缺少空格，是因为+号精确的按照两个单词给出的顺序将其连接起来）  &lt;p&gt;When you concatenate a string with a value that is not a string, the latter is converted to a string. (As you see in &lt;a&gt;Chapter 5&lt;/a&gt;, every Java object can be converted to a string.) For example:&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;当你将一个字符串和一个非字符串连接时，后者将转换为字符串（第五章中，你将看到，Java对象都可以转换成字符串），例如：  &lt;p&gt;int age = 13;  &lt;p&gt;String rating = &amp;quot;PG&amp;quot; + age;  &lt;p&gt;sets rating to the string &amp;quot;PG13&amp;quot;.  &lt;p&gt;将rating设置为”PG13”。  &lt;p&gt;This feature is commonly used in output statements. For example,  &lt;p&gt;这一功能通常用于输出语句，例如  &lt;p&gt;System.out.println(&amp;quot;The answer is &amp;quot; + answer);  &lt;p&gt;is perfectly acceptable and will print what one would want (and with the correct spacing because of the space after the word is).  &lt;p&gt;可以很好的接受，并打印出你想要的（由于is 后面有空格，所以也能正确的打印出空格）  &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;Testing Strings for Equality &lt;/b&gt;&lt;b&gt;测试字符串相等&lt;/b&gt;&lt;b&gt;&lt;/b&gt;  &lt;p&gt;To test whether two strings are equal, use the equals method. The expression&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;要测试两个字符串是否相等，使用equals方法。表达式  &lt;p&gt;s.equals(t)  &lt;p&gt;returns TRue if the strings s and t are equal, false otherwise. Note that s and t can be string variables or string constants. For example, the expression  &lt;p&gt;返回true当字符串t和s相等时，否则，返回false。注意，s和t可以是字符串变量，也可以是字符串常量。例如，表达式  &lt;p&gt;&amp;quot;Hello&amp;quot;.equals(greeting)  &lt;p&gt;is perfectly legal. To test whether two strings are identical except for the upper/lowercase letter distinction, use the equalsIgnoreCase method.  &lt;p&gt;也是很合法的。要测试两个字符串除了大小写的差别是否相同，使用equalsIgnoreCase方法。  &lt;p&gt;&amp;quot;Hello&amp;quot;.equalsIgnoreCase(&amp;quot;hello&amp;quot;)  &lt;p&gt;Do &lt;i&gt;not&lt;/i&gt; use the == operator to test whether two strings are equal! It only determines whether or not the strings are stored in the same location. Sure, if strings are in the same location, they must be equal. But it is entirely possible to store multiple copies of identical strings in different places.  &lt;p&gt;不要使用==运算符来测试两个字符串是否相等！这种方法仅能判断两个字符串是否存储在同一个位置上。当然，如果字符串存储在同一个位置上，他们肯定相等。但是在不同的位置存储相同的字符串的多个拷贝也是完全有可能的。  &lt;p&gt;String greeting = &amp;quot;Hello&amp;quot;; //initialize greeting to a string  &lt;p&gt;if (greeting == &amp;quot;Hello&amp;quot;) . . .  &lt;p&gt;// probably true  &lt;p&gt;if (greeting.substring(0, 3) == &amp;quot;Hel&amp;quot;) . . .  &lt;p&gt;// probably false  &lt;p&gt;If the virtual machine would always arrange for equal strings to be shared, then you could use the == operator for testing equality. But only string &lt;i&gt;constants&lt;/i&gt; are shared, not strings that are the result of operations like + or substring. Therefore, &lt;i&gt;never&lt;/i&gt; use == to compare strings lest you end up with a program with the worst kind of bug—an intermittent one that seems to occur randomly.  &lt;p&gt;如果虚拟机总是将字符串分配为共享的，那么，你可以使用==运算符来测试相等。但是只有字符串常量是共享的，而那些+或者substring运算产生的字符串则不是共享的。所以，千万不可以使用==来比较字符串，以免你编写出的程序存在最糟糕的一种bug——一种不连续发生的貌似随机的Bug。  &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;C++ NOTE&lt;/b&gt;  &lt;p&gt;   &lt;p&gt;If you are used to the C++ string class, you have to be particularly careful about equality testing. The C++ string class does overload the == operator to test for equality of the string contents. It is perhaps unfortunate that Java goes out of its way to give strings the same &amp;quot;look and feel&amp;quot; as numeric values but then makes strings behave like pointers for equality testing. The language designers could have redefined == for strings, just as they made a special arrangement for +. Oh well, every language has its share of inconsistencies.&lt;a&gt;&lt;/a&gt;  &lt;p&gt;如果你习惯了C++的string类，那么你需要特别注意相等性测试。C++中的string类在进行字符串内容的相等比较的时候，运算符==进行了重载。Java打破自己的形式，给字符串赋予数字值一般的外表，而实际上又让这些字符串在比较的时候像指针一样，这也许是个不幸的事情。这门语言的设计者可以重新定义string中的==符号，就像他们特别分配了+号一样。嗯，好吧，每个语言都有其矛盾的一面。  &lt;p&gt;C programmers never use == to compare strings but use strcmp instead. The Java method compareTo is the exact analog to strcmp. You can use  &lt;p&gt;C程序员从不使用==来比较字符串，而是使用strcmp。Java中的compareTo方法精确的类似于strcmp，你可以使用  &lt;p&gt;if (greeting.compareTo(&amp;quot;Hello&amp;quot;) == 0) . . .  &lt;p&gt;but it seems clearer to use equals instead.  &lt;p&gt;但是使用equals似乎更清晰明了。  &lt;p&gt;The String class in Java contains more than 50 methods. A surprisingly large number of them are sufficiently useful so that we can imagine using them frequently. The following API note summarizes the ones we found most useful.  &lt;p&gt;Java中的String类有多达50个方法。这么多的方法都十分的有用，所以我们可以经常使用它们。下面的API注释中，我们总结了最有用的一些方法  &lt;p&gt;（译者：以下内容不再翻译，仅供参考。）  &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;NOTE&lt;/b&gt;  &lt;p&gt;   &lt;p&gt;You will find these API notes throughout the book to help you understand the Java Application Programming Interface (API). Each API note starts with the name of a class such as java.lang.String—the significance of the so-called &lt;i&gt;package&lt;/i&gt; name java.lang is explained in &lt;a&gt;Chapter 4&lt;/a&gt;. The class name is followed by the names, explanations, and parameter descriptions of one or more methods.  &lt;p&gt;We typically do not list all methods of a particular class but instead select those that are most commonly used, and describe them in a concise form. For a full listing, consult the on-line documentation.  &lt;p&gt;We also list the version number in which a particular class was introduced. If a method has been added later, it has a separate version number.  &lt;p&gt;  &lt;p&gt;&lt;b&gt;java.lang.String 1.0&lt;/b&gt;  &lt;ul&gt; &lt;li&gt;char charAt(int index)&lt;/ul&gt; &lt;p&gt;returns the code unit at the specified location. You probably don't want to call this method unless you are interested in low-level code units.  &lt;ul&gt; &lt;li&gt;int codePointAt(int index) &lt;b&gt;5.0&lt;/b&gt;&lt;/ul&gt; &lt;p&gt;returns the code point that starts or ends at the specified location.  &lt;ul&gt; &lt;li&gt;int offsetByCodePoints(int startIndex, int cpCount) &lt;b&gt;5.0&lt;/b&gt;&lt;/ul&gt; &lt;p&gt;returns the index of the code point that is cpCount code points away from the code point at startIndex.  &lt;ul&gt; &lt;li&gt;int compareTo(String other)&lt;/ul&gt; &lt;p&gt;returns a negative value if the string comes before other in dictionary order, a positive value if the string comes after other in dictionary order, or 0 if the strings are equal.  &lt;ul&gt; &lt;li&gt;boolean endsWith(String suffix)&lt;/ul&gt; &lt;p&gt;returns TRue if the string ends with suffix.  &lt;ul&gt; &lt;li&gt;boolean equals(Object other)&lt;/ul&gt; &lt;p&gt;returns true if the string equals other.  &lt;ul&gt; &lt;li&gt;boolean equalsIgnoreCase(String other)&lt;/ul&gt; &lt;p&gt;returns true if the string equals other, except for upper/lowercase distinction.  &lt;ul&gt; &lt;li&gt;int indexOf(String str)  &lt;li&gt;int indexOf(String str, int fromIndex)  &lt;li&gt;int indexOf(int cp)  &lt;li&gt;int indexOf(int cp, int fromIndex)&lt;/ul&gt; &lt;p&gt;return the start of the first substring equal to the string str or the code point cp, starting at index 0 or at fromIndex, or -1 if str does not occur in this string.  &lt;ul&gt; &lt;li&gt;int lastIndexOf(String str)  &lt;li&gt;int lastIndexOf(String str, int fromIndex)  &lt;li&gt;int lastindexOf(int cp)  &lt;li&gt;int lastindexOf(int cp, int fromIndex)&lt;/ul&gt; &lt;p&gt;return the start of the last substring equal to the string str or the code point cp, starting at the end of the string or at fromIndex.  &lt;ul&gt; &lt;li&gt;int length()&lt;/ul&gt; &lt;p&gt;returns the length of the string.  &lt;ul&gt; &lt;li&gt;int codePointCount(int startIndex, int endIndex) &lt;b&gt;5.0&lt;/b&gt;&lt;/ul&gt; &lt;p&gt;returns the number of code points between startIndex and endIndex - 1. Unpaired surrogates are counted as code points.  &lt;ul&gt; &lt;li&gt;String replace(CharSequence oldString, CharSequence newString)&lt;/ul&gt; &lt;p&gt;returns a new string that is obtained by replacing all substrings matching oldString in the string with the string newString. You can supply String or StringBuilder objects for the CharSequence parameters.  &lt;ul&gt; &lt;li&gt;boolean startsWith(String prefix)&lt;/ul&gt; &lt;p&gt;returns true if the string begins with prefix.  &lt;ul&gt; &lt;li&gt;String substring(int beginIndex)  &lt;li&gt;String substring(int beginIndex, int endIndex)&lt;/ul&gt; &lt;p&gt;return a new string consisting of all code units from beginIndex until the end of the string or until endIndex - 1.  &lt;ul&gt; &lt;li&gt;String toLowerCase()&lt;/ul&gt; &lt;p&gt;returns a new string containing all characters in the original string, with uppercase characters converted to lower case.  &lt;ul&gt; &lt;li&gt;String toUpperCase()&lt;/ul&gt; &lt;p&gt;returns a new string containing all characters in the original string, with lowercase characters converted to upper case.  &lt;ul&gt; &lt;li&gt;String trim()&lt;/ul&gt; &lt;p&gt;returns a new string by eliminating all leading and trailing spaces in the original string.  &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;Reading the On-Line API Documentation&lt;/b&gt;  &lt;p&gt;As you just saw, the String class has lots of methods. Furthermore, there are thousands of classes in the standard libraries, with many more methods. It is plainly impossible to remember all useful classes and methods. Therefore, it is essential that you become familiar with the on-line API documentation that lets you look up all classes and methods in the standard library. The API documentation is part of the JDK. It is in HTML format. Point your web browser to the docs/api/index.html subdirectory of your JDK installation. You will see a screen like that in &lt;a&gt;Figure 3-2&lt;/a&gt;.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;Figure 3-2. The three panes of the API documentation&lt;/b&gt;  &lt;p&gt;&lt;a&gt;[View full size image]&lt;/a&gt;  &lt;p&gt;&lt;a href="http://blufiles.storage.msn.com/y1p4iJf0JBb69li0Or0jLQIJMetRh8SvF9lV9Pt7M3WELKUPBuVWCYAipu6f7WyA14rH69ClcVRv6w"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px" height=171 alt="clip_image004" src="http://blufiles.storage.msn.com/y1p4iJf0JBb69mu_iiup8yshOI7JosP59YwGOGrhrQqW9UUtZ43rLmNFsboEuL9GtjTFAbah2fTkso" width=240 border=0&gt;&lt;/a&gt;  &lt;p&gt;The screen is organized into three frames. A small frame on the top left shows all available packages. Below it, a larger frame lists all classes. Click on any class name, and the API documentation for the class is displayed in the large frame to the right (see &lt;a&gt;Figure 3-3&lt;/a&gt;). For example, to get more information on the methods of the String class, scroll the second frame until you see the &lt;a&gt;String&lt;/a&gt; link, then click on it.  &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;Figure 3-3. Class description for the &lt;/b&gt;&lt;b&gt;String&lt;/b&gt;&lt;b&gt; class&lt;/b&gt;  &lt;p&gt;&lt;a&gt;[View full size image]&lt;/a&gt;  &lt;p&gt;&lt;a href="http://blufiles.storage.msn.com/y1p4iJf0JBb69nIcvl0UXWd0hv6IgLPqmXSomHA3b_pnx0nCin8BfJonYoX7kmpxYttpwmtemOj35Y"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px" height=171 alt="clip_image005" src="http://blufiles.storage.msn.com/y1p4iJf0JBb69k9QoJXW3DAwujExaFYoxv1cOJzdbYmAIFqy72ztrORZAjoKDFBhYYO4rYiiMhec6A" width=240 border=0&gt;&lt;/a&gt;  &lt;p&gt;Then scroll the frame on the right until you reach a summary of all methods, sorted in alphabetical order (see &lt;a&gt;Figure 3-4&lt;/a&gt;). Click on any method name for a detailed description of that method (see &lt;a&gt;Figure 3-5&lt;/a&gt;). For example, if you click on the compareToIgnoreCase link, you get the description of the compareToIgnoreCase method.  &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;Figure 3-4. Method summary of the &lt;/b&gt;&lt;b&gt;String&lt;/b&gt;&lt;b&gt; class&lt;/b&gt;  &lt;p&gt;&lt;a&gt;[View full size image]&lt;/a&gt;  &lt;p&gt;&lt;a href="http://blufiles.storage.msn.com/y1p4iJf0JBb69nguC_5KFqgocALl0j_DtDBs77BPmMeQHsuOwuVMw5t7FC9CvJprQ3BVbAxm3KPyiw"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px" height=171 alt="clip_image006" src="http://blufiles.storage.msn.com/y1p4iJf0JBb69kYsXC97EMXcygIFk6OA6YWfDXke0-KB3AApJM9c110ruFqug-ggqlagiBDXdsZHU4" width=240 border=0&gt;&lt;/a&gt;  &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;Figure 3-5. Detailed description of a &lt;/b&gt;&lt;b&gt;String&lt;/b&gt;&lt;b&gt; method&lt;/b&gt;  &lt;p&gt;&lt;a&gt;[View full size image]&lt;/a&gt;  &lt;p&gt;&lt;a href="http://blu1.storage.msn.com/y1p4XOwyNlfbX4md31n4iXE942-6f4s0FNaf7niQp8rU9pkQMFi7HuSp9AYc6oL4A8VIid5cND1eV5TaxGg11FbC0egcTBLkKZH"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px" height=171 alt="clip_image007" src="http://blu1.storage.msn.com/y1p4XOwyNlfbX6Rw-hKgRF886VLmLTDYsNKKVJforz7UVD-yFFJxdJepFDOIqIyEa03feGNaW-ZMnLy1CEzTo7jGcRTWYn94rHr" width=240 border=0&gt;&lt;/a&gt;  &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;TIP&lt;/b&gt;  &lt;p&gt;   &lt;p&gt;Bookmark the docs/api/index.html page in your browser right now.&lt;img src="http://c.services.spaces.live.com/CollectionWebService/c.gif?cid=-3743893519549122624&amp;page=RSS%3a+3.6+Strings%e5%ad%97%e7%ac%a6%e4%b8%b2&amp;referrer=" width="1px" height="1px" border="0" alt=""&gt;&lt;img style="position:absolute" alt="" width="0px" height="0px" src="http://c.live.com/c.gif?NC=31263&amp;amp;NA=1149&amp;amp;PI=73329&amp;amp;RF=&amp;amp;DI=3919&amp;amp;PS=85545&amp;amp;TP=x-spirit.spaces.live.com&amp;amp;GT1=X-Spirit"&gt;</description><comments>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!330.entry#comment</comments><guid isPermaLink="true">http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!330.entry</guid><pubDate>Wed, 12 Sep 2007 10:51:53 GMT</pubDate><slash:comments>0</slash:comments><msn:type>blogentry</msn:type><live:type>blogentry</live:type><live:typelabel>Blog entry</live:typelabel><wfw:commentRss>http://X-Spirit.spaces.live.com/blog/cns!CC0B04AE126337C0!330/comments/feed.rss</wfw:commentRss><wfw:comment>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!330.entry#comment</wfw:comment><dcterms:modified>2007-09-12T10:57:47Z</dcterms:modified></item><item><title>3.5.4 其他运算符</title><link>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!314.entry</link><description>&lt;p&gt;&lt;b&gt;Bitwise Operators 位运算符&lt;/b&gt; &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;When working with any of the integer types, you have operators that can work directly with the bits that make up the integers. This means that you can use masking techniques to get at individual bits in a number. The bitwise operators are&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&amp;amp; (&amp;quot;and&amp;quot;) | (&amp;quot;or&amp;quot;) ^ (&amp;quot;xor&amp;quot;) ~ (&amp;quot;not&amp;quot;) &lt;p&gt;These operators work on bit patterns. For example, if n is an integer variable, then &lt;p&gt;int fourthBitFromRight = (n &amp;amp; 8) / 8; &lt;p&gt;gives you a 1 if the fourth bit from the right in the binary representation of n is 1, and 0 if not. Using &amp;amp; with the appropriate power of 2 lets you mask out all but a single bit. &lt;p&gt;在对整数类型进行处理的时，还有能够直接处理构成整数的各个位的运算符。这意味着你可以使用掩码技术来处理一个数字中的各个独立位。这些位运算符是： &lt;p&gt;&amp;amp; (&amp;quot;与&amp;quot;) | (&amp;quot;或&amp;quot;) ^ (&amp;quot;异或&amp;quot;) ~ (&amp;quot;非&amp;quot;) &lt;p&gt;这些运算符工作在比特形式下。例如，如果n是一个整型变量，那么 &lt;p&gt;int fourthBitFromRight = (n &amp;amp; 8) / 8; &lt;p&gt;这条语句将在n的二进制表示从右起第四位是1时得出结果1，否则为0。使用&amp;amp;符号搭配适当的2的指数幂可以使你屏蔽某一个位以外的所有位。 &lt;p&gt;&lt;a&gt;&lt;/a&gt;NOTE 注释 &lt;p&gt;  &lt;p&gt;When applied to boolean values, the &amp;amp; and | operators yield a boolean value. These operators are similar to the &amp;amp;&amp;amp; and || operators, except that the &amp;amp; and | operators are not evaluated in &amp;quot;short circuit&amp;quot; fashion. That is, both arguments are first evaluated before the result is computed. &lt;p&gt;当应用于布尔值时，&amp;amp;和|运算将产生一个布尔值。这些运算符和&amp;amp;&amp;amp;以及||运算符是类似的，但是&amp;amp;和|并不以短路形式运算。也就是说，两个参数在结果算出之前就参与运算。（译者注，参见&lt;a href="http://www.itsway.net/java/java020505.aspx"&gt;http://www.itsway.net/java/java020505.aspx&lt;/a&gt;） &lt;p&gt;There are also &amp;gt;&amp;gt; and &amp;lt;&amp;lt; operators, which shift a bit pattern to the right or left. These operators are often convenient when you need to build up bit patterns to do bit masking: &lt;p&gt;int fourthBitFromRight = (n &amp;amp; (1 &amp;lt;&amp;lt; 3)) &amp;gt;&amp;gt; 3; &lt;p&gt;Finally, a &amp;gt;&amp;gt;&amp;gt; operator fills the top bits with zero, whereas &amp;gt;&amp;gt; extends the sign bit into the top bits. There is no &amp;lt;&amp;lt;&amp;lt; operator. &lt;p&gt;还有&amp;gt;&amp;gt;和&amp;lt;&amp;lt;运算符，可以向左或者向右移动一位。这些运算符在你需要通过位模式来执行按位掩码时是非常方便的，例如： &lt;p&gt;int fourthBitFromRight = (n &amp;amp; (1 &amp;lt;&amp;lt; 3)) &amp;gt;&amp;gt; 3; &lt;p&gt;最后，&amp;gt;&amp;gt;&amp;gt;运算符用0填写头两位，而&amp;gt;&amp;gt;把符号为增加到头一位。没有&amp;lt;&amp;lt;&amp;lt;运算符。 &lt;p&gt;&lt;a&gt;&lt;/a&gt;CAUTION 注意 &lt;p&gt;  &lt;p&gt;The right-hand side argument of the shift operators is reduced modulo 32 (unless the left-hand side is a long, in which case the right-hand side is reduced modulo 64). For example, the value of 1 &amp;lt;&amp;lt; 35 is the same as 1 &amp;lt;&amp;lt; 3 or 8.&lt;a&gt;&lt;/a&gt; &lt;p&gt;移位运算符右边的参数被减少到32（除非左边的参数较长，这种情况下，右边的较少到64）。例如，1&amp;lt;&amp;lt;35的值和1&amp;lt;&amp;lt;3或者1&amp;lt;&amp;lt;8是一样的。 &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;C++ NOTE C++注释 &lt;p&gt;  &lt;p&gt;In C/C++, there is no guarantee as to whether &amp;gt;&amp;gt; performs an arithmetic shift (extending the sign bit) or a logical shift (filling in with zeroes). Implementors are free to choose whatever is more efficient. That means the C/C++ &amp;gt;&amp;gt; operator is really only defined for non-negative numbers. Java removes that ambiguity.&lt;a&gt;&lt;/a&gt; &lt;p&gt;在C/C++中，并不保证&amp;gt;&amp;gt;进行的是算术移位(扩展符号位)还是逻辑移位（以0填充）。设备可以在二者中选择更有效的操作。这就意味着C/C++中的&amp;gt;&amp;gt;运算符的确仅仅是为非负数定义的。Java去除了这种歧义性。 &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;Mathematical Functions and Constants 数学函数与常量&lt;/b&gt; &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;The Math class contains an assortment of mathematical functions that you may occasionally need, depending on the kind of programming that you do. &lt;p&gt;To take the square root of a number, you use the sqrt method: &lt;p&gt;Math类包含一组你有时会用到的数学函数，这取决于你所编程序的类型。要计算一个数字的平方根，需要使用sqrt方法： &lt;p&gt;double x = 4; &lt;p&gt;double y = Math.sqrt(x); &lt;p&gt;System.out.println(y); // 打印 2.0 &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;NOTE 注释 &lt;p&gt;  &lt;p&gt;There is a subtle difference between the println method and the sqrt method. The println method operates on an object, System.out, defined in the System class. But the sqrt method in the Math class does not operate on any object. Such a method is called a static method. You can learn more about static methods in &lt;a&gt;Chapter 4&lt;/a&gt;. &lt;p&gt;println方法和sqrt方法有一个微妙的差别。println方法对一个对象进行操作，即System类中定义的System.out。但是Math类中的sqrt方法并不对任何对象进行操作。这样的方法称作静态方法。你可在第四章中学习更多有关静态方法的知识。 &lt;p&gt;The Java programming language has no operator for raising a quantity to a power: you must use the pow method in the Math class. The statement&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;double y = Math.pow(x, a); &lt;p&gt;sets y to be x raised to the power a (x&lt;sup&gt;a&lt;/sup&gt;). The pow method has parameters that are both of type double, and it returns a double as well. &lt;p&gt;Java语言没有指数幂运算符，你需要使用Math类中的pow方法。语句 &lt;p&gt;double y = Math.pow(x, a); &lt;p&gt;将y的值设置为x的a次幂。pow方法的两个参数都应该是double类型，且返回值也是double类型。 &lt;p&gt;The Math class supplies the usual trigonometric functions&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;Math类提供了常用的三角函数： &lt;p&gt;Math.sin &lt;p&gt;Math.cos &lt;p&gt;Math.tan &lt;p&gt;Math.atan &lt;p&gt;Math.atan2 &lt;p&gt;and the exponential function and its inverse, the natural log:&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;以及指数函数及其逆运算——自然对数： &lt;p&gt;Math.exp &lt;p&gt;Math.log &lt;p&gt;Finally, two constants denote the closest possible approximations to the mathematical constants p and e:&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;最后，介绍两个与数学常量p 和 e的值非常近似的常量： &lt;p&gt;Math.PI &lt;p&gt;Math.E &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;TIP提示 &lt;p&gt;  &lt;p&gt;Starting with JDK 5.0, you can avoid the Math prefix for the mathematical methods and constants by adding the following line to the top of your source file:&lt;a&gt;&lt;/a&gt; &lt;p&gt;从JDK5.0开始，你可以在源文件起始处使用如下代码来避免每次使用数学方法和常量的Math前缀。 &lt;p&gt;import static java.lang.Math.*; &lt;p&gt;For example, &lt;p&gt;例如: &lt;p&gt;System.out.println(&amp;quot;The square root of \u03C0 is &amp;quot; + sqrt(PI)); &lt;p&gt;We discuss static imports in &lt;a&gt;Chapter 4&lt;/a&gt;. &lt;p&gt;我们将在第四章讨论静态导入。 &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;NOTE注意 &lt;p&gt;  &lt;p&gt;The functions in the Math class use the routines in the computer's floating-point unit for fastest performance. If completely predictable results are more important than fast performance, use the StrictMath class instead. It implements the algorithms from the &amp;quot;Freely Distributable Math Library&amp;quot; fdlibm, guaranteeing identical results on all platforms. See &lt;a href="http://www.netlib.org/fdlibm/index.html"&gt;http://www.netlib.org/fdlibm/index.html&lt;/a&gt; for the source of these algorithms. (Whenever fdlibm provides more than one definition for a function, the StrictMath class follows the IEEE 754 version whose name starts with an &amp;quot;e&amp;quot;.)&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;为了获得最快的性能，Math类中的函数使用计算机浮点运算单元中的例程。如果可预测的结果完全重于快速表现，则使用StrictMath类。这个类从“自由分布数学库”中实现运算，保证各个平台上的统一的结果。算法源码参见&lt;a href="http://www.netlib.org/fdlibm/index.html"&gt;http://www.netlib.org/fdlibm/index.html&lt;/a&gt;。不论何时fdlibm提供对一个函数的多种定义，StrictMath类始终遵循以“e”开始命名的IEEE 754版本。 &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;Conversions Between Numeric Types 数字类型之间的转换&lt;/b&gt; &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;It is often necessary to convert from one numeric type to another. &lt;a&gt;Figure 3-1&lt;/a&gt; shows the legal conversions. &lt;p&gt;在多种数字类型之间进行转换是常有的事，图3-1说明了合法的转换： &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;图&lt;/b&gt;&lt;b&gt;3-1 数字类型之间的合法转换&lt;/b&gt; &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;img height=195 src="http://blu1.storage.msn.com/y1p4XOwyNlfbX7hcwXeP5zJj3JCyjpBgngo8JUaIVEJr7GWveTs7sMLg6hVqDBj9-xZpldkZSKGjoNqYK3KT4PCbxSQUCFfj9p0" width=366 border=0&gt; &lt;p&gt;The six solid arrows in &lt;a&gt;Figure 3-1&lt;/a&gt; denote conversions without information loss. The three dotted arrows denote conversions that may lose precision. For example, a large integer such as 123456789 has more digits than the float type can represent. When the integer is converted to a float, the resulting value has the correct magnitude but it loses some precision.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;图3-1中的六个实箭头表示无信息丢失的转换。三个虚箭头表示可能丢失精度的转换。例如，一个大的整型数字，如123456789，其位数多于浮点型能够表示的位数。当这个整型数转换成浮点型时，结果值仍然很大，但是丢失了精度。 &lt;p&gt;int n = 123456789; &lt;p&gt;float f = n; // f is 1.23456792E8 &lt;p&gt;When two values with a binary operator (such as n + f where n is an integer and f is a floating-point value) are combined, both operands are converted to a common type before the operation is carried out.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;当两个数字和一个二进制运算符结合在一起（例如n+f中，n是一个整数，而f是一个浮点数），两个操作数都会在运算之前被转换为通用类型。 &lt;ul&gt; &lt;li&gt;If either of the operands is of type double, the other one will be converted to a double. &lt;li&gt;Otherwise, if either of the operands is of type float, the other one will be converted to a float. &lt;li&gt;Otherwise, if either of the operands is of type long, the other one will be converted to a long. &lt;li&gt;Otherwise, both operands will be converted to an int.&lt;/ul&gt; &lt;ul&gt; &lt;li&gt;如果两个操作数有一个是double型，另一个转换为double型。 &lt;li&gt;否则，如果两个操作数有一个为float型，则另一个转换为float型。 &lt;li&gt;否则，如果两个操作数有一个为long型，则另一个转换为long型。 &lt;li&gt;否则，两个操作数都被转换为整型。&lt;/ul&gt; &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;Casts&lt;/b&gt; &lt;p&gt;In the preceding section, you saw that int values are automatically converted to double values when necessary. On the other hand, there are obviously times when you want to consider a double as an integer. Numeric conversions are possible in Java, but of course information may be lost. Conversions in which loss of information is possible are done by means of casts. The syntax for casting is to give the target type in parentheses, followed by the variable name. For example:&lt;a&gt;&lt;/a&gt; &lt;p&gt;在前面的章节中，你可以看到整型值在需要的时候可以自动转换为double型，另一方面，有时你也希望把double型转换为整型。在Java中，数字类型的转换是允许的，但是丢失信息也是自然的。丢失信息的转换是依靠强制转换来完成的。强制转换的语句是在变量名前加上由圆括号括起来的目标类型，例如： &lt;p&gt;double x = 9.997; &lt;p&gt;int nx = (int) x; &lt;p&gt;Then, the variable nx has the value 9 because casting a floating-point value to an integer discards the fractional part. &lt;p&gt;这样，变量nx的值就是0，因为浮点型向整型的强制转换舍弃了小数部分。 &lt;p&gt;If you want to round a floating-point number to the nearest integer (which is the more useful operation in most cases), use the Math.round method:&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;如果你想把一个浮点数四舍五入成最接近的整数（在大多数情况下，这是更有用的操作），使用Math.round方法： &lt;p&gt;double x = 9.997; &lt;p&gt;int nx = (int) Math.round(x); &lt;p&gt;Now the variable nx has the value 10. You still need to use the cast (int) when you call round. The reason is that the return value of the round method is a long, and a long can only be assigned to an int with an explicit cast because there is the possibility of information loss. &lt;p&gt;现在，变量nx的值就是10了。在你调用round方法时，你还是需要进行强制转换(int)。原因是round方法的返回值类型是long，而long类型在给int变量赋值时，由于可能产生信息丢失，所以必须采用显式转换。 &lt;p&gt;&lt;a&gt;&lt;/a&gt;CAUTION注意 &lt;p&gt;If you try to cast a number of one type to another that is out of the range for the target type, the result will be a truncated number that has a different value. For example, (byte) 300 is actually 44. &lt;p&gt;如果你试图将某种类型的数字转换为比原类型范围小的目标类型，结果将被截断，产生一个不同的值，例如(byte) 300 的结果实际上是44。 &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;C++ NOTE C++注释 &lt;p&gt;You cannot cast between boolean values and any numeric type. This convention prevents common errors. In the rare case that you want to convert a boolean value to a number, you can use a conditional expression such as b ? 1 : 0. &lt;p&gt;你不能在布尔型和数字类型之间进行转换。这种转换将产生常见错误。极少数情况下，你希望将布尔值转换为一个数字，此时你可以使用条件表达式，例如b?1:0 &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;Parentheses and Operator Hierarchy 圆括号和运算优先级&lt;/b&gt; &lt;p&gt;&lt;a&gt;Table 3-4&lt;/a&gt; shows the precedence of operators. If no parentheses are used, operations are performed in the hierarchical order indicated. Operators on the same level are processed from left to right, except for those that are right associative, as indicated in the table. For example, because &amp;amp;&amp;amp; has a higher precedence than ||, the expression&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;Table 3-4. Operator Precedence&lt;/b&gt; &lt;p&gt;&lt;b&gt;Operators&lt;/b&gt; &lt;p&gt;&lt;b&gt;Associativity&lt;/b&gt; &lt;p&gt;[] . () (method call) &lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;Left to right &lt;p&gt;! ~ ++ -- + (unary) – (unary) () (cast) new &lt;p&gt;Right to left &lt;p&gt;* / % &lt;p&gt;Left to right &lt;p&gt;+ - &lt;p&gt;Left to right &lt;p&gt;&amp;lt;&amp;lt; &amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;Left to right &lt;p&gt;&amp;lt; &amp;lt;= &amp;gt; &amp;gt;= instanceof &lt;p&gt;Left to right &lt;p&gt;== != &lt;p&gt;Left to right &lt;p&gt;&amp;amp; &lt;p&gt;Left to right &lt;p&gt;^ &lt;p&gt;Left to right &lt;p&gt;| &lt;p&gt;Left to right &lt;p&gt;&amp;amp;&amp;amp; &lt;p&gt;Left to right &lt;p&gt;|| &lt;p&gt;Left to right &lt;p&gt;?: &lt;p&gt;Right to left &lt;p&gt;= += -= *= /= %= &amp;amp;= |= ^= &amp;lt;&amp;lt;= &amp;gt;&amp;gt;= &amp;gt;&amp;gt;&amp;gt;= &lt;p&gt;Right to left &lt;p&gt;表3-4展示了运算符的优先级。如果没有使用括号，运算符将按照表中显示的优先级进行运算。除了表中指明的右结合的运算符，同一级别的运算符自左向右运算。例如，&amp;amp;&amp;amp;和优先级高于||，表达式 &lt;p&gt;a &amp;amp;&amp;amp; b || c &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;means等于 &lt;p&gt;(a &amp;amp;&amp;amp; b) || c &lt;p&gt;Because += associates right to left, the expression &lt;p&gt;由于+=自右向左结合，表达式 &lt;p&gt;a += b += c &lt;p&gt;means等于 &lt;p&gt;a += (b += c) &lt;p&gt;That is, the value of b += c (which is the value of b after the addition) is added to a. &lt;p&gt;也就是b+=c的值（即第一次加法后b的值）再加到a上。 &lt;p&gt;&lt;a&gt;&lt;/a&gt;C++ NOTE C++注释 &lt;p&gt;Unlike C or C++, Java does not have a comma operator. However, you can use a comma-separated list of expressions in the first and third slot of a for statement.&lt;a&gt;&lt;/a&gt; &lt;p&gt;与C或C++不同，Java没有逗号运算符，但是你可以在一个for语句中的第一个和第三个位置使用一个逗号分隔的表达式。 &lt;p&gt;C语言中的逗号运算符： &lt;p&gt;C语言中逗号“，”也是一种运算符，称为逗号运算符。 其功能是把两个表达式连接起来组成一个表达式， 称为逗号表达式。&lt;br&gt;其一般形式为： 表达式1，表达式2 其求值过程是分别求两个表达式的值，并以表达式2的值作为整个逗号表达式的值。&lt;br&gt;void main(){ &lt;br&gt;int a=2,b=4,c=6,x,y; &lt;br&gt;y=(x=a+b),(b+c); &lt;br&gt;printf(&amp;quot;y=%d,x=%d&amp;quot;,y,x); &lt;br&gt;} &lt;br&gt;a&amp;lt;--2,b&amp;lt;--4,c&amp;lt;--6,x&amp;lt;--0,y&amp;lt;--0 &lt;br&gt;x&amp;lt;--a+b,y&amp;lt;---b+c &lt;br&gt;本例中，y等于整个逗号表达式的值，也就是表达式2的值，x是第一个表达式的值。对于逗号表达式还要说明几点：&lt;br&gt;1.逗号表达式一般形式中的表达式1和表达式2 也可以又是逗号表达式。例如： 表达式1，(表达式2，表达式3) 形成了嵌套情形。因此可以把逗号表达式扩展为以下形式： 表达式1，表达式2，…表达式n 整个逗号表达式的值等于表达式n的值。&lt;br&gt;2.程序中使用逗号表达式，通常是要分别求逗号表达式内各表达式的值，并不一定要求整个逗号表达式的值。&lt;br&gt;3.并不是在所有出现逗号的地方都组成逗号表达式，如在变量说明中，函数参数表中逗号只是用作各变量之间的间隔符。&lt;br&gt;以上是摘抄来的 我本人觉得自己最常使用逗号运算符是在&lt;br&gt;for循环里&lt;br&gt;for (i = 0, j = 0; i &amp;lt; 3 &amp;amp;&amp;amp; j &amp;lt; 3; i++, j+=2) { &lt;br&gt;printf(&amp;quot;i = %d, j = %d&amp;quot;,i,j); &lt;br&gt;} &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;&lt;b&gt;Enumerated Types 枚举类型&lt;/b&gt; &lt;p&gt;Sometimes, a variable should only hold a restricted set of values. For example, you may sell clothes or pizza in four sizes: small, medium, large, and extra large. Of course, you could encode these sizes as integers 1, 2, 3, 4, or characters S, M, L, and X. But that is an error-prone setup. It is too easy for a variable to hold a wrong value (such as 0 or m).&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;有时候，一个变量需要仅保存一组有限值的集合。例如，你可能出售四种尺寸的衣服或者匹萨：小号、中号、大号和特大号。当然，你可以给这四种型号编号为1，2，3，4或者S,M,L,X。但这是一个具有错误倾向的设置。变量很可能会承载一个错误的值（比如0或者m）。 &lt;p&gt;Starting with JDK 5.0, you can define your own enumerated type whenever such a situation arises. An enumerated type has a finite number of named values. For example, &lt;p&gt;从JDK5.0开始，你可以在遇到这种情况时定义自己的枚举类型。一个枚举类型具有有限个数的命名变量。例如： &lt;p&gt;enum Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE }; &lt;p&gt;Now you can declare variables of this type: &lt;p&gt;现在，你可以定义这种类型的变量： &lt;p&gt;Size s = Size.MEDIUM; &lt;p&gt;A variable of type Size can hold only one of the values listed in the type declaration or the special value null that indicates that the variable is not set to any value at all. &lt;p&gt;一个Size类型的变量只能承载Size类型中声明的一个值，或者承载一个特殊值null来表示这个变量没有被设置任何值。 &lt;p&gt;We discuss enumerated types in greater detail in &lt;a&gt;Chapter 5&lt;/a&gt;. &lt;p&gt;我们将在第五章更详细的讨论枚举类型。&lt;img src="http://c.services.spaces.live.com/CollectionWebService/c.gif?cid=-3743893519549122624&amp;page=RSS%3a+3.5.4+%e5%85%b6%e4%bb%96%e8%bf%90%e7%ae%97%e7%ac%a6&amp;referrer=" width="1px" height="1px" border="0" alt=""&gt;&lt;img style="position:absolute" alt="" width="0px" height="0px" src="http://c.live.com/c.gif?NC=31263&amp;amp;NA=1149&amp;amp;PI=73329&amp;amp;RF=&amp;amp;DI=3919&amp;amp;PS=85545&amp;amp;TP=x-spirit.spaces.live.com&amp;amp;GT1=X-Spirit"&gt;</description><comments>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!314.entry#comment</comments><guid isPermaLink="true">http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!314.entry</guid><pubDate>Tue, 11 Sep 2007 00:50:42 GMT</pubDate><slash:comments>1</slash:comments><msn:type>blogentry</msn:type><live:type>blogentry</live:type><live:typelabel>Blog entry</live:typelabel><wfw:commentRss>http://X-Spirit.spaces.live.com/blog/cns!CC0B04AE126337C0!314/comments/feed.rss</wfw:commentRss><wfw:comment>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!314.entry#comment</wfw:comment><dcterms:modified>2007-09-11T00:57:00Z</dcterms:modified></item><item><title>3.5.3 Relational and boolean Operators关系和逻辑运算符</title><link>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!312.entry</link><description>&lt;p&gt;   &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;Java has the full complement of relational operators. To test for equality you use a double equal sign, ==. For example, the value of  &lt;p&gt;Java有完全的关系运算符补充。要测试相等，你可以使用一个双等号，==。比如，  &lt;p&gt;3 == 7  &lt;p&gt;is false.  &lt;p&gt;3==7的值是false。  &lt;p&gt;Use a != for inequality. For example, the value of  &lt;p&gt;使用!=来测试不等。比如：  &lt;p&gt;3 != 7  &lt;p&gt;is true.  &lt;p&gt;3 != 7的值是true。  &lt;p&gt;Finally, you have the usual &amp;lt; (less than), &amp;gt; (greater than), &amp;lt;= (less than or equal), and &amp;gt;= (greater than or equal) operators.  &lt;p&gt;最后，还有普通的&amp;lt; （小于），&amp;gt; （大于），&amp;lt;= （小于等于），和 &amp;gt;= (大于等于) 运算符。  &lt;p&gt;Java, following C++, uses &amp;amp;&amp;amp; for the logical &amp;quot;and&amp;quot; operator and || for the logical &amp;quot;or&amp;quot; operator. As you can easily remember from the != operator, the exclamation point ! is the logical negation operator. The &amp;amp;&amp;amp; and || operators are evaluated in &amp;quot;short circuit&amp;quot; fashion. The second argument is not evaluated if the first argument already determines the value. If you combine two expressions with the &amp;amp;&amp;amp; operator,  &lt;p&gt;Java，和C++一样，使用&amp;amp;&amp;amp;表示逻辑与，使用||表示逻辑或。由于你能轻易记得!=运算符，所以感叹号!就表示逻辑非。 &amp;amp;&amp;amp; 和 || 运算符采用“短路”方式求值。如果第一个参数的值已经确定，则不需要考虑第二个参数的值。如果你将两个表达式用&amp;amp;&amp;amp;连接，  &lt;p&gt;expression&lt;sub&gt;1&lt;/sub&gt; &amp;amp;&amp;amp; expression&lt;sub&gt;2&lt;/sub&gt;  &lt;p&gt;and the truth value of the first expression has been determined to be false, then it is impossible for the result to be TRue. Thus, the value for the second expression is not calculated. This behavior can be exploited to avoid errors. For example, in the expression  &lt;p&gt;并且第一个表达式的真值是false，那么运算结果不可能为true。因此第二个表达式的值不参与运算。该特性可以用来避免错误。例如，在表达式  &lt;p&gt;x != 0 &amp;amp;&amp;amp; 1 / x &amp;gt; x + y // no division by 0  &lt;p&gt;the second part is never evaluated if x equals zero. Thus, 1 / x is not computed if x is zero, and no divide-by-zero error can occur.  &lt;p&gt;当中，第二部分如果x等于0的话就不被计算。  &lt;p&gt;Similarly, the value of expression&lt;sub&gt;1&lt;/sub&gt; || expression&lt;sub&gt;2&lt;/sub&gt; is automatically true if the first expression is true, without evaluation of the second expression.  &lt;p&gt;类似的，表达式expression&lt;sub&gt;1&lt;/sub&gt; || expression&lt;sub&gt;2 &lt;/sub&gt;中，如果第一表达式为true，那么整个表达式的值就为true,而不计算第二个表达式的值。  &lt;p&gt;Finally, Java supports the ternary ?: operator that is occasionally useful. The expression  &lt;p&gt;最后，Java支持偶尔很有用的三目运算符?:。表达式  &lt;p&gt;condition ? expression&lt;sub&gt;1&lt;/sub&gt; : expression&lt;sub&gt;2&lt;/sub&gt;  &lt;p&gt;evaluates to the first expression if the condition is TRue, to the second expression otherwise. For example,  &lt;p&gt;如果condition为ture则计算expression&lt;sub&gt;1&lt;/sub&gt;的值，否则计算expression&lt;sub&gt;2&lt;/sub&gt;的值。例如：  &lt;p&gt;x &amp;lt; y ? x : y  &lt;p&gt;gives the smaller of x and y.  &lt;p&gt;求得x和y当中较小的一个。&lt;img src="http://c.services.spaces.live.com/CollectionWebService/c.gif?cid=-3743893519549122624&amp;page=RSS%3a+3.5.3+Relational+and+boolean+Operators%e5%85%b3%e7%b3%bb%e5%92%8c%e9%80%bb%e8%be%91%e8%bf%90%e7%ae%97%e7%ac%a6&amp;referrer=" width="1px" height="1px" border="0" alt=""&gt;&lt;img style="position:absolute" alt="" width="0px" height="0px" src="http://c.live.com/c.gif?NC=31263&amp;amp;NA=1149&amp;amp;PI=73329&amp;amp;RF=&amp;amp;DI=3919&amp;amp;PS=85545&amp;amp;TP=x-spirit.spaces.live.com&amp;amp;GT1=X-Spirit"&gt;</description><comments>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!312.entry#comment</comments><guid isPermaLink="true">http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!312.entry</guid><pubDate>Mon, 10 Sep 2007 11:10:08 GMT</pubDate><slash:comments>0</slash:comments><msn:type>blogentry</msn:type><live:type>blogentry</live:type><live:typelabel>Blog entry</live:typelabel><wfw:commentRss>http://X-Spirit.spaces.live.com/blog/cns!CC0B04AE126337C0!312/comments/feed.rss</wfw:commentRss><wfw:comment>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!312.entry#comment</wfw:comment><dcterms:modified>2007-09-10T11:11:52Z</dcterms:modified></item><item><title>3.5.2 Operators运算符之增量运算符和减量运算符</title><link>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!309.entry</link><description>&lt;p&gt;&lt;b&gt;Increment and Decrement Operators&lt;/b&gt;&lt;b&gt;增量和减量运算符&lt;/b&gt;  &lt;p&gt;Programmers, of course, know that one of the most common operations with a numeric variable is to add or subtract 1. Java, following in the footsteps of C and C++, has both increment and decrement operators: n++ adds 1 to the current value of the variable n, and n-- subtracts 1 from it. For example, the code&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;程序员，自然地，知道一种最普通的带有数字变量的运算符，用来实现加1或者减1。Java步C和C++的后尘，也有增量和减量运算符：n++ 给当前变量的值加1，而n-- 从n中减去1。例如，代码：  &lt;p&gt;int n = 12;  &lt;p&gt;n++;  &lt;p&gt;changes n to 13. Because these operators change the value of a variable, they cannot be applied to numbers themselves. For example, 4++ is not a legal statement.  &lt;p&gt;将n改变为13。由于这些运算符用来改变变量的值，所以他们不能被用来改变数字本身。例如4++就不是一个合法的语句。  &lt;p&gt;There are actually two forms of these operators; you have seen the &amp;quot;postfix&amp;quot; form of the operator that is placed after the operand. There is also a prefix form, ++n. Both change the value of the variable by 1. The difference between the two only appears when they are used inside expressions. The prefix form does the addition first; the postfix form evaluates to the old value of the variable.  &lt;p&gt;这些运算符实际上有两种形式；你见过运算符被置于操作数后面的“后缀”形式。还有一个前缀形式，++n。都是改变变量的值多一或少一。二者的不同仅体现在他们用于表达式的时候。前缀形式先做加法运算；后缀形式求得变量的原值。  &lt;p&gt;int m = 7;  &lt;p&gt;int n = 7;  &lt;p&gt;int a = 2 * ++m; // now a is 16, m is 8  &lt;p&gt;int b = 2 * n++; // now b is 14, n is 8  &lt;p&gt;We recommend against using ++ inside other expressions because this often leads to confusing code and annoying bugs.  &lt;p&gt;我们不推荐在其他表达式中使用++，因为这经常导致混乱的代码以及恼人的bug。  &lt;p&gt;(Of course, while it is true that the ++ operator gives the C++ language its name, it also led to the first joke about the language. C++ haters point out that even the name of the language contains a bug: &amp;quot;After all, it should really be called ++C, because we only want to use a language after it has been improved.&amp;quot;)  &lt;p&gt;（当然，当++运算符赋予C++语言这个名字的时候，它也引发了这个语言的第一个笑话。C++的反对者指出就连这个程序语言的名字都存在bug:“毕竟，她真的该叫做C++，因为我们只想在语言被改进以后使用它。”）&lt;img src="http://c.services.spaces.live.com/CollectionWebService/c.gif?cid=-3743893519549122624&amp;page=RSS%3a+3.5.2+Operators%e8%bf%90%e7%ae%97%e7%ac%a6%e4%b9%8b%e5%a2%9e%e9%87%8f%e8%bf%90%e7%ae%97%e7%ac%a6%e5%92%8c%e5%87%8f%e9%87%8f%e8%bf%90%e7%ae%97%e7%ac%a6&amp;referrer=" width="1px" height="1px" border="0" alt=""&gt;&lt;img style="position:absolute" alt="" width="0px" height="0px" src="http://c.live.com/c.gif?NC=31263&amp;amp;NA=1149&amp;amp;PI=73329&amp;amp;RF=&amp;amp;DI=3919&amp;amp;PS=85545&amp;amp;TP=x-spirit.spaces.live.com&amp;amp;GT1=X-Spirit"&gt;</description><comments>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!309.entry#comment</comments><guid isPermaLink="true">http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!309.entry</guid><pubDate>Fri, 07 Sep 2007 00:58:22 GMT</pubDate><slash:comments>1</slash:comments><msn:type>blogentry</msn:type><live:type>blogentry</live:type><live:typelabel>Blog entry</live:typelabel><wfw:commentRss>http://X-Spirit.spaces.live.com/blog/cns!CC0B04AE126337C0!309/comments/feed.rss</wfw:commentRss><wfw:comment>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!309.entry#comment</wfw:comment><dcterms:modified>2007-09-07T00:58:52Z</dcterms:modified></item><item><title>3.5.1 Operators运算符之算术运算符</title><link>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!304.entry</link><description>&lt;p&gt;The usual arithmetic operators + – * / are used in Java for addition, subtraction, multiplication, and division. The / operator denotes integer division if both arguments are integers, and floating-point division otherwise. Integer remainder (sometimes called modulus) is denoted by %. For example, 15 / 2 is 7, 15 % 2 is 1, and 15.0 / 2 is 7.5.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;通常的算术运算符+ – * /在Java中用来进行加，减，乘，除。当两个操作数都是整数时，运算符/表示整数除法，其他情况表示浮点除法。整数余数（有时也叫模数）用%表示。例如，15 / 2 等于 7, 15 % 2 等于 1, 而 15.0 / 2 等于 7.5。 &lt;p&gt;Note that integer division by 0 raises an exception, whereas floating-point division by 0 yields an infinite or NaN result.&lt;a&gt;&lt;/a&gt; &lt;p&gt;注意整数除法中0作除数将导致异常，而浮点除法中用0作除法将产生无穷或者NaN的结果。 &lt;p&gt;There is a convenient shortcut for using binary arithmetic operators in an assignment. For example, &lt;p&gt;在一条赋值语句中有一个使用二元算术运算的捷径。例如： &lt;p&gt;x += 4; &lt;p&gt;is equivalent to &lt;p&gt;等效于 &lt;p&gt;x = x + 4; &lt;p&gt;(In general, place the operator to the left of the = sign, such as *= or %=.) &lt;p&gt;（总之，就是把运算符放在等号的左边，例如*= 或者 %= 。） &lt;p&gt;&lt;a&gt;&lt;/a&gt;NOTE注释 &lt;p&gt;  &lt;p&gt;One of the stated goals of the Java programming language is portability. A computation should yield the same results no matter which virtual machine executes it. For arithmetic computations with floating-point numbers, it is surprisingly difficult to achieve this portability. The double type uses 64 bits to store a numeric value, but some processors use 80-bit floating-point registers. These registers yield added precision in intermediate steps of a computation. For example, consider the computation:&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;Java编程语言的一个初衷就是可移植性。对于一个运算应该产生相同的结果，无论何种虚拟机执行该运算。对于浮点数参与的算术运算，要实现这种可移植性是惊人的困难的。双精度类型的用64位存储一个数值，但是一些处理器使用的是80位浮点寄存器。这些寄存器在中等级别的计算中产生额外的精度。例如，考虑如下计算： &lt;p&gt;double w = x * y / z; &lt;p&gt;Many Intel processors compute x * y and leave the result in an 80-bit register, then divide by z and finally truncate the result back to 64 bits. That can yield a more accurate result, and it can avoid exponent overflow. But the result may be different from a computation that uses 64 bits throughout. For that reason, the initial specification of the Java virtual machine mandated that all intermediate computations must be truncated. The numeric community hated it. Not only can the truncated computations cause overflow, they are actually slower than the more precise computations because the truncation operations take time. For that reason, the Java programming language was updated to recognize the conflicting demands for optimum performance and perfect reproducibility. By default, virtual machine designers are now permitted to use extended precision for intermediate computations. However, methods tagged with the strictfp keyword must use strict floating-point operations that yield reproducible results. For example, you can tag main as &lt;p&gt;许多Intel处理器计算x*y并将结果存放于80位的寄存器中，然后除以z并最终将结果省略成64位的。那可以产生更为精确的结果，并可以避免指数溢出。但是完全使用64位计算将可能产生不同的结果。由于那个原因，起初Java虚拟机规格规定所有中间运算必须被舍掉多余的精度。数字团体厌恶这种处理方式。舍去操作不仅会引起溢出，而且由于舍去操作需要占用时间而花费了比精确计算更多的时间。由此，Java编程语言进行了升级，考虑了最适宜的性能和完美的再现性这两个互相冲突的要求。现在虚拟机设计者被许可使用扩展精度于中间级运算中。但是使用关键字strictfp标明的方法必须使用严格的浮点操作以产生有复验性的结果，例如，你可以标记main方法如下： &lt;p&gt;public static strictfp void main(String[] args) &lt;p&gt;Then all instructions inside the main method use strict floating-point computations. If you tag a class as strictfp, then all of its methods use strict floating-point computations. &lt;p&gt;于是main方法中的所有指令都采用严格的浮点运算。如果你标记一个类为strictfp，那么该类的所有方法都将使用严格的的浮点计算。 &lt;p&gt;The gory details are very much tied to the behavior of the Intel processors. In default mode, intermediate results are allowed to use an extended exponent, but not an extended mantissa. (The Intel chips support truncation of the mantissa without loss of performance.) Therefore, the only difference between default and strict mode is that strict computations may overflow when default computations don't.&lt;a&gt;&lt;/a&gt; &lt;p&gt;详细资料非常依赖于Intel处理器的表现。在默认模式下，中间结果被许可使用扩展指数，但不能使用扩展尾数。（Intel芯片支持不影响性能的情况下舍去尾数。）因此，默认模式和严格模式唯一的不同是严格计算可能引起溢出而默认模式不会。 &lt;p&gt;If your eyes glazed over when reading this note, don't worry. Floating-point overflow isn't a problem that one encounters for most common programs. We don't use the strictfp keyword in this book. &lt;p&gt;如果阅读此注释时你的眼睛变得迟钝，不要紧。浮点溢出对大多数普通编程而言并不是个能遇到的问题。在本书中我们不使用strictfp关键字。（汗：你既然用不着，说这么一大堆废话干啥？害得老子翻译了足足一个小时，还稀里糊涂的。）&lt;img src="http://c.services.spaces.live.com/CollectionWebService/c.gif?cid=-3743893519549122624&amp;page=RSS%3a+3.5.1+Operators%e8%bf%90%e7%ae%97%e7%ac%a6%e4%b9%8b%e7%ae%97%e6%9c%af%e8%bf%90%e7%ae%97%e7%ac%a6&amp;referrer=" width="1px" height="1px" border="0" alt=""&gt;&lt;img style="position:absolute" alt="" width="0px" height="0px" src="http://c.live.com/c.gif?NC=31263&amp;amp;NA=1149&amp;amp;PI=73329&amp;amp;RF=&amp;amp;DI=3919&amp;amp;PS=85545&amp;amp;TP=x-spirit.spaces.live.com&amp;amp;GT1=X-Spirit"&gt;</description><comments>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!304.entry#comment</comments><guid isPermaLink="true">http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!304.entry</guid><pubDate>Thu, 30 Aug 2007 04:33:00 GMT</pubDate><slash:comments>0</slash:comments><msn:type>blogentry</msn:type><live:type>blogentry</live:type><live:typelabel>Blog entry</live:typelabel><wfw:commentRss>http://X-Spirit.spaces.live.com/blog/cns!CC0B04AE126337C0!304/comments/feed.rss</wfw:commentRss><wfw:comment>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!304.entry#comment</wfw:comment><dcterms:modified>2007-08-30T04:33:18Z</dcterms:modified></item><item><title>3.4 Variables变量</title><link>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!300.entry</link><description>&lt;p&gt;   &lt;p&gt;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 examples:&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;在Java中，每个变量都有一个类型。你可以用把类型写在前面，后面紧跟变量名的方式来声明变量。下面是一些例子：  &lt;p&gt;double salary;  &lt;p&gt;int vacationDays;  &lt;p&gt;long earthPopulation;  &lt;p&gt;boolean done;  &lt;p&gt;Notice the semicolon at the end of each declaration. The semicolon is necessary because a declaration is a complete Java statement.  &lt;p&gt;注意每一个声明后面的分号。由于每个声明都是一条完整的Java语句，所以分号是必须写的。  &lt;p&gt;A variable name must begin with a letter and must be a sequence of letters or digits. Note that the terms &amp;quot;letter&amp;quot; and &amp;quot;digit&amp;quot; are much broader in Java than in most languages. A letter is defined as 'A'–'Z', 'a'–'z', '_', or any Unicode character that denotes a letter in a language. For example, German users can use umlauts such as 'ä' in variable names; Greek speakers could use a p. Similarly, digits 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.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;变量名必须以字母开头的一串字母或数字序列。注意，Java中所说的“字母”和“数字”比大多数编程语言要宽泛的多。字母是指'A'–'Z', 'a'–'z', '_',或者任何在某种语言中表示某个字母的Unicode字符。例如，德国人可以在变量名中使用元音变音'ä'；希腊人可以使用p。类似的，数字也是'0'–'9'或者任何在某种语言中表示一个数位的Unicode字符。诸如'+' or '©'此类的字符也不能被用于变量名，空格也不可以。所有的变量名中的字符乃至大小写都是有意义的。变量名的长度几乎是没有限制的。  &lt;p&gt;&lt;a&gt;&lt;/a&gt;TIP  &lt;p&gt;   &lt;p&gt;If you are really curious as to what Unicode characters are &amp;quot;letters&amp;quot; as far as Java is concerned, you can use the isJavaIdentifierStart and isJavaIdentifierPart methods in the Character class to check.&lt;a&gt;&lt;/a&gt;  &lt;p&gt;提示  &lt;p&gt;   &lt;p&gt;如果你真的像关心Java那样对于何种Unicode字符属于“字母”感到好奇的话，不妨用Character类中的isJavaIdentifierStart和isJavaIdentifierPart方法去检查。  &lt;p&gt;You also cannot use a Java reserved word for a variable name. (See &lt;a&gt;Appendix A&lt;/a&gt; for a list of reserved words.)  &lt;p&gt;你不能用Java保留字作为变量名。  &lt;p&gt;You can have multiple declarations on a single line:  &lt;p&gt;你可以在同一行声明多个变量：  &lt;p&gt;int i, j; // both are integers  &lt;p&gt;However, we don't recommend this style. If you declare each variable separately, your programs are easier to read.  &lt;p&gt;但是，我们并不推荐使用这种方式。如果你分别声明每一个变量，你的程序可读性更好。  &lt;p&gt;&lt;a&gt;&lt;/a&gt;NOTE  &lt;p&gt;   &lt;p&gt;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 of the type, such as&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;Box box; // ok--Box is the type and box is the variable name  &lt;p&gt;Other programmers prefer to use an &amp;quot;a&amp;quot; prefix for the variable:  &lt;p&gt;Box aBox;  &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;注释  &lt;p&gt;   &lt;p&gt;如你所见，命名是区分大小写的，例如，hireday和hireDay是两个不同的名字。通常，你不应该仅仅通过大小写来区分两个命名。但是，有时候很难给一个变量起一个好名字。很多程序员就用与类型名相同的名字来给变量命名，例如：  &lt;p&gt;Box box; // ok--Box 是个类型而 box 是变量名  &lt;p&gt;有的程序员喜欢给变量名加上一个“a”前缀：  &lt;p&gt;Box aBox;  &lt;p&gt;&lt;b&gt;Initializing Variables&lt;/b&gt;&lt;b&gt;变量初始化&lt;/b&gt;  &lt;p&gt;After you declare a variable, you must explicitly initialize it by means of an assignment statement—you can never use the values of uninitialized variables. For example, the Java compiler flags the following sequence of statements as an error:&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;声明变量以后，你必须明确的用一个赋值语句对其初始化——你绝不能够使用一个没有初始化的变量。例如，Java编译器将会标记如下语句为一个错误：  &lt;p&gt;int vacationDays;  &lt;p&gt;System.out.println(vacationDays); // ERROR--variable not initialized  &lt;p&gt;You assign to a previously declared variable by using the variable name on the left, an equal sign (=), and then some Java expression that has an appropriate value on the right.  &lt;p&gt;给变量赋值时，你可以把先前声明好的变量名写在左边，再写一个等号(=)，然后右边紧跟一些Java具有适当值的表达式。  &lt;p&gt;int vacationDays;  &lt;p&gt;vacationDays = 12;  &lt;p&gt;You can both declare and initialize a variable on the same line. For example:&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;你也可以把变量的声明和初始化写在一行，例如：  &lt;p&gt;int vacationDays = 12;  &lt;p&gt;Finally, in Java you can put declarations anywhere in your code. For example, the following is valid code in Java:  &lt;p&gt;最后要说明的，在Java中，你可以把变量的声明放在你代码的任何地方。比如，下面的代码在Java中是正确的：  &lt;p&gt;double salary = 65000.0;  &lt;p&gt;System.out.println(salary);  &lt;p&gt;int vacationDays = 12; // ok to declare a variable here  &lt;p&gt;In Java, it is considered good style to declare variables as closely as possible to the point where they are first used.  &lt;p&gt;在Java中，一种比较好的方式就是声明变量以后紧接着指出该变量第一次使用的位置。  &lt;p&gt;&lt;a&gt;&lt;/a&gt;C++ NOTE  &lt;p&gt;   &lt;p&gt;C and C++ distinguish between the declaration and definition of variables. For example,  &lt;p&gt;int i = 10;  &lt;p&gt;is a definition, whereas  &lt;p&gt;extern int i;  &lt;p&gt;is a declaration. In Java, no declarations are separate from definitions.  &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;C++ 附注  &lt;p&gt;   &lt;p&gt;C和C++中区分声明和定义。例如：  &lt;p&gt;int i = 10;  &lt;p&gt;是一个定义，而  &lt;p&gt;extern int i;  &lt;p&gt;是一个声明。在Java中，没有独立于定义的声明。  &lt;p&gt;&lt;b&gt;Constants&lt;/b&gt;&lt;b&gt;常量&lt;/b&gt;  &lt;p&gt;In Java, you use the keyword final to denote a constant. For example,&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;在Java中，你可以用关键字final来指明一个常量，例如：  &lt;p&gt;public class Constants  &lt;p&gt;{  &lt;p&gt;public static void main(String[] args)  &lt;p&gt;{  &lt;p&gt;final double CM_PER_INCH = 2.54;  &lt;p&gt;double paperWidth = 8.5;  &lt;p&gt;double paperHeight = 11;  &lt;p&gt;System.out.println(&amp;quot;Paper size in centimeters: &amp;quot;  &lt;p&gt;+ paperWidth * CM_PER_INCH + &amp;quot; by &amp;quot; + paperHeight * CM_PER_INCH);  &lt;p&gt;}  &lt;p&gt;}  &lt;p&gt;The keyword final indicates that you can assign to the variable once, and then its value is set once and for all. It is customary to name constants in all upper case.  &lt;p&gt;关键字final指出你可以给变量赋值一次，而其值也只能设置一次。通常习惯上将常量名全部大写。  &lt;p&gt;It is probably more common in Java to want a constant that is available to multiple methods inside a single class. These are usually called class constants. You set up a class constant with the keywords static final. Here is an example of using a class constant:&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;  &lt;p&gt;在Java中，我们或许更多时候需要一个能被一个类中的多个方法使用的常量。这种常量被称之为类常量。类常量用关键字static final来设置。下面是一个使用类常量的例子：  &lt;p&gt;public class Constants2  &lt;p&gt;{  &lt;p&gt;public static void main(String[] args)  &lt;p&gt;{  &lt;p&gt;double paperWidth = 8.5;  &lt;p&gt;double paperHeight = 11;  &lt;p&gt;System.out.println(&amp;quot;Paper size in centimeters: &amp;quot;  &lt;p&gt;+ paperWidth * CM_PER_INCH + &amp;quot; by &amp;quot; + paperHeight * CM_PER_INCH);  &lt;p&gt;}  &lt;p&gt;public static final double CM_PER_INCH = 2.54;  &lt;p&gt;}  &lt;p&gt;Note that the definition of the class constant appears outside the main method. Thus, the constant can also be used in other methods of the same class. Furthermore, if (as in our example) the constant is declared public, methods of other classes can also use the constant—in our example, as Constants2.CM_PER_INCH.  &lt;p&gt;注意到对类常量的定义出现在了主方法的外面。正因为如此，类常量也可以被同类的其他方法访问。此外，如果（如我们的例子）常量被声明为public，那么其他类的方法也可以使用这个常量——在我们的例子中，就像Constants2中的CM_PER_INCH一样。  &lt;p&gt;&lt;a&gt;&lt;/a&gt;C++ NOTE  &lt;p&gt;   &lt;p&gt;const is a reserved Java keyword, but it is not currently used for anything. You must use final for a constant.  &lt;p&gt;C++ 注释  &lt;p&gt;   &lt;p&gt;const是一个Java预留的关键字，但是现在不再用于任何场合。你必须使用final来定义常量。&lt;img src="http://c.services.spaces.live.com/CollectionWebService/c.gif?cid=-3743893519549122624&amp;page=RSS%3a+3.4+Variables%e5%8f%98%e9%87%8f&amp;referrer=" width="1px" height="1px" border="0" alt=""&gt;&lt;img style="position:absolute" alt="" width="0px" height="0px" src="http://c.live.com/c.gif?NC=31263&amp;amp;NA=1149&amp;amp;PI=73329&amp;amp;RF=&amp;amp;DI=3919&amp;amp;PS=85545&amp;amp;TP=x-spirit.spaces.live.com&amp;amp;GT1=X-Spirit"&gt;</description><comments>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!300.entry#comment</comments><guid isPermaLink="true">http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!300.entry</guid><pubDate>Tue, 28 Aug 2007 11:37:00 GMT</pubDate><slash:comments>0</slash:comments><msn:type>blogentry</msn:type><live:type>blogentry</live:type><live:typelabel>Blog entry</live:typelabel><wfw:commentRss>http://X-Spirit.spaces.live.com/blog/cns!CC0B04AE126337C0!300/comments/feed.rss</wfw:commentRss><wfw:comment>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!300.entry#comment</wfw:comment><dcterms:modified>2007-08-28T11:38:04Z</dcterms:modified></item><item><title>3.3  Data Types数据类型</title><link>http://X-Spirit.spaces.live.com/Blog/cns!CC0B04AE126337C0!289.entry</link><description>&lt;p&gt;Java is a strongly typed language. This means that every variable must have a declared type. There are eight primitive types in Java. Four of them are integer types; two are floating-point number types; one is the character type char, used for code units in the Unicode encoding scheme (see the section on &lt;a&gt;the char type&lt;/a&gt;); and one is a boolean type for truth values.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;Java是一种强类型语言。这意味着每个变量必须声明类型。Java中有八种原始类型。其中4种是整数类型；两种是浮点数类型；一种是字符类型char，适用于Unicode编码方案中的代码单元（参见本节中的char类型小节）；还有一种是用来表示真值的布尔类型。 &lt;p&gt;&lt;a&gt;&lt;/a&gt;NOTE注释 &lt;p&gt;  &lt;p&gt;Java has an arbitrary precision arithmetic package. However, &amp;quot;big numbers,&amp;quot; as they are called, are Java objects and not a new Java type. You see how to use them later in this chapter. &lt;p&gt;Java有一个任意精度的算术包。顾名思义，“大数”是一个Java对象，而并非新的Java类型。你将在本章后面看到如何使用它们。 &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;h6&gt;Integers整数&lt;/h6&gt; &lt;p&gt;The integer types are for numbers without fractional parts. Negative values are allowed. Java provides the four integer types shown in &lt;a&gt;Table 3-1&lt;/a&gt;.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;整数类型是四种无小数部分的数字，允许负值。Java提供表3-1所示的四种整数类型。 &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;Table 3-1. Java Integer Types&lt;/b&gt; &lt;p&gt;&lt;b&gt;类型&lt;/b&gt;&lt;b&gt;&lt;/b&gt; &lt;p&gt;&lt;b&gt;存储空间&lt;/b&gt;&lt;b&gt;&lt;/b&gt; &lt;p&gt;&lt;b&gt;范围（闭区间）&lt;/b&gt;&lt;b&gt;&lt;/b&gt; &lt;p&gt;Int&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;4 字节 &lt;p&gt;–2,147,483,648 to 2,147,483, 647 (超过20亿) &lt;p&gt;Short &lt;p&gt;2字节 &lt;p&gt;–32,768 to 32,767 &lt;p&gt;Long &lt;p&gt;8字节 &lt;p&gt;–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 &lt;p&gt;Byte &lt;p&gt;1字节 &lt;p&gt;–128 to 127 &lt;p&gt;In most situations, the int type is the most practical. If you want to represent the number of inhabitants of our planet, you'll need to resort to a long. The byte and short types are mainly intended for specialized applications, such as low-level file handling, or for large arrays when storage space is at a premium. &lt;p&gt;大多数情况下，int类型是最实用的。如果你想表示我们星球上居民的数量，你就需要诉诸于long类型。Byte和short类型主要用于一些特殊的应用，比如较低级的文件处理，或者当存储空间非常珍贵的时候处理大的数组。 &lt;p&gt;Under Java, the ranges of the integer types do not depend on the machine on which you will be running the Java code. This alleviates a major pain for the programmer who wants to move software from one platform to another, or even between operating systems on the same platform. In contrast, C and C++ programs use the most efficient integer type for each processor. As a result, a C program that runs well on a 32-bit processor may exhibit integer overflow on a 16-bit system. Because Java programs must run with the same results on all machines, the ranges for the various types are fixed.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;Long integer numbers have a suffix L (for example, 4000000000L). Hexadecimal numbers have a prefix 0x (for example, 0xCAFE). Octal numbers have a prefix 0. For example, 010 is 8. Naturally, this can be confusing, and we recommend against the use of octal constants.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;在Java中，整数类型的范围不取决于你运行Java代码的机器。这避免了将软件在两个平台或者在同一平台上的两个操作系统之间转移而带来的主要麻烦。与之相反的是，C和C++程序对每个处理器使用最有效的整数类型。造成的结果就是，一个C程序在一个32位处理器上运行良好而在一个16位系统中可能表现出整数溢出。因为Java程序必须保证在所有的机器上运行得到相同的结果，不同类型的范围是固定的。长整型数字有一个L后缀（例如4000000000L）。十六位数字有一个0x前缀（例如，0xCAFE）。八进制数字有一个0前缀。例如，010就是8。当然，这可能导致混淆，所以我们建议避免使用八进制数。 &lt;p&gt;&lt;a&gt;&lt;/a&gt;C++ NOTE C++注释 &lt;p&gt;  &lt;p&gt;In C and C++, int denotes the integer type that depends on the target machine. On a 16-bit processor, like the 8086, integers are 2 bytes. On a 32-bit processor like the Sun SPARC, they are 4-byte quantities. On an Intel Pentium, the integer type of C and C++ depends on the operating system: for DOS and Windows 3.1, integers are 2 bytes. When 32-bit mode is used for Windows programs, integers are 4 bytes. In Java, the sizes of all numeric types are platform independent. &lt;p&gt;Note that Java does not have any unsigned types.&lt;a&gt;&lt;/a&gt; &lt;p&gt;在C和C++中，int表示的整数类型取决于目标机。在16位处理器上，例如8086机，整数占用2字节。在32位处理器，例如Sun公司的SPARC，整数占用4字节。在Intel奔腾上，C和C++的整数类型取决于操作系统：对于DOS和Windows3.1，整数是2字节。当Windows程序使用32位模式时，整数占用4字节。在Java中，一切数字类型的大小都是平台无关的。注意，Java没有任何无符号类型。 &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;h6&gt;Floating-Point Types浮点类型&lt;/h6&gt; &lt;p&gt;The floating-point types denote numbers with fractional parts. The two floating-point types are shown in &lt;a&gt;Table 3-2&lt;/a&gt;.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;浮点类型表示的数字含有小数部分。表3-2显示了两种浮点类型。 &lt;p&gt;&lt;a&gt;&lt;/a&gt;&lt;b&gt;Table 3-2. Floating-Point Types&lt;/b&gt; &lt;p&gt;类型 &lt;p&gt;存储空间 &lt;p&gt;范围 &lt;p&gt;float&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;4字节 &lt;p&gt;大约 ±3.40282347E+38F (6–7 个有效十进制位) &lt;p&gt;double &lt;p&gt;8字节 &lt;p&gt;大约 ±1.79769313486231570E+308 (15个有效十进制位) &lt;p&gt;The name double refers to the fact that these numbers have twice the precision of the float type. (Some people call these double-precision numbers.) Here, the type to choose in most applications is double. The limited precision of float is simply not sufficient for many situations. Seven significant (decimal) digits may be enough to precisely express your annual salary in dollars and cents, but it won't be enough for your company president's salary. The only reasons to use float are in the rare situations in which the slightly faster processing of single-precision numbers is important or when you need to store a large number of them.&lt;a&gt;&lt;/a&gt; &lt;p&gt;Numbers of type float have a suffix F (for example, 3.402F). Floating-point numbers without an F suffix (such as 3.402) are always considered to be of type double. You can optionally supply the D suffix (for example, 3.402D).&lt;a&gt;&lt;/a&gt; &lt;p&gt;Double这个名字说明该类型具有两倍于float类型的精度。（有人将之称为双精度数字。）这里，大多数应用程序选择double类型。Float类型有限的精度对于许多情况都是不足的。七个有效的十进制位也许用来以美元和美分的单位表示你的年薪还是足够的，但是用来表示你公司老总的薪水就显得不够了。仅当极少数需要对单精度数字进行敏捷的处理或者需要存储大量单精度数字的时候，才有理由使用float类型。 &lt;p&gt;As of JDK 5.0, you can specify floating-point numbers in hexadecimal. For example, 0.125 is the same as 0x1.0p-3. In hexadecimal notation, you use a p, not an e, to denote the exponent.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;从JDK5.0起，你可以指定十六进制的浮点数字。例如，0.125就等同于0x1.0p-3。在十六进制符号中，采用p而非e来表示指数。 &lt;p&gt;All floating-point computations follow the IEEE 754 specification. In particular, there are three special floating-point values: &lt;p&gt;positive infinity&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;negative infinity &lt;p&gt;NaN (not a number) &lt;p&gt;to denote overflows and errors. For example, the result of dividing a positive number by 0 is positive infinity. Computing 0/0 or the square root of a negative number yields NaN.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;所有浮点计算遵循IEEE 754规范。特别的，有三种特殊的浮点值： &lt;p&gt;positive infinity正无穷 &lt;p&gt;negative infinity负无穷 &lt;p&gt;NaN (非数字) &lt;p&gt;来表示溢出和错误。例如，将一个正数除以0得到的结果就是正无穷。0/0或者负数的平方根就是NaN。 &lt;p&gt;&lt;a&gt;&lt;/a&gt;NOTE注释 &lt;p&gt;  &lt;p&gt;The constants Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, and Double.NaN (as well as corresponding Float constants) represent these special values, but they are rarely used in practice. In particular, you cannot test &lt;p&gt;if (x == Double.NaN) // is never true &lt;p&gt;to check whether a particular result equals Double.NaN. All &amp;quot;not a number&amp;quot; values are considered distinct. However, you can use the Double.isNaN method:&lt;a&gt;&lt;/a&gt; &lt;p&gt;if (Double.isNaN(x)) // check whether x is &amp;quot;not a number&amp;quot; &lt;p&gt;常量Double.POSITIVE_INFINITY、Double.NEGATIVE_INFINITY、Double.NaN（以及相应的Float常量）表示以上特殊值。但它们在实际应用中非常少用。特别的，你无法测试 &lt;p&gt;if(x==Double.NaN)//永不为真 &lt;p&gt;来检查实际结果是否等于Double.NaN。所有“非数字”值被归为独特的。但是你可以使用Double.isNaN方法。 &lt;p&gt;if (Double.isNaN(x)) // 检测x是否是“非数字”。 &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;CAUTION注意 &lt;p&gt;  &lt;p&gt;Floating-point numbers are not suitable for financial calculation in which roundoff errors cannot be tolerated. For example, the command System.out.println(2.0 - 1.1) prints 0.8999999999999999, not 0.9 as you would expect. Such roundoff errors are caused by the fact that floating-point numbers are represented in the binary number system. There is no precise binary representation of the fraction 1/10, just as there is no accurate representation of the fraction 1/3 in the decimal system. If you need precise numerical computations without roundoff errors, use the BigDecimal class, which is introduced later in this chapter.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;浮点数字在不能容忍循环错误的财政计算中是不合适的。例如，System.out.println(2.0 - 1.1) 命令打印出 0.8999999999999999, 而非你期望得到的0.9。这种循环错误是由于在二进制系统中表示浮点数而引起的。对于分数1/10没有精确的二进制表示，正如对于分数1/3没有精确的十进制表示一样。如果你需要没有循环错误的精确数值计算，请使用BigDecimal类，这将在本章稍后介绍。 &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;h6&gt;The char Type char类型&lt;/h6&gt; &lt;p&gt;To understand the char type, you have to know about the Unicode encoding scheme. Unicode was invented to overcome the limitations of traditional character encoding schemes. Before Unicode, there were many different standards: ASCII in the United States, ISO 8859-1 for Western European languages, KOI-8 for Russian, GB18030 and BIG-5 for Chinese, and so on. This causes two problems. A particular code value corresponds to different letters in the various encoding schemes. Moreover, the encodings for languages with large character sets have variable length: some common characters are encoded as single bytes, others require two or more bytes.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;要理解char类型，你需要了解Unicode编码规则。Unicode是为克服传统字符编码规则的局限性而发明的。在Unicode之前，有许多标准：美国的ASCII、西欧语言的ISO 8859-1、俄语使用的KOI-8、中文使用的GB18030 和 BIG-5等等。这造成了两个问题。一个特定的码值在不同的编码规则中对应于不同的字母。此外，大字符集的语言使用的编码具有可变的长度：一些普通的字符以单字节编码，而其余的需要两个或更多字节。 &lt;p&gt;Unicode was designed to solve these problems. When the unification effort started in the 1980s, a fixed 2-byte width code was more than sufficient to encode all characters used in all languages in the world, with room to spare for future expansion—or so everyone thought at the time. In 1991, Unicode 1.0 was released, using slightly less than half of the available 65,536 code values. Java was designed from the ground up to use 16-bit Unicode characters, which was a major advance over other programming languages that used 8-bit characters.&lt;a&gt;&lt;/a&gt; &lt;p&gt;Unicode的初衷就是解决这个问题。在统一化进程始于20世纪80年代的时候，一个定长的两字节码已经足够对世界上所有语言中的所有字符进行编码，剩下的空间还可以用于将来的扩展——大概当初每个人都是这样认为的。1991年，Unicode 1.0诞生了，仅使用了全部可用65536个码值中的一半。Java被设计为完全采用16位Unicode字符，这是Java优于其他采用8位字符的一个主要优点。 &lt;p&gt;Unfortunately, over time, the inevitable happened. Unicode grew beyond 65,536 characters, primarily due to the addition of a very large set of ideographs used for Chinese, Japanese, and Korean. Now, the 16-bit char type is insufficient to describe all Unicode characters.&lt;a&gt;&lt;/a&gt; &lt;p&gt;We need a bit of terminology to explain how this problem is resolved in Java, beginning with JDK 5.0. A code point is a code value that is associated with a character in an encoding scheme. In the Unicode standard, code points are written in hexadecimal and prefixed with U+, such as U+0041 for the code point of the letter A. Unicode has code points that are grouped into 17 code planes. The first code plane, called the basic multilingual plane, consists of the &amp;quot;classic&amp;quot; Unicode characters with code points U+0000 to U+FFFF. Sixteen additional planes, with code points U+10000 to U+10FFFF, hold the supplementary characters.&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;不幸的是，随着时间的过去，不可避免的事情发生了。Unicode超过了65535个字符，主要是由于像中文、日文、韩文这样的大量的象形文字的加入而造成的。现在，16位char类型已经不足以描述所有Unicode字符。 &lt;p&gt;我们需要使用一点术语来解释这个问题在Java中，从JDK5.0开始是如何得以解决的。一个代码点就是一个编码规则中与一个字符相关联的码值。在Unicode标准中，代码点是用16进制写成，加上U+前缀，例如U+0041就是字母A的代码点。Unicode的代码点被分成17个代码组。第一个代码组叫做基本多语言组，是由采用U+0000至U+FFFF代码点的“经典”Unicode字符组成。额外的16个代码组，代码点从U+10000至U+10FFFF，保存辅助字符。 &lt;p&gt;The UTF-16 encoding is a method of representing all Unicode code points in a variable length code. The characters in the basic multilingual plane are represented as 16-bit values, called code units. The supplementary characters are encoded as consecutive pairs of code units. Each of the values in such an encoding pair falls into an unused 2048-byte range of the basic multilingual plane, called the surrogates area (U+D800 to U+DBFF for the first code unit, U+DC00 to U+DFFF for the second code unit).This is rather clever, because you can immediately tell whether a code unit encodes a single character or whether it is the first or second part of a supplementary character. For example, the mathematical symbol for the set of integers has code point U+1D56B and is encoded by the two code units U+D835 and U+DD6B. (See &lt;a href="http://en.wikipedia.org/wiki/UTF-16"&gt;http://en.wikipedia.org/wiki/UTF-16&lt;/a&gt; for a description of the encoding algorithm.)&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;UTF-16编码是一种以变长编码表示所有Unicode代码点的方法。基本多语言组中的字符以16位值表示，叫做代码单元。辅助字符以连续的代码单元对编码。这样一个编码对中的每个值就属于一个未占用的2048字节的基本多语言组范围，称作代理区域（U+D800至U+DBFF 表示第一个代码单元, U+DC00至U+DFFF表示第二个代码单元）。这是相当明智的，因为你可以立即说出一个代码单元是否对一个单字符进行编码或者它是辅助字符的第一部分还是第二部分。例如，整数集的算术符号的代码点为U+1D56B，它是由两个代码单元U+D835和U+DD6B编码而成。（参见&lt;a href="http://en.wikipedia.org/wiki/UTF-16"&gt;http://en.wikipedia.org/wiki/UTF-16&lt;/a&gt;获得有关编码算法的描述） &lt;p&gt;In Java, the char type describes a code unit in the UTF-16 encoding. &lt;p&gt;Our strong recommendation is not to use the char type in your programs unless you are actually manipulating UTF-16 code units. You are almost always better off treating strings as abstract data types.&lt;a&gt;&lt;/a&gt; &lt;p&gt;Java中，char类型描述UTF-16编码中的一个代码单元。 &lt;p&gt;我们强烈建议在程序中避免使用char类型，除非你对UTF-16代码单元十分熟练。你几乎总是将字符串视为抽象数据类型即可。 &lt;p&gt;Having said that, there will be some cases when you will encounter char values. Most commonly, these will be character constants. For example, 'A' is a character constant with value 65. It is different from &amp;quot;A&amp;quot;, a string containing a single character. Unicode code units can be expressed as hexadecimal values that run from \u0000 to \uFFFF. For example, \u2122 is the trademark symbol (™) and \u03C0 is the Greek letter pi (p).&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;尽管如上所述，但是有时候你也会遇到char值。最常见的就是字符常量。例如，‘A’是一个值为65的字符常量。它与“A”这个仅包含一个字符的字符串不同。Unicode代码单元可被表示成从\u0000到\uFFFF的十六进制值。例如，\u2122是商标符号(™) 而 \u03C0 是希腊字母 (p). &lt;p&gt;Besides the \u escape sequences that indicate the encoding of Unicode code units, there are several escape sequences for special characters, as shown in &lt;a&gt;Table 3-3&lt;/a&gt;. You can use these escape sequences inside quoted character constants and strings, such as '\u2122' or &amp;quot;Hello\n&amp;quot;. The \u escape sequence (but none of the other escape sequences) can even be used outside quoted character constants and strings. For example,&lt;a&gt;&lt;/a&gt; &lt;p&gt;public static void main(String\5B\5D args) &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;除了用\u转义符来表示Unicode代码单元的编码，还有一些特殊的转义符来表示特殊字符，如表3-3所示。你可以在用引号引起来的字符常量和字符串中使用这些转义符，例如'\u2122'或&amp;quot;Hello\n&amp;quot;。\u转义符（但其他转义符除外）甚至可以在引号引起来的字符常量和字符串外使用。例如：public static void main(String\5B\5D args) &lt;p&gt;&lt;b&gt;Table 3-3. Escape Sequences for Special Characters&lt;/b&gt; &lt;p&gt;Escape Sequence&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;Name &lt;p&gt;Unicode Value &lt;p&gt;\b &lt;p&gt;退格 &lt;p&gt;\u0008 &lt;p&gt;\t &lt;p&gt;Tab &lt;p&gt;\u0009 &lt;p&gt;\n &lt;p&gt;换行 &lt;p&gt;\u000a &lt;p&gt;\r &lt;p&gt;回车 &lt;p&gt;\u000d &lt;p&gt;\&amp;quot; &lt;p&gt;双引号 &lt;p&gt;\u0022 &lt;p&gt;\' &lt;p&gt;单引号 &lt;p&gt;\u0027 &lt;p&gt;\\ &lt;p&gt;反斜线 &lt;p&gt;\u005c &lt;p&gt;is perfe